import { Match } from '../../entity/platform/match.entity';
import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseServiceV2 } from '../../frame/BaseServiceV2';
import { ProjectService } from './project.service';
import { MatchPathService } from './matchPath.service';
import dayjs = require('dayjs');
import { ScoreService } from './score.service';
import { SignService } from './sign.service';
import { completeBuilderCondition } from '../../frame/conditionBuilder';
@Provide()
export class MatchService extends BaseServiceV2 {
  @InjectEntityModel(Match)
  model: Repository<Match>;

  @Inject()
  projectService: ProjectService;

  @Inject()
  matchService: MatchPathService;

  @Inject()
  scoreService: ScoreService;

  @Inject()
  signService: SignService;

  getQueryColumnsOpera() {
    const obj = {
      tags: this.Opera.Json,
      name: this.Opera.Like,
    };
    return obj;
  }
  // 赛事进行中第一部创建报名分数
  async updateProject({ id }, data) {
    const builder = this.model.createQueryBuilder();
    completeBuilderCondition({ id });
    const match = await builder.getOne();
    if (match && match.match_status === '2') {
      // 如果赛事改为进行中将赛事流程按排序进行查询
      const path = await this.matchService.query({ match: id, is_use: '0' }, { order: { order_num: 'ASC' } });
      if (path && path.total > 0) {
        // 如果有赛事流程就查询报名信息
        const sign = await this.signService.query({ match: id, status: '1' });
        const score = await this.scoreService.query({ match: id, matchPath: path.data[0].id });
        // 检测该流程的分数 全部删除重新分配
        if (score && score.total > 0) {
          for (const val of score.data) {
            await this.scoreService.delete(val.id);
          }
        }
        // 重新分配分数
        for (const val of sign.data) {
          await this.scoreService.create({ match: id, matchPath: path.data[0].id, sign: val.id });
        }
      }
    }
    // 赛事状态修改为结束 将赛事信息整理存入项目库中
    if (match && match.match_status === '3') {
      const result = await this.projectService.query({ user: match.user, name: match.name });
      if (result && result.total > 0) {
        await this.projectService.update({ id: result.data[0].id }, { user: match.user, name: match.name, industry: match.industry, tags: ['赛事'], time: dayjs().format('YYYY-MM-DD'), source: '赛事', status: '1' });
      } else {
        await this.projectService.create({ user: match.user, name: match.name, industry: match.industry, tags: ['赛事'], time: dayjs().format('YYYY-MM-DD'), source: '赛事', status: '1' });
      }
    }
  }

  // 删除赛事 删除相应的流程
  async deleteFlow(id) {
    const result = await this.matchService.query({ match: id });
    if (result && result.total > 0) {
      for (const val of result.data) {
        await this.matchService.delete({ id: val.id });
      }
    }
  }
}
