const {
  api,
  payApi,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  authAgainByUser,
  userLocation
} = require('../../lib/util.js')
const qrcode = require('../../lib/qrcode.js')
Page({
  data: {
    orderDetail: null,
    states: {
      '0': '未支付',
      '1': '已支付',
      '2': '交易关闭',
      '3': '已退款',
      '4': '退款中',
    },
    title:'获取中'
  },
  onLoad: function(op) {
    this.getOrderDetail(op)
  },
  onShow: function() {},
  getOrderDetail(orderId) {
    api.get('order/getDetail', orderId )
      .then(res => {
        console.log('res:', res)
        this.setData({
          orderDetail: res.data
        })
      })
      .catch(err => {
        this.setData({
          title:'获取失败'
        })
        alertTip(err)
      })
  },
  payOrder(e){
    const orderId = this.data.orderDetail.id
    wxLogin()
      .then(code => {
        payApi.get('getOpenId', {
          code
        })
          .then(res => {
            let openId = res.openId
            payApi.post('miniAppIdCardNumberOrder', {
              openId,
              orderId
            })
              .then(res => {
                let { timeStamp, nonce_str: nonceStr, signType, prepay_id, paySign } = res
                //统一下单了
                wx.requestPayment({
                  timeStamp,
                  nonceStr,
                  'package': prepay_id,
                  'signType': 'MD5',
                  paySign,
                  'success': function (res) {
                    alertTip('支付成功', function () {
                      wx.navigateBack()
                    })
                  },
                  'fail': function (res) {
                    alertTip(res.errMsg)
                  }
                })
              })
              .catch(err => {
                alertTip(err.err_code_des || err.return_msg)
                console.error(err)
              })
          })
          .catch(err => {
            console.error('openid', err)
            alertTip('超时了请重试' && err && err.remark)
          })
      })
      .catch(err => {
        console.error(err)
      })
  }
})