import { MerchantEntity } from './../entity/merchant';
import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import * as _ from 'lodash';
import { BaseSysUserService } from '../../base/service/sys/user';
import * as md5 from 'md5';

@Provide()
export class MerchantService extends BaseService {
  @InjectEntityModel(MerchantEntity)
  merchantEntity: Repository<MerchantEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @Inject()
  baseSysUserService: BaseSysUserService;

  async add(param) {
    const exists = await this.baseSysUserEntity.findOneBy({
      username: param.mchId,
    });
    if (!_.isEmpty(exists)) {
      throw new CoolCommException('该商户号不能使用~');
    }

    const userId = await this.baseSysUserService.add({
      name: param.name,
      nickName: param.name,
      username: param.mchId,
      password: param.password,
      roleIdList: [2],
      status: param.status,
      departmentId: 2,
    });

    await this.merchantEntity.save({
      ...param,
      fundPwd: md5(param.fundPwd),
      userId,
    });

    return param.id;
  }

  async update(param) {
    if (!_.isEmpty(param.fundPwd)) {
      param.fundPwd = md5(param.fundPwd);
    } else {
      delete param.fundPwd;
    }
    await this.merchantEntity.save(param);
    const user = await this.baseSysUserEntity.findOneBy({ id: param.userId });
    await this.baseSysUserService.update({
      ...user,
      name: param.name,
      nickName: param.name,
      username: param.mchId,
      password: param.password,
      status: param.status,
    });
  }

  async delete(ids) {
    const merchants = await this.merchantEntity.findBy({
      id: In(ids),
    });
    await this.merchantEntity.delete(ids);
    await this.baseSysUserEntity.delete({
      id: In(merchants.map(item => item.userId)),
    });
  }

  async getByMchId(mchId) {
    return await this.merchantEntity.findOneBy({
      mchId: mchId,
    });
  }

  async getMerchantList() {
    return await this.merchantEntity.find({
      where: {
        status: 1
      },
      select: ["mchId", "name"]
    })
  }
}
