import { Inject, Logger, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { ILogger } from '@midwayjs/logger';
import { CoolCommException } from '@cool-midway/core';
import * as _ from 'lodash';
import { ChannelService } from './channel';
import { MerchantService } from './merchant';
import { DispatchService } from './channels/dispatch';
import { Utils } from '../../../comm/utils';
import * as md5 from 'md5';
import { RateService } from './rate';
import { MchChannelService } from './mchChannel';
import { RefundService } from './refund';
import { PayService } from './pay';
import { OrderService } from './order';
import { isNumber } from '@midwayjs/core/dist/util/types';

@Provide()
export class PayRefundService extends BaseService {

  @Inject()
  orderService: OrderService;

  @Inject()
  payService: PayService;

  @Inject()
  merchantService: MerchantService;

  @Inject()
  refundService: RefundService;

  @Inject()
  dispatchService: DispatchService;

  @Logger()
  logger: ILogger;

  @Inject()
  utils: Utils;

  async queryRefund(payload) {
    try {
      this.logger.info('退款查询', JSON.stringify(payload));
      await this.validQueryParam(payload);
      const merchant = await this.payService.validMerchant(payload.mchId);
      await this.payService.validSign(payload, merchant);
      const refund = await this.refundService.findByRefundNo(
        payload.refundNo
      );
      if (!refund || refund.mchId !== payload.mchId) {
        throw new Error('退款订单不存在');
      }
      return {
        mchId: refund.mchId,
        orderNo: refund.orderNo,
        outOrderNo: refund.outOrderNo,
        refundNo: refund.refundNo,
        amount: refund.amount,
        currency: refund.currency,
        charge: refund.charge,
        status: refund.status,
        reson: refund.reson,
        remark: refund.remark
      };
    } catch (err) {
      this.logger.error('查询失败', JSON.stringify(payload), err.message);
      throw new CoolCommException(err.message);
    }
  }

  async validQueryParam(payload) {
    if (_.isEmpty(payload.mchId)) {
      throw new Error('商户号【mchId】不能为空');
    }
    if (_.isEmpty(payload.refundNo)) {
      throw new Error('退款订单号【refundNo】不能为空');
    }
    if (_.isEmpty(payload.sign)) {
      throw new Error('签名【sign】不能为空');
    }
  }

  async refund(payload) {
    try {
      this.logger.info('退款下单', JSON.stringify(payload));
      await this.validParam(payload);
      const merchant = await this.payService.validMerchant(payload.mchId);
      await this.payService.validSign(payload, merchant);
      const order = await this.orderService.findByOrderNo(payload.orderNo);
      if (!order || +order.status !== 1) {
        throw new Error('订单不存在或订单状态非支付成功');
      }
      let amount = order.amount;
      if(isNumber(payload.amount) && +payload.amount < +order.amount) {
        amount = payload.amount;
      }
      return await this.refundService.toRefund(order, amount, payload.reason || '');
    } catch (err) {
      this.logger.error('退款下单', JSON.stringify(payload), err.message);
      throw new CoolCommException(err.message);
    }
  }

  async validParam(payload) {
    if (_.isEmpty(payload.mchId)) {
      throw new Error('商户号【mchId】不能为空');
    }
    if (_.isEmpty(payload.orderNo)) {
      throw new Error('平台订单号【orderNo】不能为空');
    }
    if (_.isEmpty(payload.sign)) {
      throw new Error('签名【sign】不能为空');
    }
  }
}
