import { Inject, Provide } from '@midwayjs/core';
import { get, union } from 'lodash';
import { CollectionService } from './platform/collection.service';
import { UserService } from './system/user.service';
import { Context } from '@midwayjs/koa';
import { MatchService } from './platform/match.service';

/**
 * 工具类服务,为其他地方提供一些通用的函数
 */
@Provide()
export class ServiceUtilService {
  @Inject()
  ctx: Context;
  @Inject()
  userService: UserService;
  @Inject()
  collectionService: CollectionService;
  @Inject()
  matchService: MatchService;
  /**
   * 填充创建人数据
   * @param {object} data 数据
   */
  async fillOnwer(data) {
    if (data && get(data, 'user')) {
      const dataUser = await this.userService.fetch({ id: get(data, 'user') });
      if (dataUser) data.userInfo = { name: get(dataUser, 'name', ''), phone: get(dataUser, 'phone', '') };
    }
    return data;
  }
  /**
   * 填充是否收藏字段: is_collection boolean类型
   * @param {object} data 数据
   */
  async fillCollection(data, type) {
    const user = this.ctx.user;
    if (user && get(user, 'id')) {
      const collectionData = await this.collectionService.fetch({ user: get(user, 'id'), source: get(data, 'id'), type });
      if (collectionData) data.is_collection = true;
    }
    return data;
  }
  /**
   * 填充赛事信息
   * @param {object} data 数据
   */
  async fillMatchInfo(data) {
    const match = get(data, 'match');
    if (!match) return;
    const matchInfo = await this.matchService.fetch({ id: match });
    if (matchInfo) data = { ...data, matchInfo };
    return data;
  }

  /**
   * 用户创建特殊身份认证
   */
  async fillIdentity(data, type) {
    if (data && get(data, 'user')) {
      const dataUser = await this.userService.fetch({ id: get(data, 'user') });
      if (dataUser) {
        const role = union(get(dataUser, 'role'), [type]);
        await this.userService.update({ id: get(dataUser, 'id') }, { id: get(dataUser, 'id'), role, status: '1' });
      }
    }
  }
}
