import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '../../frame/BaseService';
import { Menus } from '../../entity/system/menus.entity';
import { get, orderBy } from 'lodash';
import * as fs from 'fs';
import path = require('path');
@Provide()
export class MenusService extends BaseService<Menus> {
  @InjectEntityModel(Menus)
  model: Repository<Menus>;

  async queryMenu(query = {}): Promise<Array<object>> {
    const qb = this.queryBuilder(query);
    const whereObj = this.buildFindWhere(qb);
    const data = await this.model.find({ where: whereObj, order: { order_num: 'ASC' } });
    let treeMenu = data.filter(f => !f.parent_id);
    treeMenu = this.treeMenu(data, treeMenu);
    return treeMenu;
  }

  treeMenu(allMenus, nowMenu) {
    for (const nm of nowMenu) {
      const { id, parent_id } = nm;
      // 查下下级其是否有目录
      let children = allMenus.filter(f => f.parent_id === id);
      children = this.treeMenu(allMenus, children);
      if (children.length > 0) nm.children = children;
      // 换父级组件的名称
      if (parent_id) {
        const r = allMenus.find(f => f.id === parent_id);
        if (r) nm.parent_name = r.name;
      }
    }
    nowMenu = orderBy(nowMenu, ['order_num'], ['asc']);
    return nowMenu;
  }

  async initData() {
    // C:\workspace\cxyy\cxyy-service\dist\service\menus.json
    const place = path.resolve(__dirname, '../../../../menus.json');
    let list: any = fs.readFileSync(place, 'utf8');
    if (!list) return;
    list = JSON.parse(list);
    list = get(list, 'RECORDS');
    let id = 1;
    for (const menu of list) {
      menu.id = id;
      menu.config = JSON.parse(get(menu, 'config'));
      id++;
    }
    // 重新整理parent_id
    for (const menu of list) {
      if (!menu.parent_id) continue;
      const parent = list.find(f => f._id === menu.parent_id);
      if (!parent) continue;
      menu.parent_id = parent.id;
    }
    list = list.map(i => {
      delete i._id;
      if (!i.parent_id || i.parent_id === '') delete i.parent_id;
      return i;
    });
    await this.model.insert(list);
  }
}
