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

@Provide()
export class AgentService extends BaseService {

  @InjectEntityModel(AgentEntity)
  agentEntity: Repository<AgentEntity>;

  @InjectEntityModel(AgentMerchantEntity)
  agentMerchantEntity: Repository<AgentMerchantEntity>;

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

  @Inject()
  baseSysUserService: BaseSysUserService;

  async page(query) {
    let { keyWord = '' } = query;
    const sql = `SELECT * FROM dj_agent a WHERE 1=1
      ${this.setSql(keyWord, 'and a.name like ?', [`%${keyWord}%`])}
      ${this.setSql(keyWord, 'and a.username like ?', [`%${keyWord}%`])}
    `;
    const result = await this.sqlRenderPage(sql, query);
    // 匹配角色
    if (!_.isEmpty(result.list)) {
      const agentIds = result.list.map(e => e.id);
      const mchIds = await this.nativeQuery(
        'SELECT a.agentId, a.mchId FROM dj_agent_mch a WHERE a.agentId in (?) ',
        [agentIds]
      );
      result.list.forEach(e => {
        e['mchIds'] = mchIds
          .filter(mch => mch.agentId == e.id)
          .map(mch => mch.mchId)
      });
    }
    return result;
  }

  public async info(id) {
    const info = await this.agentEntity.findOneBy({ id });
    const mchIds = await this.nativeQuery(
      'select a.mchId from dj_agent_mch a where a.agentId = ?',
      [id]
    );
    if (mchIds) {
      info['mchIds'] = mchIds.map(e => {
        return e.mchId
      });
    }
    return info;
  }

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

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

    const newAgent = await this.agentEntity.save({
      ...param,
      userId,
    });

    await Promise.all(
      param.mchIds.map(async e => {
        return await this.agentMerchantEntity.save({
          agentId: newAgent.id,
          mchId: e,
        });
      })
    );

    return param.id;
  }

  async update(param) {
    await this.agentEntity.save(param);
    const user = await this.baseSysUserEntity.findOneBy({ id: param.userId });
    await this.baseSysUserService.update({
      ...user,
      name: param.name,
      nickName: param.name,
      username: param.username,
      password: param.password,
      status: param.status,
    });
    await this.agentMerchantEntity.delete({
      agentId: param.id
    })
    await Promise.all(
      param.mchIds.map(async e => {
        return await this.agentMerchantEntity.save({
          agentId: param.id,
          mchId: e,
        });
      })
    );
  }

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

}
