import { orderConfirm, tradeNoQuery, triggerPay } from '../../utils/service';
import monitor from '../../utils/alipayLogger';
import { history } from '../../utils';
Component({
  props: {
    data: {
      bookInfo: {}
    },
    onConfirmBook: () => {}
  },
  data: {
    bookInfo: {},
    loading: false
  },

  didMount() {
    my.setNavigationBar({
      title: '预约确认'
    });
    this.setData({
      bookInfo: this.props.data.bookInfo
    });
  },

  methods: {
    async confirmBook(e) {
      if (this.data.loading) {
        return;
      }

      this.setData({
        loading: true
      });
      let formId = '';

      if (e && e.detail && e.detail.formId) {
        formId = e.detail.formId;
      }

      const {
        doctorId,
        orderSourceId,
        cardNum
      } = this.data.bookInfo;
      const params = {
        doctorId,
        orderSourceId,
        cardNum,
        formId
      };
      const [err, res] = await orderConfirm(params);

      if (res) {
        monitor.api({
          api: '预约挂号',
          success: true,
          c1: 'taSR_YL',
          time: 2000
        });

        if (res.amount > 0) {
          this.tradeNoQuery(res.orderId, this.data.bookInfo);
        } else {
          this.setData({
            'bookInfo.status': true,
            'bookInfo.msg': '预约成功'
          });
          this.nextStep();
        }
      } else {
        monitor.api({
          api: '预约挂号',
          success: false,
          c1: 'taSR_YL',
          time: 2000
        });
        this.setData({
          'bookInfo.status': !err,
          'bookInfo.msg': err.msg
        });
        this.nextStep();
      }
    },

    // 唤起支付弹窗
    async tradeNoQuery(orderId, bookInfo) {
      // 生成订单号
      const [err, tradeRes] = await tradeNoQuery({
        type: 1,
        idNum: orderId,
        depName: bookInfo.depName
      });

      if (tradeRes) {
        // monitor.api('挂号缴费', true, 2000, 200, '挂号缴费成功');
        monitor.api({
          api: '挂号缴费',
          success: true,
          c1: 'taSR_YL',
          time: 200
        }); // res为：商家订单号

        my.tradePay({
          // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
          tradeNO: tradeRes.tradeNo,
          success: payRes => {
            this.triggerPay(tradeRes.outTradeNo, tradeRes.tradeNo, payRes.resultCode);
          },
          fail: res => {
            // 订单支付异常
            this.setData({
              'bookInfo.status': false,
              'bookInfo.msg': res.message
            });
            this.nextStep();
          }
        });
      } else {
        monitor.api('挂号缴费', false, 2000, err.code || 500, err.msg);
        monitor.api({
          api: '挂号缴费',
          success: false,
          c1: 'taSR_YL',
          time: 200
        });
      }
    },

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

      if (resultCode === '4000' || resultCode === '6002') {
        // 支付失败
        this.setData({
          'bookInfo.status': false,
          'bookInfo.msg': '支付失败'
        });
        this.nextStep();
        return;
      } else if (resultCode === '6001') {
        // 取消支付
        this.setData({
          'bookInfo.status': false,
          'bookInfo.msg': '取消支付'
        });
        this.nextStep();
        return;
      }

      if (confirmRes) {
        // 交易成功
        if (confirmRes.status === 'TRADE_SUCCESS') {
          // 已经成功
          this.setData({
            'bookInfo.status': true,
            'bookInfo.msg': '支付成功'
          });
          this.nextStep();
        } else {
          // 其他情况视为异常
          this.setData({
            'bookInfo.status': true,
            'bookInfo.msg': '支付异常'
          });
          this.nextStep();
        }
      }
    },

    nextStep() {
      this.setData({
        loading: false
      });
      setTimeout(() => {
        history.openPage({
          pageType: 'booking-success',
          data: {
            bookInfo: this.data.bookInfo
          }
        });
      });
    }

  }
});