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

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class BalanceService extends BaseService {
  @InjectEntityModel(BalanceEntity)
  balanceEntity: Repository<BalanceEntity>;

  @Inject()
  utils: Utils;

  @Inject()
  ctx;

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

  @InjectEntityModel(WalletEntity)
  walletEntity: Repository<WalletEntity>;

  async addBalance(param) {
    let wallet = await this.walletEntity.findOneBy({
      mchId: param.mchId,
      currency: param.currency
    });
    if (!wallet) {
      wallet = await this.walletEntity.save({
        mchId: param.mchId,
        currency: param.currency,
        balance: 0,
        freeze: 0
      })
    }
    if (+param.amount !== 0) {
      await this.balanceEntity.insert({
        orderNo: param.orderNo,
        mchId: param.mchId,
        type: param.type,
        currency: param.currency,
        amount: param.amount,
        remark: param.remark
      });
      wallet.balance = +wallet.balance + +param.amount;
      wallet.freeze = +wallet.freeze + +param.freeze;
    } else {
      wallet.freeze = +wallet.freeze + +param.freeze;
    }
    await this.walletEntity.save(wallet);
  }

  async page(query) {
    let { orderNo = '', mchId = '', type = '', currency = '', createTime = [] } = 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_balance a WHERE 1=1
      ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
      ${this.utils.isMerchant(roleIds)
        ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
        : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
      }
      ${this.setSql(type, 'and a.type = ?', [type])}
      ${this.setSql(currency, 'and a.currency like ?', [`%${currency}%`])}
      ${this.setSql(
        createTime && createTime.length === 2,
        'and (a.createTime between ? and ?)',
        createTime
      )}
    `;
    return this.sqlRenderPage(sql, query);
  }
}
