import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Between, In } from 'typeorm';
import { Member } from '../../entities/Member';
import { MemberLevel } from '../../entities/MemberLevel';
import { MemberAddress } from '../../entities/MemberAddress';
import { CoreMemberService } from '../core/CoreMemberService';
import * as bcrypt from 'bcrypt';
import { CreateMemberDto, UpdateMemberDto } from '../../dto/member.dto';

@Injectable()
export class MemberService {
  constructor(
    @InjectRepository(Member)
    private memberRepository: Repository<Member>,
    @InjectRepository(MemberLevel)
    private memberLevelRepository: Repository<MemberLevel>,
    @InjectRepository(MemberAddress)
    private memberAddressRepository: Repository<MemberAddress>,
    private memberCoreService: CoreMemberService,
  ) {}

  /**
   * 获取会员列表（分页）
   */
  async getMemberList(queryDto: any): Promise<any> {
    const { 
      page = 1, 
      limit = 20, 
      keyword, 
      status, 
      level_id, 
      start_date, 
      end_date,
      site_id = 0 
    } = queryDto;
    
    const queryBuilder = this.memberRepository.createQueryBuilder('member')
      .leftJoinAndSelect('member.level', 'level')
      .where('member.is_delete = :isDelete', { isDelete: 0 })
      .orderBy('member.register_time', 'DESC');

    // 站点筛选
    if (site_id > 0) {
      queryBuilder.andWhere('member.site_id = :siteId', { siteId: site_id });
    }

    // 关键词搜索
    if (keyword) {
      queryBuilder.andWhere(
        '(member.username LIKE :keyword OR member.nickname LIKE :keyword OR member.mobile LIKE :keyword OR member.email LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    // 状态筛选
    if (status !== undefined && status !== '') {
      queryBuilder.andWhere('member.status = :status', { status });
    }

    // 等级筛选
    if (level_id) {
      queryBuilder.andWhere('member.level_id = :levelId', { levelId: level_id });
    }

    // 日期范围筛选
    if (start_date && end_date) {
      queryBuilder.andWhere('member.register_time BETWEEN :startDate AND :endDate', {
        startDate: new Date(start_date),
        endDate: new Date(end_date),
      });
    }

    const [members, total] = await queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .getManyAndCount();

    return {
      list: members,
      total,
      page,
      limit,
      total_pages: Math.ceil(total / limit),
    };
  }

  /**
   * 获取会员详情
   */
  async getMemberDetail(memberId: number): Promise<Member> {
    const member = await this.memberRepository.findOne({
      where: { member_id: memberId, is_del: 0 },
      relations: ['level', 'addresses', 'labels', 'accounts'],
    });

    if (!member) {
      throw new NotFoundException('会员不存在');
    }

    return member;
  }

  async createMember(memberData: CreateMemberDto): Promise<Member> {
    // 检查用户名是否已存在
    const exists = await this.memberCoreService.isUsernameExists(memberData.username);
    if (exists) {
      throw new Error('用户名已存在');
    }

    // 创建会员
    const member = await this.memberCoreService.createMember(memberData);
    
    // 创建会员地址
    if (memberData.addresses && memberData.addresses.length > 0) {
      for (const addressData of memberData.addresses) {
        await this.createMemberAddress(member.member_id, addressData);
      }
    }

    return member;
  }

  async updateMember(memberId: number, updateData: UpdateMemberDto): Promise<Member> {
    // 检查会员是否存在
    const member = await this.memberCoreService.getMemberById(memberId);
    if (!member) {
      throw new NotFoundException('会员不存在');
    }

    // 更新会员信息
    const updatedMember = await this.memberCoreService.updateMember(memberId, updateData);

    // 更新会员地址
    if (updateData.addresses !== undefined) {
      await this.updateMemberAddresses(memberId, updateData.addresses);
    }

    if (!updatedMember) {
      throw new Error('更新后的会员不存在');
    }
    return updatedMember;
  }

  async deleteMember(memberId: number): Promise<void> {
    // 检查会员是否存在
    const member = await this.memberCoreService.getMemberById(memberId);
    if (!member) {
      throw new NotFoundException('会员不存在');
    }

    // 删除会员
    await this.memberCoreService.deleteMember(memberId);
    
    // 删除相关数据
    await this.deleteMemberRelatedData(memberId);
  }

  async batchDeleteMembers(memberIds: number[]): Promise<void> {
    for (const memberId of memberIds) {
      await this.deleteMember(memberId);
    }
  }

  /**
   * 更新会员状态
   */
  async updateMemberStatus(memberId: number, status: number): Promise<void> {
    await this.memberRepository.update(memberId, { status });
  }

  /**
   * 批量更新会员状态
   */
  async batchUpdateMemberStatus(memberIds: number[], status: number): Promise<void> {
    await this.memberRepository.update(memberIds, { status });
  }

  /**
   * 重置会员密码
   */
  async resetMemberPassword(memberId: number, newPassword: string): Promise<void> {
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    await this.memberRepository.update(memberId, { password: hashedPassword });
  }

  /**
   * 分配会员等级
   */
  async assignMemberLevel(memberId: number, levelId: number): Promise<void> {
    await this.memberRepository.update(memberId, { member_level: levelId });
  }

  async batchAssignMemberLevel(memberIds: number[], levelId: number): Promise<void> {
    for (const memberId of memberIds) {
      await this.assignMemberLevel(memberId, levelId);
    }
  }

  /**
   * 调整会员积分
   */
  async adjustMemberPoints(memberId: number, points: number, reason: string): Promise<void> {
    if (points > 0) {
      await this.memberCoreService.addPoints(memberId, points);
    } else {
      await this.memberCoreService.deductPoints(memberId, Math.abs(points));
    }

    // 记录积分变动日志
    // 这里可以调用积分日志服务记录变动历史
  }

  /**
   * 调整会员余额
   */
  async adjustMemberBalance(memberId: number, amount: number, reason: string): Promise<void> {
    if (amount > 0) {
      await this.memberCoreService.addBalance(memberId, amount);
    } else {
      await this.memberCoreService.deductBalance(memberId, Math.abs(amount));
    }

    // 记录余额变动日志
    // 这里可以调用余额日志服务记录变动历史
  }

  /**
   * 获取会员统计信息
   */
  async getMemberStats(siteId: number = 0): Promise<any> {
    const where: any = { is_del: 0 };
    if (siteId > 0) {
      where.site_id = siteId;
    }

    const totalMembers = await this.memberRepository.count({ where });
    const activeMembers = await this.memberRepository.count({ 
      where: { ...where, status: 1 } 
    });
    
    const todayNewMembers = await this.memberRepository.count({
      where: {
        ...where,
        register_time: {
          gte: new Date(new Date().setHours(0, 0, 0, 0)),
          lt: new Date(new Date().setHours(23, 59, 59, 999)),
        },
      },
    });

    const thisMonthNewMembers = await this.memberRepository.count({
      where: {
        ...where,
        register_time: {
          gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
          lt: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0),
        },
      },
    });

    return {
      total: totalMembers,
      active: activeMembers,
      today_new: todayNewMembers,
      this_month_new: thisMonthNewMembers,
      inactive: totalMembers - activeMembers,
    };
  }

  /**
   * 导出会员数据
   */
  async exportMembers(queryDto: any): Promise<any> {
    // TODO: 实现导出功能
    const members = await this.getMemberList({ ...queryDto, limit: 10000 });
    return members.list;
  }

  /**
   * 导入会员数据
   */
  async importMembers(importData: any[]): Promise<any> {
    // TODO: 实现导入功能
    const results = {
      success: 0,
      failed: 0,
      errors: [] as Array<{row: any, error: string}>,
    };

    for (const data of importData) {
      try {
        await this.createMember(data);
        results.success++;
      } catch (error) {
        results.failed++;
        results.errors.push({
          row: data,
          error: error.message,
        });
      }
    }

    return results;
  }

  /**
   * 创建会员地址
   */
  async createMemberAddress(memberId: number, addressData: any): Promise<any> {
    // 实现创建会员地址逻辑
    const address = {
      member_id: memberId,
      ...addressData,
      create_time: new Date(),
      update_time: new Date(),
    };
    return await this.memberAddressRepository.save(address);
  }

  /**
   * 更新会员地址
   */
  async updateMemberAddresses(memberId: number, addresses: any[]): Promise<void> {
    // 实现更新会员地址逻辑
    for (const addressData of addresses) {
      if (addressData.address_id) {
        await this.memberAddressRepository.update(addressData.address_id, {
          ...addressData,
          update_time: new Date(),
        });
      }
    }
  }

  /**
   * 删除会员相关数据
   */
  async deleteMemberRelatedData(memberId: number): Promise<void> {
    // 实现删除会员相关数据逻辑
    await this.memberAddressRepository.delete({ member_id: memberId });
    // 可以添加其他相关数据的删除逻辑
  }
} 