import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysUser } from '../../entities/SysUser';
import { SysUserLog } from '../../entities/SysUserLog';
import { SysUserRole } from '../../entities/SysUserRole';
// 移除时间工具函数引用，使用原生 Date 对象
import * as bcrypt from 'bcrypt';

@Injectable()
export class CoreAdminService {
  constructor(
    @InjectRepository(SysUser)
    private sysUserRepository: Repository<SysUser>,
    @InjectRepository(SysUserLog)
    private sysUserLogRepository: Repository<SysUserLog>,
    @InjectRepository(SysUserRole)
    private sysUserRoleRepository: Repository<SysUserRole>,
  ) {}

  /**
   * 创建管理员用户
   */
  async createAdmin(adminData: Partial<SysUser>): Promise<SysUser> {
    const admin = this.sysUserRepository.create(adminData);
    
    // 加密密码
    if (admin.password) {
      admin.password = await bcrypt.hash(admin.password, 10);
    }
    
    // 设置默认值 - TypeORM 会自动处理时间戳
    admin.status = 1;
    admin.is_del = 0;
    admin.login_count = 0;
    
    return await this.sysUserRepository.save(admin);
  }

  /**
   * 根据ID获取管理员用户
   */
  async getAdminById(uid: number): Promise<SysUser | null> {
    return await this.sysUserRepository.findOne({
      where: { uid, is_del: 0 },
      relations: ['user_role', 'user_logs'],
    });
  }

  /**
   * 根据用户名获取管理员用户
   */
  async getAdminByUsername(username: string): Promise<SysUser | null> {
    return await this.sysUserRepository.findOne({
      where: { username, is_del: 0 },
      relations: ['user_role', 'user_logs'],
    });
  }

  /**
   * 更新管理员用户
   */
  async updateAdmin(uid: number, updateData: Partial<SysUser>): Promise<SysUser> {
    const admin = await this.getAdminById(uid);
    if (!admin) {
      throw new Error('管理员用户不存在');
    }

    // 如果更新密码，需要重新加密
    if (updateData.password) {
      updateData.password = await bcrypt.hash(updateData.password, 10);
    }

    // TypeORM 会自动更新 update_time
    
    await this.sysUserRepository.update(uid, updateData);
    const updatedAdmin = await this.getAdminById(uid);
    if (!updatedAdmin) {
      throw new Error('更新后的管理员用户不存在');
    }
    return updatedAdmin;
  }

  /**
   * 删除管理员用户（软删除）
   */
  async deleteAdmin(uid: number): Promise<void> {
    const admin = await this.getAdminById(uid);
    if (!admin) {
      throw new Error('管理员用户不存在');
    }

    await this.sysUserRepository.update(uid, {
      is_del: 1,
      delete_time: Math.floor(Date.now() / 1000),
      // TypeORM 会自动更新 update_time
    });
  }

  /**
   * 获取管理员用户列表 - 完全按照PHP框架的搜索器方法实现
   */
  async getAdminList(params: {
    page?: number;
    limit?: number;
    username?: string;
    realname?: string;
    status?: number;
    site_id?: number;
    createTime?: [string, string];
    lastTime?: [string, string];
  }): Promise<{ data: SysUser[]; total: number }> {
    const { page = 1, limit = 20, username, realname, status, site_id, createTime, lastTime } = params;
    const skip = (page - 1) * limit;

    const queryBuilder = this.sysUserRepository
      .createQueryBuilder('admin')
      .leftJoinAndSelect('admin.userrole', 'userrole')
      .leftJoinAndSelect('admin.roles', 'roles')
      .where('admin.is_del = :is_del', { is_del: 0 });

    // 对应PHP的searchUsernameAttr方法
    if (username) {
      queryBuilder.andWhere('admin.username LIKE :username', { username: `%${this.handleSpecialCharacter(username)}%` });
    }

    // 对应PHP的searchRealnameAttr方法
    if (realname) {
      queryBuilder.andWhere('admin.real_name LIKE :realname', { realname: `%${realname}%` });
    }

    // 对应PHP的searchStatusAttr方法
    if (status !== undefined) {
      queryBuilder.andWhere('admin.status = :status', { status });
    }

    // 对应PHP的searchCreateTimeAttr方法
    if (createTime && createTime.length === 2) {
      const [startTime, endTime] = createTime;
      if (startTime && endTime) {
        const startTimestamp = Math.floor(new Date(startTime).getTime() / 1000);
        const endTimestamp = Math.floor(new Date(endTime).getTime() / 1000);
        queryBuilder.andWhere('admin.create_time BETWEEN :startTime AND :endTime', { startTime: startTimestamp, endTime: endTimestamp });
      } else if (startTime) {
        const startTimestamp = Math.floor(new Date(startTime).getTime() / 1000);
        queryBuilder.andWhere('admin.create_time >= :startTime', { startTime: startTimestamp });
      } else if (endTime) {
        const endTimestamp = Math.floor(new Date(endTime).getTime() / 1000);
        queryBuilder.andWhere('admin.create_time <= :endTime', { endTime: endTimestamp });
      }
    }

    // 对应PHP的searchLastTimeAttr方法
    if (lastTime && lastTime.length === 2) {
      const [startTime, endTime] = lastTime;
      if (startTime && endTime) {
        const startTimestamp = Math.floor(new Date(startTime).getTime() / 1000);
        const endTimestamp = Math.floor(new Date(endTime).getTime() / 1000);
        queryBuilder.andWhere('admin.last_time BETWEEN :startTime AND :endTime', { startTime: startTimestamp, endTime: endTimestamp });
      } else if (startTime) {
        const startTimestamp = Math.floor(new Date(startTime).getTime() / 1000);
        queryBuilder.andWhere('admin.last_time >= :startTime', { startTime: startTimestamp });
      } else if (endTime) {
        const endTimestamp = Math.floor(new Date(endTime).getTime() / 1000);
        queryBuilder.andWhere('admin.last_time <= :endTime', { endTime: endTimestamp });
      }
    }

    // 如果指定了site_id，需要通过user_role表关联查询
    if (site_id !== undefined) {
      queryBuilder
        .innerJoin('sys_user_role', 'user_role', 'user_role.uid = admin.uid')
        .andWhere('user_role.site_id = :site_id', { site_id })
        .andWhere('user_role.is_del = :role_is_del', { role_is_del: 0 });
    }

    const [data, total] = await queryBuilder
      .skip(skip)
      .take(limit)
      .orderBy('admin.create_time', 'DESC')
      .getManyAndCount();

    return { data, total };
  }

