import { wxLogin } from '@/common/auth.js'
import { checkPayOnlineSwitch, wechatMiniWxPay } from '@/services/api/pay.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 = {
    methods: {
        // 验证微信支付是否可用
        async miniWxPayFor(data) {
            try {
                const res = await checkPayOnlineSwitch()
                if (res.data === 1) {
                    this.weChatMiniWxPay(data)
                } else {
                    // this.$api.navigateTo(`/pages/user/order/order-payment?money=${data.payableAmount}`)
                    console.log('暂不支持线上支付')
                }
            } catch (e) {
                console.log(e)
            }
        },
        // 获取微信支付payment
        async weChatMiniWxPay(data) {
            try {
                // 获取微信code
                const wechatCode = await wxLogin()
                // 微信支付请求 返回支付信息
                const response = await 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)
                if (payFlag) {
                    // 微信支付成功回调 在页面onload中通过this.$on监听orderPaySuccess事件回调
                    console.log('支付成功')
                    this.$emit('orderPaySuccess', data)
                } else {
                    uni.setStorageSync('PAY_ORDER_INFO', data)
                    this.$router.redirectTo('order/pay-faild')
                }
            } catch (error) {
                // 微信支付失败
                if (error.msg === 'error') {
                    uni.setStorageSync('PAY_ORDER_INFO', data)
                    this.$router.redirectTo('order/pay-faild')
                } else {
                    this.$util.msg(error.msg, 2000)
                }
            }
        }
    }
}

export default wechatPay
