import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysUser } from '../../entities/SysUser';
import { SysUserRole } from '../../entities/SysUserRole';
import { CoreAdminService } from '../core/CoreAdminService';
import { CreateAdminDto, UpdateAdminDto, QueryAdminDto, BatchUpdateStatusDto, BatchAssignRoleDto, ResetPasswordDto } from '../../dto/admin/AdminDto';

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

  async createAdmin(adminData: CreateAdminDto, site_id: number = 0): Promise<SysUser> {
    // 检查用户名是否已存在
    const exists = await this.coreAdminService.isUsernameExists(adminData.username);
    if (exists) {
      throw new Error('用户名已存在');
    }

    // 创建管理员
    const admin = await this.coreAdminService.createAdmin(adminData);
    
    // 创建用户角色关联
    if (adminData.role_ids) {
      await this.createUserRole(admin.uid, site_id, adminData.role_ids);
    }

    return admin;
  }

  async updateAdmin(uid: number, updateData: UpdateAdminDto, site_id: number = 0): Promise<SysUser> {
    // 检查管理员是否存在
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }

    // 更新管理员信息
    const updatedAdmin = await this.coreAdminService.updateAdmin(uid, updateData);

    // 更新角色关联
    if (updateData.role_ids !== undefined) {
      await this.updateUserRole(uid, site_id, updateData.role_ids);
    }

    return updatedAdmin;
  }

  async deleteAdmin(uid: number, site_id: number = 0): Promise<void> {
    // 检查管理员是否存在
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }

    // 删除管理员
    await this.coreAdminService.deleteAdmin(uid);
    
    // 删除角色关联
    await this.deleteUserRole(uid, site_id);
  }

  async batchDeleteAdmins(uids: number[], site_id: number = 0): Promise<void> {
    for (const uid of uids) {
      await this.deleteAdmin(uid, site_id);
    }
  }

  async resetAdminPassword(uid: number, resetData: ResetPasswordDto, site_id: number = 0): Promise<void> {
    // 检查管理员是否存在
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }

    // 重置密码
    await this.coreAdminService.updateAdmin(uid, { password: resetData.new_password });
  }

  async updateAdminStatus(uid: number, status: number, site_id: number = 0): Promise<void> {
    // 检查管理员是否存在
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }

    // 更新状态
    await this.coreAdminService.updateAdmin(uid, { status });
  }

  async batchUpdateAdminStatus(uids: number[], status: number, site_id: number = 0): Promise<void> {
    for (const uid of uids) {
      await this.updateAdminStatus(uid, status, site_id);
    }

  }

  async assignAdminRoles(uid: number, role_ids: string, site_id: number = 0): Promise<void> {
    // 检查管理员是否存在
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }

    // 分配角色
    await this.updateUserRole(uid, site_id, role_ids);
  }

  async batchAssignAdminRoles(uids: number[], role_ids: string, site_id: number = 0): Promise<void> {
    for (const uid of uids) {
      await this.assignAdminRoles(uid, role_ids, site_id);
    }
  }

  async getAdminDetail(uid: number, site_id: number = 0): Promise<SysUser> {
    const admin = await this.coreAdminService.getAdminById(uid);
    if (!admin) {
      throw new Error('管理员用户不存在');
    }
    return admin;
  }

  async getAdminList(query: QueryAdminDto, site_id: number = 0): Promise<{ list: SysUser[]; total: number }> {
    const result = await this.coreAdminService.getAdminList(query);
    return { list: result.data, total: result.total };
  }

  async exportAdmins(site_id: number = 0): Promise<SysUser[]> {
    const result = await this.coreAdminService.getAdminList({ page: 1, limit: 1000 });
    return result.data;
  }

  async getAdminStats(site_id: number = 0): Promise<any> {
    return await this.coreAdminService.getAdminStats();
  }

  // 私有方法：创建用户角色关联
  private async createUserRole(uid: number, site_id: number, role_ids: string): Promise<void> {
    const userRole = this.sysUserRoleRepository.create({
      uid,
      site_id,
      role_ids,
      create_time: Math.floor(Date.now() / 1000),
      is_admin: 0,
      status: 1,
      delete_time: 0,
    });
    await this.sysUserRoleRepository.save(userRole);
  }

  // 私有方法：更新用户角色关联
  private async updateUserRole(uid: number, site_id: number, role_ids: string): Promise<void> {
    await this.sysUserRoleRepository.update(
      { uid, site_id, delete_time: 0 },
      { role_ids }
    );
  }

  // 私有方法：删除用户角色关联
  private async deleteUserRole(uid: number, site_id: number): Promise<void> {
    await this.sysUserRoleRepository.update(
      { uid, site_id, delete_time: 0 },
      { delete_time: Math.floor(Date.now() / 1000) }
    );
  }
} 