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

@Provide()
export class RateService extends BaseService {
  @InjectEntityModel(RateEntity)
  rateEntity: Repository<RateEntity>;

  @Inject()
  walletService: WalletService;

  @Inject()
  ctx;

  @Inject()
  utils: Utils;
  
  @InjectEntityModel(MerchantEntity)
  merchantEntity: Repository<MerchantEntity>;

  async page(query) {
    let { mchId = '', currency = '', type = '' } = 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_rate 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}%`])}
      ${this.setSql(type, 'and a.type like ?', [`%${type}%`])}
    `;
    return this.sqlRenderPage(sql, query);
  }


  async add(param) {
    const data = await this.rateEntity.findOneBy({
      mchId: param.mchId,
      payType: param.payType,
      type: param.type,
      currency: param.currency
    })
    if (data) {
      throw new Error('已存在相同的费率配置');
    }
    await this.rateEntity.save(param);
    await this.walletService.createWallet(param.mchId, param.currency)
    return param.id;
  }

  async getOne(where) {
    return await this.rateEntity.findOneBy(where);
  }
}