  /**
   * 验证管理员密码
   */
  async validatePassword(uid: number, password: string): Promise<boolean> {
    const admin = await this.getAdminById(uid);
    if (!admin) {
      return false;
    }

    return await bcrypt.compare(password, admin.password);
  }

  /**
   * 更新管理员登录信息
   */
  async updateLoginInfo(uid: number, ip: string): Promise<void> {
    const currentTimestamp = Math.floor(Date.now() / 1000);
    await this.sysUserRepository.update(uid, {
      last_ip: ip,
      last_time: currentTimestamp,
      login_count: () => 'login_count + 1',
      update_time: currentTimestamp,
    });
  }

  /**
   * 检查用户名是否已存在 - 对应PHP的searchUsernameAttr方法
   */
  async isUsernameExists(username: string, excludeUid?: number): Promise<boolean> {
    const queryBuilder = this.sysUserRepository
      .createQueryBuilder('admin')
      .where('admin.username = :username', { username })
      .andWhere('admin.is_del = :is_del', { is_del: 0 });

    if (excludeUid) {
      queryBuilder.andWhere('admin.uid != :uid', { uid: excludeUid });
    }

    const count = await queryBuilder.getCount();
    return count > 0;
  }

  /**
   * 获取管理员统计信息
   */
  async getAdminStats(site_id?: number): Promise<{
    total: number;
    active: number;
    inactive: number;
    superAdmin: number;
  }> {
    const queryBuilder = this.sysUserRepository
      .createQueryBuilder('admin')
      .where('admin.is_del = :is_del', { is_del: 0 });

    if (site_id !== undefined) {
      queryBuilder
        .innerJoin('sys_user_role', 'user_role', 'user_role.uid = admin.uid')
        .andWhere('user_role.site_id = :site_id', { site_id })
        .andWhere('user_role.is_del = :role_is_del', { role_is_del: 0 });
    }

    const total = await queryBuilder.getCount();
    const active = await queryBuilder.andWhere('admin.status = :status', { status: 1 }).getCount();
    const inactive = await queryBuilder.andWhere('admin.status = :status', { status: 0 }).getCount();

    const superAdminQueryBuilder = this.sysUserRoleRepository
      .createQueryBuilder('user_role')
      .where('user_role.is_del = :is_del', { is_del: 0 })
      .andWhere('user_role.is_admin = :is_admin', { is_admin: 1 });

    if (site_id !== undefined) {
      superAdminQueryBuilder.andWhere('user_role.site_id = :site_id', { site_id });
    }

    const superAdmin = await superAdminQueryBuilder.getCount();

    return { total, active, inactive, superAdmin };
  }

  /**
   * 处理特殊字符 - 对应PHP的handelSpecialCharacter方法
   */
  private handleSpecialCharacter(str: string): string {
    // 这里应该实现PHP框架中的特殊字符处理逻辑
    // 暂时返回原字符串
    return str;
  }
} 