import { CoolEvent, CoolEventManager, Event } from '@cool-midway/core';
import { BaseSysMenuService } from '../service/sys/menu';
import {
  App,
  ILogger,
  IMidwayApplication,
  Inject,
  Logger,
} from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysMenuEntity } from '../entity/sys/menu';
import { BaseSysRoleMenuEntity } from '../entity/sys/role_menu';
import { BaseTranslateService } from '../service/translate';

/**
 * 导入菜单
 */
@CoolEvent()
export class BaseMenuEvent {
  @Logger()
  coreLogger: ILogger;

  @Inject()
  baseSysMenuService: BaseSysMenuService;

  @App()
  app: IMidwayApplication;

  @Inject()
  coolEventManager: CoolEventManager;

  @Inject()
  baseTranslateService: BaseTranslateService;

  @InjectEntityModel(BaseSysMenuEntity)
  baseSysMenuEntity: Repository<BaseSysMenuEntity>;

  @InjectEntityModel(BaseSysRoleMenuEntity)
  baseSysRoleMenuEntity: Repository<BaseSysRoleMenuEntity>;

  @Event('onMenuImport')
  async onMenuImport(datas) {
    for (const module in datas) {
      await this.baseSysMenuService.import(datas[module]);
      this.coreLogger.info(
        '\x1B[36m [cool:module:base] midwayjs cool module base import [' +
          module +
          '] module menu success \x1B[0m'
      );
    }
    this.coolEventManager.emit('onMenuInit', {});
    this.baseTranslateService.check();
  }

  @Event('onServerReady')
  async onServerReady() {
    await this.ensureDataSourceMenu();
    this.baseTranslateService.loadTranslations();
  }

  private async ensureDataSourceMenu() {
    const router = '/sys/data-source';
    const existing = await this.baseSysMenuEntity.findOne({ where: { router } });
    if (existing) {
      return;
    }

    const parent = await this.baseSysMenuEntity.findOne({ where: { name: '系统管理', type: 0 } });
    if (!parent?.id) {
      this.coreLogger.warn('[cool:module:base] skip data-source menu sync: parent 系统管理 not found');
      return;
    }

    const saved = await this.baseSysMenuEntity.save({
      parentId: parent.id,
      name: '数据源管理',
      router,
      perms: null,
      type: 1,
      icon: 'icon-data',
      orderNum: 4,
      viewPath: 'modules/base/views/data-source.vue',
      keepAlive: true,
      isShow: true,
    });

    const adminRoleMenu = await this.baseSysRoleMenuEntity.findOne({
      where: { roleId: 1, menuId: saved.id },
    });
    if (!adminRoleMenu) {
      await this.baseSysRoleMenuEntity.save({ roleId: 1, menuId: saved.id });
    }

    await this.baseSysMenuService.refreshPerms(saved.id);
    this.coreLogger.info('[cool:module:base] synced system data-source menu');
  }
}
