<template>
	<div class="payDefine">
		<!-- <m-header v-if="headerStatus" /> -->

		<div class="container" v-if="browserStatus">
			<div class="amount">￥{{ amount }}</div>
			<van-cell-group :border="true">
				<!-- 扫码支付 -->
				<van-cell title="订单信息" :value="orderBody" />
				<!-- <van-cell title="收款方" value="深圳大雅乐盟网管教育股份有限公司" /> -->
				<van-cell title="支付方式" :value="payTypeString" />
				<van-cell title="实付金额" :value="'￥' + amount + '元'" />
			</van-cell-group>

			<van-button type="primary" color="#2DC7AA" block size="large" @click="getPayment" round>立即支付</van-button>
		</div>

		<div class="container" else>
			<div class="error-text">
				<van-icon v-if="errorText" class="error-icon" name="warning-o" />
				{{ errorText }}
			</div>
		</div>
	</div>
</template>

<script>
/* eslint-disable */
const axios = require('@/common/axios').default
import MHeader from '@/components/MHeader'
import { executePayment } from './AdapayApi'
import {
	browser,
	changeTwoDecimal,
	getUrlCode,
} from '@/utils/common'
import numeral from 'numeral'
export default {
	name: 'payDefine',
	components: {
		MHeader
	},
	data() {
		let query = this.$route.query
		return {
			headerStatus: false,
			browserStatus: false,
			amount: changeTwoDecimal(query.amount), // 支付金额
			orderNo: query.orderNo, // 订单号
			sign: query.sign, // 签名
			payType: query.payType,
			payTypeString: query.payType == 'wx_pub' ? '微信' : '支付宝',
			errorText: null, // 错误信息
			orderBody: query.orderBody,
			orderSubject: query.orderSubject,
			code: query.code, // 微信授权code码
		}
	},
	mounted() {
		// 删除token
		localStorage.removeItem('Authorization')

		if (window.location.href.indexOf("?#") < 0) {
			window.location.href = window.location.href.replace("#", "?#");
		}
		// 判断当前浏览器
		const payType = this.payType
		const ua = window.navigator.userAgent.toLowerCase()
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			if(payType === 'wx_pub') {
				//授权
				let code = getUrlCode('code')
				if(code) {
					this.code = code // 赋值code码
				}
				this.browserStatus = true
				document.title = '微信支付'
			} else if(payType == 'alipay_qr') {
				this.errorText = '请使用支付宝扫码'
			}
		} else if (ua.match(/AlipayClient/i) == 'alipayclient') {
			if(payType === 'wx_pub') {
				this.errorText = '请使用微信扫码'
			} else if(payType == 'alipay_qr') {
				// 支付宝支付
				this.browserStatus = true
				document.title = '支付宝支付'
			}
		} else {
			this.errorText = '请在微信或支付宝客户端打开'
		}
		this.errorText && (document.title = 'ERROR')
	},
	methods: {
		// 下单
		async getPayment() {
			try {
                if (!(parseFloat(this.amount) > 0)) {
                    this.$toast('支付金额异常')
                    return
                }
                let that = this,
                    payMap = {
						orderNo: this.orderNo,
						sign: this.sign,
						amount: numeral(this.amount).format('0.00'),
						payChannel: this.payType, // 支付渠道
						orderBody: this.orderBody,
						orderSubject: this.orderSubject
					}
				// 判断是否是微信公众号支付
                if(this.payType == 'wx_pub') {
                    payMap.code = this.code
				}
				this.$toast.loading({
					duration: 0,
					message: '加载中...',
					forbidClick: true
				})

                await executePayment(payMap).then(res => {
					this.$toast.clear()
                    let result = res.data
                    if(result.code == 200) {
                        let payment = result.data
                        if (payment.status === 'succeeded') {
							this.scanCodePay(payment)
                        } else if(payment.status == 'failed') {
							this.browserStatus = false
							this.errorText = payment.error_msg
							document.title = 'ERROR'
                        } else if(payment.status == 'pending') {
                            this.$dialog.alert({
                                title: '提示',
                                message: '订单处理中...',
                                confirmButtonColor: '#269a93'
                            })
                        }
                    } else {
                        this.$dialog.alert({
                            title: '提示',
                            message: result.msg,
                            confirmButtonColor: '#269a93'
                        })
                    }
                }).catch(err => {
					this.$toast.clear()
                    this.$dialog.alert({
                        title: '提示',
                        message: JSON.stringify(err),
                        confirmButtonColor: '#269a93'
                    })
                })
            } catch (error) {
                this.$dialog.alert({
                    title: '提示',
                    message: '网络异常，请检查网络连接',
                    confirmButtonColor: '#269a93'
                })
            }
		},
		scanCodePay(data) {
			// 判断支付方式 如果是 test 模式 支付用测试url 否则用生产url
			if(this.payType == 'alipay_qr') {
				let url = data.prod_mode === "false" ? data.expend.qrcode_url + "?payment_id=" + data.id + "&pay_channel=" + data.pay_channel : data.expend.qrcode_url
				window.location.href = url
			} else if(this.payType == 'wx_pub') {
				let tempPayInfo = JSON.parse(data.expend.pay_info)
				this.payInfo = tempPayInfo
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
					}
				}else{
					this.onBridgeReady();
				}
			}
		},
		onBridgeReady() {
			let payInfo = this.payInfo
			let orderNo = this.orderNo
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": payInfo.appId,     //公众号名称，由商户传入
					"timeStamp": payInfo.timeStamp,         //时间戳，自1970年以来的秒数
					"nonceStr": payInfo.nonceStr, //随机串
					"package": payInfo.package,
					"signType": payInfo.signType,         //微信签名方式：
					"paySign": payInfo.paySign //微信签名
				},
				(res) => {
					// if(res.err_msg == "get_brand_wcpay_request:ok" ){
						// 使用以上方式判断前端返回,微信团队郑重提示：
						//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					// } else
					if(res.err_msg == "get_brand_wcpay_request:cancel" || res.err_msg == "get_brand_wcpay_request:fail") {
						// 用户取消支付
						this.$router.replace({
							path: '/paymentResult',
							query: {
								type: "FAILED",
								orderNo: orderNo,
								isBack: "off"
							}
						})
					} else {
						// 使用以上方式判断前端返回,微信团队郑重提示：
						//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						this.$router.replace({
							path: '/paymentResult',
							query: {
								orderNo: this.orderNo,
								isBack: "off"
							}
						})
					}
				}
			);
		},
		goAuth() { // 用户授权
			let urlNow = encodeURIComponent(window.location.href);
			let scope = 'snsapi_base'; //snsapi_userinfo   //静默授权 用户无感知
			let appid = 'wx751141096e75a4ee';
			// let appid = 'wx86f161d5a32af6ac';
			let url =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`;
			window.location.replace(url)
		}
	},
	destroyed() {
		this.$toast.clear()
		this.$dialog.close()
		document.title = '酷乐秀'
	}
}
</script>

<style lang="less" scoped>
	.payDefine {
		overflow: hidden;
		background: #fff;
		min-height: 100vh;
	}
	.amount {
		padding: .3rem 0;
		font-size: .3rem;
		text-align: center;
		font-weight: 600;
	}
	/deep/.van-cell__title, /deep/.van-cell__value {
		flex: auto;
		font-size: .15rem;
		color: #4F4F4F;
	}
	/deep/.van-button {
		font-size: .16rem;
		width: 86%;
    	margin: .2rem auto;
	}
	.error-text {
		font-size: .15rem;
		width: 100%;
		text-align: center;
		color: #3F3F3F;
		margin-top: 100px;
	}

	.error-icon {
		display: block;
		color: #ffb07b;
		font-size: 120px;
		margin-bottom: .3rem;
	}
</style>
