import { Sign } from '../../entity/platform/sign.entity';
import { Match } from '../../entity/platform/match.entity';
import { get } from 'lodash';
import { ErrorCode, ServiceError } from '../../error/service.error';
import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository } from 'typeorm';
import { BaseService } from '../../frame/BaseService';
@Provide()
export class SignService extends BaseService<Sign> {
  @InjectEntityModel(Sign)
  model: Repository<Sign>;

  @InjectEntityModel(Match)
  mModel: Repository<Match>;

  // 报名检查
  async createExamine(data) {
    const { user, match } = data;
    const result = await this.model.findOne({ where: { user: Equal(user), match: Equal(match) } });
    if (result) throw new ServiceError(ErrorCode.SERVICE_REPEAT);
  }

  // 列表
  async sign(query) {
    const { skip = 0, limit = 0, ...condition } = query;
    // const list = await this.model.find(condition).skip(skip).limit(limit).lean();
    const qb = this.queryBuilder(condition);
    const whereObject = this.buildFindWhere(qb);
    const builder = this.model.createQueryBuilder().setFindOptions({ where: whereObject, skip, take: limit });
    const list = await builder.getMany();
    const total = await builder.getCount();
    const data = [];
    for (const val of list) {
      if (get(val, 'match')) {
        // 查询需求发布者
        // const matchInfo = await this.mModel.findById(val.match).lean();
        const matchInfo = await this.mModel.findOne({ where: { id: Equal(val.match) } });
        if (matchInfo) {
          data.push({ ...val, ...{ matchInfo } });
        }
      }
    }
    // const total = await this.model.count(condition);
    return { data, total };
  }
}
