import { computeMedicarePayOrder, computeSelfPaidOrder, tradeNoForOrder, triggerPay } from '../../utils/service';
import { history, promisify } from '../../utils';
import monitor from '../../utils/alipayLogger';
const getAuthCode = promisify(my.getAuthCode);
Component({
  props: {
    data: {}
  },
  data: {
    paymentDetails: {},
    sourceType: null,
    // 0医保 1自费
    loading: false
  },

  didMount() {
    my.setNavigationBar({
      title: '诊间缴费'
    });
    this.toPay();
  },

  methods: {
    async toResult({
      subTitle,
      success
    }) {
      await this.setData({
        loading: false
      });
      history.openPage({
        pageType: 'payment-result',
        data: {
          subTitle,
          success
        }
      });
    },

    async triggerPay(outTradeNo, tradeNo, resultCode) {
      const [err, result] = await triggerPay({
        outTradeNo,
        tradeNo,
        resultCode
      });

      if (err) {
        this.toResult({
          success: false
        });
        return;
      } // 交易成功


      if (result.status === 'TRADE_SUCCESS') {
        // 已经成功
        this.toResult({
          success: true,
          subTitle: `流水号：${tradeNo}`
        });
      } else {
        // 其他情况视为异常
        this.toResult({
          success: false
        });
      }
    },

    // 支付
    async surePay() {
      if (this.data.loading) {
        return;
      }

      await this.setData({
        loading: true
      });
      const {
        sourceType
      } = this.data;
      const {
        outTradeNo
      } = this.props.data.orderDetail;
      const appIdRes = my.getAppIdSync(); // 生成订单号

      const datas = {
        outTradeNo,
        appId: appIdRes.appId,
        useBalance: true,
        useMedicare: sourceType === '0'
      };
      const [err, tradeRes] = await tradeNoForOrder(datas);

      if (err) {
        this.toResult({
          success: false
        });
        return;
      }

      if (tradeRes.needPay === false) {
        this.toResult({
          success: true
        });
        return;
      }

      if (tradeRes) {
        monitor.api({
          api: '门诊缴费',
          success: true,
          c1: 'taSR_YL',
          time: 2000
        });
        my.tradePay({
          // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
          tradeNO: tradeRes.tradeNo,
          success: payRes => {
            // 4000 订单处理失败
            // 6001 用途中途取消支付
            // 6002 网络链接出错
            if (payRes.resultCode === '4000' || payRes.resultCode === '6002') {
              // 支付失败
              this.toResult({
                success: false
              });
            } else if (payRes.resultCode === '6001') {
              // 取消支付
              this.toResult({
                success: false,
                subTitle: '取消支付'
              });
            } else {
              // 其他情况调用接口确认
              this.triggerPay(tradeRes.outTradeNo, tradeRes.tradeNo, payRes.resultCode);
            }
          },
          fail: () => {
            // 订单支付异常
            this.toResult({
              success: false
            });
          }
        });
      } else {
        monitor.api({
          api: '门诊缴费',
          success: false,
          c1: 'taSR_YL',
          time: 2000
        });
      }
    },

    getMedicareAuthCode() {
      return getAuthCode({
        scopes: ['auth_user', 'medicare']
      });
    },

    // 支付订单详情
    async toPay() {
      const {
        sourceType,
        orderDetail
      } = this.props.data;
      let authCode = '';

      if (sourceType === '0') {
        const [err, res] = await this.getMedicareAuthCode();

        if (err) {
          return my.alert({
            content: '获取授权失败'
          });
        }

        authCode = res.authCode;
      }

      const appIdRes = my.getAppIdSync();

      if (sourceType === '0') {
        const [, res] = await computeMedicarePayOrder({
          appId: appIdRes.appId,
          outTradeNo: orderDetail.outTradeNo,
          authCode
        });

        if (res) {
          this.setData({
            paymentDetails: res || {},
            sourceType
          });
        }
      }

      if (sourceType === '1') {
        const [, res] = await computeSelfPaidOrder({
          appId: appIdRes.appId,
          outTradeNo: orderDetail.outTradeNo
        });

        if (res) {
          this.setData({
            paymentDetails: res || {},
            sourceType
          });
        }
      }
    }

  }
});