import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, In, Repository } from 'typeorm';
import { BaseService } from '../../frame/BaseService';
import { Collection } from '../../entity/platform/collection.entity';
import { Expert } from '../../entity/users/expert.entity';
import { get, pick } from 'lodash';
@Provide()
export class ExpertService extends BaseService<Expert> {
  @InjectEntityModel(Expert)
  model: Repository<Expert>;

  @InjectEntityModel(Collection)
  cModel: Repository<Collection>;

  // 企业列表
  async list(query: any) {
    const { skip = 0, limit = 0, is_show, status } = pick(query, ['skip', 'limit', 'is_show', 'status']);
    const { one, two, thr, four } = pick(query, ['one', 'two', 'thr', 'four']);
    const whereObject: any = {};
    // if (is_show) whereObject.is_show = Equal(is_show);
    // if (status) whereObject.status = Equal(status);
    if (one) whereObject.field = In(one);
    if (two) whereObject.title = In(two);
    if (thr) whereObject.area = In(thr);
    if (four) whereObject.area = In(four);
    const builder = this.model.createQueryBuilder().setFindOptions({ where: whereObject, skip, take: limit });
    const data = await builder.getMany();
    const total = await builder.getCount();
    return { data, total };
  }

  // 企业详情
  async detail(id) {
    const user = this.ctx.user;
    const data = { is_collection: false };
    const arr = await this.model.findOne({ where: { id: Equal(id) } });
    if (arr && get(arr, 'id') && user) {
      // TODO: 查询是否收藏该企业
      const collection = await this.cModel.findOne({ where: { user: Equal(user.id), source: Equal(arr.id) } });
      if (collection) data.is_collection = true;
    }
    return { ...arr, ...data };
  }
}
