import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Friend } from '../../entity/platform/friend.entity';
import { BaseServiceV2 } from '../../frame/BaseServiceV2';
import { get, pick } from 'lodash';
import { IsNull, Equal, Repository } from 'typeorm';
@Provide()
export class FriendService extends BaseServiceV2 {
  @InjectEntityModel(Friend)
  model: Repository<Friend>;

  // 合作伙伴列表
  async list(query) {
    const { skip = 0, limit = 0, parent_code, ...info } = pick(query, ['skip', 'limit', 'code', 'parent_code']);
    const whereObject: any = { parent_code, ...info };
    if (!parent_code) whereObject.parent_code = IsNull();
    const builder = this.model.createQueryBuilder().setFindOptions({ where: whereObject, skip, take: limit, order: { order_num: 'DESC' } });
    const data = await builder.getMany();
    const total = await builder.getCount();
    for (const val of data) {
      if (get(val, 'code')) {
        // 查询下一级
        const region = await this.model.findOne({ where: { parent_code: Equal(val.code) } });
        if (region) Object.assign(val, { hasChildren: true });
      }
    }
    return { data, total };
  }
}
