import { Toast } from 'vant'
import { platform } from '../utils/platform'

export default {
  data () {
    return {
      order_pay_type: 2 // 支付方式(1微信2支付宝)
    }
  },
  methods: {
    AFPayBridge (data) {
      const officialOrderNumber = data.official_order_number
      // 支付宝支付
      if (this.order_pay_type === 2) {
        if (platform.isWeixin) {
          this.$router.push({ name: 'PayBridge', query: { alipayForm: decodeURIComponent(officialOrderNumber) } })
        } else {
          const div = document.createElement('div')
          div.innerHTML = officialOrderNumber
          document.body.appendChild(div)
          document.forms[0].submit()
        }
      } else {
        // 微信支付
        if (platform.isWeixin) { // 微信内
          this.weixinPay({
            ...officialOrderNumber,
            callback: data.callback
          })
        } else if (platform.isAlipay) { // 支付宝内
          // this.$router.push({ name: 'PayBridge', query: { wxpayHref: '' } })
          Toast('请使用微信打开')
        } else {
          // window.location.replace()
          Toast('请使用微信打开')
        }
      }
    },
    async weixinPay (data) {
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(data), false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(data))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(data))
        }
      } else {
        this.onBridgeReady(data)
      }
    },
    onBridgeReady (data) {
      /* eslint-disable-next-line */
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: data.app_id,
          timeStamp: data.time_stamp,
          nonceStr: data.nonce_str,
          package: data.package,
          signType: data.sign_type,
          paySign: data.pay_sign
        },
        function (res) {
          /* eslint-disable-next-line */
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            data.callback && data.callback()
          } else {
            Toast.fail('支付失败！')
          }
        }
      )
    }
  }
}
