import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Equal } from 'typeorm';
import { ApplyCompany } from '../../entity/users/applyCompany.entity';
import { BaseServiceV2 } from '../../frame/BaseServiceV2';
import { get } from 'lodash';
import { CompanyService } from './company.service';
import { UserService } from '../system/user.service';
import { ErrorCode, ServiceError } from '../../error/service.error';
@Provide()
export class ApplyCompanyService extends BaseServiceV2 {
  @InjectEntityModel(ApplyCompany)
  model: Repository<ApplyCompany>;

  @Inject()
  companyService: CompanyService;

  @Inject()
  userService: UserService;
  // 认领检查
  async createExamine(data) {
    const { user } = data;
    const company = await this.companyService.fetch({ user: user });
    if (company) throw new ServiceError(ErrorCode.SERVICE_APPLY);
  }
  /**
   * 如果审核通过修改该企业的用户id,修改用户角色
   * @param {object} data 数据
   */
  async apply(id) {
    const result = await this.model.findOne({ where: { id: Equal(id) } });
    // 查询该用户是否有企业信息
    const company = await this.companyService.fetch({ user: get(result, 'user') });
    if (company) throw new ServiceError(ErrorCode.SERVICE_APPLY);
    else {
      // 查询用户角色
      const userInfo = await this.userService.fetch({ id: get(result, 'user') });
      if (userInfo) {
        const is_update = userInfo.role.find(i => i === 'Company');
        // 如果没有企业角色 增加一个企业角色
        if (!is_update) await this.userService.update({ id: get(result, 'user') }, { id: get(result, 'user'), role: [...userInfo.role, 'Company'] });
        // 修改企业用户id
        await this.companyService.update({ id: get(result, 'company') }, { id: get(result, 'company'), user: get(result, 'user') });
      } else throw new ServiceError(ErrorCode.USER_NOT_FOUND);
    }
  }

  /**
   * 填充
   * @param {object} data 数据
   */
  async fillName(data) {
    const { company, user } = data;
    // 公司名称
    const companyInfo = await this.companyService.fetch({ id: company });
    if (companyInfo) data = { ...data, company_name: get(companyInfo, 'name') };
    // 用户名称
    const userInfo = await this.userService.fetch({ id: user });
    if (userInfo) data = { ...data, user_name: get(userInfo, 'nick_name') };

    return data;
  }
}
