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

  // 企业列表
  async list(query) {
    const { skip = 0, limit = 0, is_show, status, ...condition } = pick(query, ['skip', 'limit', 'is_show', 'status']);
    const { one, two, thr, four, five } = pick(query, ['one', 'two', 'thr', 'four', 'five']);
    const whereObject: any = {};
    if (is_show) whereObject.is_show = Equal(is_show);
    if (status) whereObject.status = Equal(status);
    if (one) whereObject.scale = In(one);
    if (two) whereObject.pattern = In(two);
    if (thr) whereObject.area = In(thr);
    if (four) whereObject.type = In(four);
    if (five) whereObject.companyStatus = In(five);
    const builder = this.model.createQueryBuilder().setFindOptions({ where: whereObject, skip, take: limit });
    const data = await builder.getMany();
    const total = await builder.getCount();
    // const info: any = { is_show, status };
    // if (one) info.scale = { $in: one };
    // if (two) info.pattern = { $in: two };
    // if (thr) info.area = { $in: thr };
    // if (four) info.type = { $in: four };
    // if (five) info.companyStatus = { $in: five };
    // const data = await this.model.find(info).skip(skip).limit(limit).lean();
    // const total = await this.model.count(info);
    return { data, total };
  }

  // 企业详情
  async detail(id) {
    const user = this.ctx.user;
    const data = { is_collection: false };
    // const arr = await this.model.findById(id).lean();
    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 };
  }
}
