import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysMenu } from '../../entities/SysMenu';
// 使用原生 Date 对象替代时间工具函数

@Injectable()
export class CoreMenuService {
  constructor(
    @InjectRepository(SysMenu)
    private sysMenuRepository: Repository<SysMenu>,
  ) {}

  async createMenu(menuData: Partial<SysMenu>): Promise<SysMenu> {
    const menu = this.sysMenuRepository.create({
      ...menuData,
      // TypeORM 会自动处理时间戳
    });

    return await this.sysMenuRepository.save(menu);
  }

  async getMenuById(id: number): Promise<SysMenu | null> {
    return await this.sysMenuRepository.findOne({
      where: { id, delete_time: 0 },
    });
  }

  async getMenuByKey(menu_key: string, app_type: string): Promise<SysMenu | null> {
    return await this.sysMenuRepository.findOne({
      where: { menu_key, app_type, delete_time: 0 },
    });
  }

  async updateMenu(id: number, updateData: Partial<SysMenu>): Promise<SysMenu> {
    const menu = await this.getMenuById(id);
    if (!menu) {
      throw new Error('菜单不存在');
    }

    Object.assign(menu, updateData);
    return await this.sysMenuRepository.save(menu);
  }

  async deleteMenu(id: number): Promise<void> {
    const menu = await this.getMenuById(id);
    if (!menu) {
      throw new Error('菜单不存在');
    }

          // TypeORM 会自动处理软删除时间戳
    await this.sysMenuRepository.save(menu);
  }

  async getMenuList(app_type?: string): Promise<SysMenu[]> {
    const where: any = { delete_time: 0 };
    if (app_type) {
      where.app_type = app_type;
    }

    return await this.sysMenuRepository.find({
      where,
      order: { sort: 'DESC' },
    });
  }

  async getMenusByAppType(app_type: string, status: number = 1): Promise<SysMenu[]> {
    return await this.sysMenuRepository.find({
      where: { app_type, status, delete_time: 0 },
      order: { sort: 'DESC' },
    });
  }

  async buildMenuTree(menus: SysMenu[], parent_key = ''): Promise<any[]> {
    const tree = [];
    
    for (const menu of menus) {
      if (menu.parent_key === parent_key) {
        const children = await this.buildMenuTree(menus, menu.menu_key);
        const menuItem = {
          ...menu,
          children: children.length > 0 ? children : undefined,
        };
        tree.push(menuItem);
      }
    }
    
    return tree;
  }

  async isMenuKeyExists(menu_key: string, app_type: string, excludeId?: number): Promise<boolean> {
    const where: any = { menu_key, app_type, delete_time: 0 };
    
    if (excludeId) {
      where.id = { $ne: excludeId };
    }

    const count = await this.sysMenuRepository.count({ where });
    return count > 0;
  }

  async getMenuStats(app_type?: string): Promise<any> {
    const where: any = { delete_time: 0 };
    if (app_type) {
      where.app_type = app_type;
    }

    const total = await this.sysMenuRepository.count({ where });
    const active = await this.sysMenuRepository.count({ where: { ...where, status: 1 } });
    const inactive = await this.sysMenuRepository.count({ where: { ...where, status: 0 } });

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