import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository, In } from 'typeorm';
import * as _ from 'lodash';
import { WalletEntity } from '../entity/wallet';
import { BalanceEntity } from '../entity/balance';
import { Utils } from '../../../comm/utils';
import { MerchantEntity } from '../entity/merchant';
import { BalanceQueue } from '../queue/balanceQueue';

@Provide()
export class WalletService extends BaseService {
  @InjectEntityModel(WalletEntity)
  walletEntity: Repository<WalletEntity>;

  @InjectEntityModel(BalanceEntity)
  balanceEntity: Repository<BalanceEntity>;

  @InjectEntityModel(MerchantEntity)
  merchantEntity: Repository<MerchantEntity>;

  @Inject()
  balanceQueue: BalanceQueue;

  @Inject()
  ctx;

  @Inject()
  utils: Utils;

  async createWallet(mchId, currency) {
    const data = await this.walletEntity.findOneBy({
      mchId: mchId,
      currency: currency,
    });
    if (!data) {
      await this.walletEntity.save({
        mchId: mchId,
        currency: currency,
        balance: 0,
        freeze: 0
      })
    }
  }

  async page(query) {
    let { mchId = '', currency = '' } = query;
    const { roleIds, userId } = this.ctx.admin;
    if (this.utils.isMerchant(roleIds)) {
      const merchant = await this.merchantEntity.findOneBy({ userId });
      if (merchant) {
        mchId = merchant.mchId;
      } else {
        mchId = '-1';
      }
    }
    const sql = `SELECT * FROM dj_wallet a WHERE 1=1
      ${this.utils.isMerchant(roleIds)
        ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
        : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
      }
      ${this.setSql(currency, 'and a.currency like ?', [`%${currency}%`])}
    `;
    return this.sqlRenderPage(sql, query);
  }

  async update(param) {
    await this.updateBalance({
      ...param,
      freeze: 0
    });
  }

  async updateBalance(param) {
    param.orderNo =
      param.orderNo || this.utils.createOrderNo(this.getPrefix(param.type));
    return new Promise(resolve => {
      this.balanceQueue.add(param);
      resolve(param);
    })
  }

  getPrefix(type) {
    if (+type === 2) {
      return 'XF';
    } else if (+type === 3) {
      return 'CZ';
    } else if (+type === 4) {
      return 'NC';
    } else if(+type === 5) {
      return 'TK'
    } else {
      return 'DS';
    }
  }

  async queryByMchIdAndCurrency(mchId, currency) {
    return this.walletEntity.findOneBy({
      mchId, currency
    })
  }

  async queryByMchId(mchId) {
    return this.walletEntity.findBy({
      mchId
    })
  }
}
