import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { BaseService } from '../../frame/BaseService';
import { Region } from '../../entity/system/region.entity';
import { get, pick } from 'lodash';
import { Equal, Repository } from 'typeorm';
@Provide()
export class RegionService extends BaseService<Region> {
  @InjectEntityModel(Region)
  model: Repository<Region>;

  // 地区列表
  async list(query) {
    const { skip = 0, limit = 0, level, code, parent_code, ...info } = pick(query, ['skip', 'limit', 'level', 'code', 'parent_code']);
    const whereObject: any = { level, code, parent_code };
    const builder = this.model.createQueryBuilder().setFindOptions({ where: whereObject, skip, take: limit });
    const data = await builder.getMany();
    const total = await builder.getCount();
    for (const val of data) {
      if (get(val, 'code')) {
        let level = get(val, 'level');
        if (get(val, 'level') === 'province') level = 'city';
        else if (get(val, 'level') === 'city') level = 'area';
        else if (get(val, 'level') === 'area') level = 'street';
        // 查询下一级
        const region = await this.model.findOne({ where: { parent_code: Equal(val.code), level: Equal(level) } });
        if (region) Object.assign(val, { hasChildren: true });
      }
    }
    return { data, total };
  }
}
