import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, In, Repository } from 'typeorm';
import { BaseService } from '../../frame/BaseService';
import { Dept } from '../../entity/system/dept.entity';
import { orderBy } from 'lodash';
@Provide()
export class DeptService extends BaseService<Dept> {
  @InjectEntityModel(Dept)
  model: Repository<Dept>;
  async queryAll() {
    const data = await this.model.find({ order: { order_num: 'DESC' } });
    let treeData = data.filter(f => !f.parent_id);
    treeData = this.treeData(data, treeData);
    return treeData;
  }

  async getNextLevel(id: number, query = { skip: 0, limit: 10 }) {
    const builder = this.model.createQueryBuilder();
    builder.setFindOptions({ where: { parent_id: Equal(id) }, skip: query.skip, take: query.limit });
    const result = await builder.getMany();
    const total = await builder.getCount();
    const ids = result.map(i => i.parent_id);
    const parents = await this.model.find({ where: { id: In(ids) }, select: ['id', 'name'] });
    result.map(i => {
      if (!i.parent_id) return i;
      const parent = parents.find(f => f.id === i.parent_id);
      if (!parent) return;
      Object.assign(i, { parent_name: parent.name });
      return i;
    });
    return { data: result, total };
  }

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