import authorize from '@/common/authorize.js'

// 调用微信支付
function wxRequestPayment(payment) {
    return new Promise((resolve, reject) => {
        uni.requestPayment({
            timeStamp: payment.timeStamp,
            nonceStr: payment.nonceStr,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success: () => {
                resolve(true)
            },
            fail: () => {
                reject({ msg: 'error' })
            }
        })
    })
}

// 微信支付
const wechatPay = {
    data() {
        return {
            loadingText: '请稍等...',
            isSubLoading: false,
        }
    },
    methods: {
        // 验证微信支付是否可用
        miniWxPayFor(data) {
            this.isSubLoading = true
            this.PayService.PayOrderOnLineSwitch().then(response => {
                if (response.data === 1) {
                    this.weChatMiniWxPay(data)
                } else {
                    this.isSubLoading = false
                    this.$api.navigateTo(`/pages/user/order/order-payment?money=${data.payableAmount}`)
                }
            })
        },
        // 获取微信支付payment
        async weChatMiniWxPay(data) {
            if (this.loadingText) this.loadingText = '等待支付中'
            try {
                // 获取微信code
                const wechatCode = await authorize.getCode('weixin')
                // 微信支付请求 返回支付信息
                const response = await this.PayService.WeChatMiniWxPay({
                    payAmount: data.payableAmount * 100,
                    payWay: 'WEIXIN',
                    code: wechatCode,
                    orderId: data.orderId
                })
                // 处理支付信息 调用微信支付
                const payment = JSON.parse(response.data.data.payInfo)
                const payFlag = await wxRequestPayment(payment)
                // 支付成功重定向
                uni.setStorageSync('orderInfo', this.hanldOrder.order)
                if (payFlag) {
                    uni.redirectTo({ url: '/pages/user/order/success' })
                } else {
                    uni.redirectTo({ url: '/pages/user/order/error' })
                }
            } catch (error) {
                // 微信支付失败
                if (error.msg === 'error') {
                    uni.setStorageSync('orderInfo', this.hanldOrder.order)
                    uni.redirectTo({ url: '/pages/user/order/error' })
                } else this.$util.msg(error.msg, 2000)
            } finally {
                this.isSubLoading = false
            }
        }
    }
}

export default wechatPay
