import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, Between } from 'typeorm';
import { Member } from '../../entities/Member';
import { MemberLevel } from '../../entities/MemberLevel';
import * as bcrypt from 'bcrypt';

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

  /**
   * 创建会员
   */
  async create(createMemberDto: any): Promise<Member> {
    const member = new Member();
    
    // 生成会员编号
    member.member_no = await this.generateMemberNo();
    
    // 加密密码
    member.password = await bcrypt.hash(createMemberDto.password, 10);
    
    // 设置其他字段
    Object.assign(member, createMemberDto);
    
    return this.memberRepository.save(member);
  }

  /**
   * 创建会员
   */
  async createMember(memberData: any): Promise<Member> {
    const member = this.memberRepository.create(memberData);
    return await this.memberRepository.save(memberData);
  }

  /**
   * 根据ID获取会员
   */
  async getMemberById(memberId: number): Promise<Member | null> {
    return await this.memberRepository.findOne({
      where: { member_id: memberId, is_del: 0 },
    });
  }

  /**
   * 更新会员
   */
  async updateMember(memberId: number, updateData: any): Promise<Member | null> {
    await this.memberRepository.update(memberId, updateData);
    return await this.getMemberById(memberId);
  }

  /**
   * 删除会员
   */
  async deleteMember(memberId: number): Promise<void> {
    await this.memberRepository.update(memberId, {
      is_del: 1,
      delete_time: Math.floor(Date.now() / 1000),
    });
  }

  /**
   * 根据ID查找会员
   */
  async findById(memberId: number): Promise<Member> {
    const member = await this.memberRepository.findOne({
      where: { member_id: memberId, is_del: 0 },
      relations: ['level', 'addresses', 'labels'],
    });

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

    return member;
  }

  /**
   * 根据用户名查找会员
   */
  async findByUsername(username: string): Promise<Member | null> {
    return await this.memberRepository.findOne({ 
      where: { username, is_del: 0 } 
    });
  }

  /**
   * 根据手机号查找会员
   */
  async findByMobile(mobile: string): Promise<Member | null> {
    return await this.memberRepository.findOne({ 
      where: { mobile, is_del: 0 } 
    });
  }

  /**
   * 根据邮箱查找会员
   */
  async findByEmail(email: string): Promise<Member | null> {
    return await this.memberRepository.findOne({ 
      where: { is_del: 0 } 
    });
  }

  /**
   * 根据关键词查找会员
   */
  async findByKeyword(keyword: string): Promise<Member[]> {
    return this.memberRepository.find({
      where: [
        { username: keyword, is_del: 0 },
        { mobile: keyword, is_del: 0 },
        { nickname: keyword, is_del: 0 },
        { nickname: keyword, is_del: 0 },
      ],
    });
  }

  /**
   * 更新会员
   */
  async update(memberId: number, updateDto: any): Promise<void> {
    const member = await this.findById(memberId);
    
    // 不允许更新敏感字段
    delete updateDto.member_id;
    delete updateDto.member_no;
    delete updateDto.site_id;
    delete updateDto.register_time;
    
    await this.memberRepository.update(memberId, updateDto);
  }

  /**
   * 删除会员（软删除）
   */
  async remove(memberId: number): Promise<void> {
    await this.memberRepository.update(memberId, { is_del: 1 });
  }

  /**
   * 验证密码
   */
  async validatePassword(member: Member, password: string): Promise<boolean> {
    return bcrypt.compare(password, member.password);
  }

  /**
   * 生成会员编号
   */
  private async generateMemberNo(): Promise<string> {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    // 查询当天注册的会员数量
    const todayStart = Math.floor(new Date(year, date.getMonth(), date.getDate()).getTime() / 1000);
    const todayEnd = Math.floor(new Date(year, date.getMonth(), date.getDate() + 1).getTime() / 1000);
    const todayCount = await this.memberRepository.count({
      where: {
        create_time: Between(todayStart, todayEnd),
        is_del: 0,
      },
    });
    
    const sequence = String(todayCount + 1).padStart(4, '0');
    return `M${year}${month}${day}${sequence}`;
  }

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

  /**
   * 增加积分
   */
  async addPoints(memberId: number, points: number): Promise<void> {
    await this.memberRepository.increment({ member_id: memberId }, 'point', points);
  }

  /**
   * 扣除积分
   */
  async deductPoints(memberId: number, points: number): Promise<void> {
    await this.memberRepository.decrement({ member_id: memberId }, 'point', points);
  }

  /**
   * 增加余额
   */
  async addBalance(memberId: number, amount: number): Promise<void> {
    await this.memberRepository.increment({ member_id: memberId }, 'balance', amount);
  }

  /**
   * 扣除余额
   */
  async deductBalance(memberId: number, amount: number): Promise<void> {
    await this.memberRepository.decrement({ member_id: memberId }, 'balance', amount);
  }

  /**
   * 更新最后登录信息
   */
  async updateLastLogin(memberId: number, loginInfo: any): Promise<void> {
    await this.memberRepository.update(memberId, {
      login_time: Math.floor(Date.now() / 1000),
      login_ip: loginInfo.ip,
    });
  }

  /**
   * 检查用户名是否已存在
   */
  async isUsernameExists(username: string, excludeId?: number): Promise<boolean> {
    const where: any = { username, is_del: 0 };
    if (excludeId) {
      where.member_id = Not(excludeId);
    }
    
    const count = await this.memberRepository.count({ where });
    return count > 0;
  }

  /**
   * 检查手机号是否已存在
   */
  async isMobileExists(mobile: string, excludeId?: number): Promise<boolean> {
    const where: any = { mobile, is_del: 0 };
    if (excludeId) {
      where.member_id = Not(excludeId);
    }
    
    const count = await this.memberRepository.count({ where });
    return count > 0;
  }

  /**
   * 检查邮箱是否已存在
   */
  async isEmailExists(email: string, excludeId?: number): Promise<boolean> {
    const where: any = { email, is_del: 0 };
    if (excludeId) {
      where.member_id = Not(excludeId);
    }
    
    const count = await this.memberRepository.count({ where });
    return count > 0;
  }

  /**
   * 获取会员统计信息
   */
  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,
        create_time: Between(
          Math.floor(new Date().setHours(0, 0, 0, 0) / 1000),
          Math.floor(new Date().setHours(23, 59, 59, 999) / 1000)
        ),
      },
    });

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