import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository } from 'typeorm';
import { BaseService } from '../../frame/BaseService';
import { User } from '../../entity/system/user.entity';
import { ErrorCode, ServiceError } from '../../error/service.error';
@Provide()
export class UserService extends BaseService<User> {
  @InjectEntityModel(User)
  model: Repository<User>;

  async createBefore(data) {
    const { role } = data;
    if (role && role.length > 1) data.status = '0';
    else data.status = '1';
    return data;
  }

  // 用户账号，微信唯一标识检查
  async createExamine(data) {
    const { openid, account } = data;
    let result;
    if (account) {
      result = await this.model.findOne({ where: { account: Equal(account) } });
      if (result) throw new ServiceError(ErrorCode.DUPLICATE_USERS_ACCOUNT);
    }
    if (openid) {
      result = await this.model.findOne({ where: { openid: Equal(openid) } });
      if (result) throw new ServiceError(ErrorCode.DUPLICATE_USERS_OPENID);
    }
  }

  // 修改后判断是否有身份 如何审核通过将有身份的数据也审核成功
  async updateAfter(id, body) {
    const arr = await this.detail(id);
    const { status } = body;
    if (status === '1' && arr.role_type !== 'User') {
      // const model = GetModel(upperFirst(arr.role_type));
      // TODO: 需要明确修改的指代内容了:如果不是User，那还得说明是哪个 users下面的所有都是，都得引入进来处理
      // const user = await model.findOne({ where: { user: id } });
      // await model.update({ where: { id: user.id } }, { status: '1' });
    }
  }

  async detail(id) {
    const arr = await this.model.findOne({ where: { id: Equal(id) } });
    let role_type;
    if (arr && arr.role && arr.role.length > 1) role_type = arr.role[1];
    else role_type = arr.role[0];
    return { ...arr, role_type };
  }
}
