import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysRole } from '../../entities/SysRole';
import { CoreRoleService } from '../core/CoreRoleService';

@Injectable()
export class RoleAdminService {
  constructor(
    @InjectRepository(SysRole)
    private sysRoleRepository: Repository<SysRole>,
    private coreRoleService: CoreRoleService,
  ) {}

  async getRoleList(query: any, site_id: number = 0): Promise<{ list: SysRole[]; total: number }> {
    const { page = 1, limit = 10, role_name, status } = query;
    
    const queryBuilder = this.sysRoleRepository
      .createQueryBuilder('sys_role')
      .where('sys_role.site_id = :site_id', { site_id });

    if (role_name) {
      queryBuilder.andWhere('sys_role.role_name LIKE :role_name', { role_name: `%${role_name}%` });
    }

    if (status !== undefined) {
      queryBuilder.andWhere('sys_role.status = :status', { status });
    }

    const [list, total] = await queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('sys_role.create_time', 'DESC')
      .getManyAndCount();

    return { list, total };
  }

  async getRoleDetail(role_id: number, site_id: number = 0): Promise<SysRole> {
    const role = await this.sysRoleRepository.findOne({
      where: { role_id, site_id },
    });
    
    if (!role) {
      throw new NotFoundException('角色不存在');
    }
    
    return role;
  }

  async createRole(roleData: any, site_id: number = 0): Promise<SysRole> {
    const role = {
      ...roleData,
      site_id,
      create_time: Math.floor(Date.now() / 1000),
      update_time: Math.floor(Date.now() / 1000),
    };

    return await this.sysRoleRepository.save(role);
  }

  async updateRole(role_id: number, updateData: any, site_id: number = 0): Promise<SysRole> {
    const role = await this.getRoleDetail(role_id, site_id);

    Object.assign(role, {
      ...updateData,
      update_time: Math.floor(Date.now() / 1000),
    });

    return await this.sysRoleRepository.save(role);
  }

  async deleteRole(role_id: number, site_id: number = 0): Promise<void> {
    const role = await this.getRoleDetail(role_id, site_id);
    await this.sysRoleRepository.remove(role);
  }

  /**
   * 批量删除角色
   */
  async batchDeleteRoles(roleIds: number[]): Promise<{ success: boolean; message: string }> {
    try {
      await this.sysRoleRepository.update(roleIds, {
        is_del: 1,
      });
      return { success: true, message: '批量删除成功' };
    } catch (error) {
      return { success: false, message: '批量删除失败' };
    }
  }

  /**
   * 更新角色状态
   */
  async updateRoleStatus(roleId: number, status: number): Promise<{ success: boolean; message: string }> {
    try {
      await this.sysRoleRepository.update(roleId, { status });
      return { success: true, message: '状态更新成功' };
    } catch (error) {
      return { success: false, message: '状态更新失败' };
    }
  }

  /**
   * 批量更新角色状态
   */
  async batchUpdateRoleStatus(roleIds: number[], status: number): Promise<{ success: boolean; message: string }> {
    try {
      await this.sysRoleRepository.update(roleIds, { status });
      return { success: true, message: '批量更新状态成功' };
    } catch (error) {
      return { success: false, message: '批量更新状态失败' };
    }
  }

  /**
   * 分配菜单
   */
  async assignMenus(roleId: number, menuIds: number[]): Promise<{ success: boolean; message: string }> {
    try {
      // 这里应该实现角色菜单分配逻辑
      // 可以更新角色的 rules 字段
      return { success: true, message: '菜单分配成功' };
    } catch (error) {
      return { success: false, message: '菜单分配失败' };
    }
  }

  /**
   * 获取角色统计
   */
  async getRoleStats(): Promise<any> {
    const total = await this.sysRoleRepository.count({ where: { is_del: 0 } });
    const active = await this.sysRoleRepository.count({ where: { is_del: 0, status: 1 } });
    const inactive = await this.sysRoleRepository.count({ where: { is_del: 0, status: 0 } });
    
    return { total, active, inactive };
  }

  /**
   * 导出角色
   */
  async exportRoles(): Promise<any[]> {
    return await this.sysRoleRepository.find({
      where: { is_del: 0 },
      order: { create_time: 'DESC' },
    });
  }
} 