import { tradeNoForOrder, tradeResult, tradeNoQuery } from '../service/common';

const tradePay = function (params, option = {}) {
  // eslint-disable-next-line no-param-reassign
  option = Object.assign({
    useBalance: false,
    useMedicare: false,
    tradeType: 'Appointment' // Outpatient: 门诊缴费； Appointment： 挂号、充值

  }, option);
  console.log(params, option);

  if (option.tradeType === 'Appointment') {
    /**
     * params 挂号 : { type: 1, idNum: '', depName: '' }
     * params 充值 : { type: 2, idNum: '', amount: 0 }
     */
    return appointment(params);
  } else {
    /**
     * params : { outTradeNo }
     */
    return outpatient(params);
  }
}; // 挂号，充值类订单


function appointment(params) {
  return tradeNoQuery(params).then(_tradePay);
} // 门诊类订单


function outpatient(params) {
  return tradeNoForOrder({
    useBalance: params.useBalance,
    // 是否使用就诊卡余额
    useMedicare: params.useMedicare,
    // 是否使用医保卡余额
    outTradeNo: params.outTradeNo // 商家订单号

  }).then(tradeData => {
    if (tradeData.tradeNo) {
      // 发起支付
      return _tradePay(tradeData);
    } else {
      return Promise.resolve(compareResult({
        success: true
      }));
    }
  });
} // 处理支付结果


function compareResult(param) {
  console.log(param);

  if (!param.success) {
    my.showToast({
      type: 'fail',
      content: param.payRes.memo || '订单支付失败'
    });
  }

  return param.success;
}

function _tradePay(tradeData = {
  tradeNo: '',
  outTradeNo: ''
}) {
  return new Promise((resolve, reject) => {
    my.tradePay({
      tradeNO: tradeData.tradeNo,

      success(payRes) {
        // 4000 订单处理失败
        // 6001 用途中途取消支付
        // 6002 网络链接出错
        if (payRes.resultCode === '4000' || payRes.resultCode === '6002' || payRes.resultCode === '6001') {
          // 支付失败
          reject(compareResult({
            success: false,
            payRes
          }));
        } else {
          // 其他情况调用接口确认
          triggerPay({
            tradeNo: tradeData.tradeNo,
            outTradeNo: tradeData.outTradeNo,
            resultCode: payRes.resultCode
          }).then(r => {
            if (r.status === 'TRADE_SUCCESS') {
              resolve(compareResult({
                success: true,
                payRes
              }));
            } else {
              reject(compareResult({
                success: false,
                payRes
              }));
            }
          });
        }
      },

      fail: payRes => {
        // 订单支付异常
        reject(compareResult({
          success: false,
          payRes
        }));
      }
    });
  });
} // 验证支付结果


function triggerPay(param) {
  return tradeResult(param);
}

export default {
  tradePay
};