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

		<div v-if="browserStatus" key="browser">
			<div class="container">
				<van-cell-group :border="false">
					<van-cell title="订单金额" :value="'￥' + amount" />
					<van-cell title="订单信息" :value="payMap.orderBody" />
					<!-- <van-cell title="收款方" value="深圳大雅乐盟网管教育股份有限公司" /> -->
				</van-cell-group>
			</div>

			<div class="order-loading">
				<p>{{ payType == 'wx_pub' ? '微信支付' : '支付宝支付' }}</p>
				<van-loading type="spinner" color="#14928A" />
			</div>
		</div>
		<div v-else key="browser">
			<div class="error-text">
				<van-icon v-if="errorText" class="error-icon" name="warning-o" />
				{{ errorText }}
			</div>
		</div>
	</div>
</template>

<script>
/* eslint-disable */
import MHeader from '@/components/MHeader'
import { executePayment } from './AdapayApi'
import {
	browser,
	getUrlCode,
	changeTwoDecimal
} from '@/utils/common'
export default {
	name: 'payWxResult',
	components: {
		MHeader
	},
	data() {
		let query = this.$route.query
		const { payMap } = query.payment ? JSON.parse(query.payment) : {}
		return {
			headerStatus: false,
			browserStatus: false,
			payType: query.payType, // 支付方式
			payMap: payMap,
			amount: changeTwoDecimal(0), // 支付金额
			errorText: null
		}
	},
	mounted() {
		// if (window.location.href.indexOf("?#") < 0) {
		// 	window.location.href = window.location.href.replace("#", "?#");
		// }
		// 判断是否在app里面
		// if (!browser().android || !browser().iPhone) {
		// 	this.headerStatus = true
		// }
		//  else {
		// 	document.title = '微信支付'
		// }

		// 判断是否有支付对象
		if(!this.payMap || !this.payType) {
			this.$dialog.alert({
				message: '支付订单信息错误请重新支付'
			}).then(() => {
				this.$router.back()
			})
		} else {
			this.amount = changeTwoDecimal(this.payMap.amount)
			// 判断当前浏览器
			const ua = window.navigator.userAgent.toLowerCase()
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				this.browserStatus = true
                this.getWxPay()
            } else if (ua.match(/AlipayClient/i) == 'alipayclient') {
				this.browserStatus = true
                this.getPayment()
            } else {
				this.errorText = '请在微信或支付宝客户端打开'
				document.title = 'ERROR'
			}
		}
		// this.getWxPay()
	},
	methods: {
		// 下单
		getPayment() {
			try {
                if (!(parseFloat(this.amount) > 0)) {
                    this.$toast('支付金额异常')
                    return
				}
				let { orderNo, sign, amount, orderBody, orderSubject } = this.payMap
                let that = this,
                    payMap = {
						orderNo: orderNo,
						sign: sign,
						amount: amount,
						orderBody: orderBody,
						orderSubject: orderSubject,
						payChannel: this.payType, // 支付渠道
					}
				// 判断是否是微信公众号支付
                if(this.payType == 'wx_pub') {
                    payMap.code = this.code
				}

				this.$toast.loading({
					duration: 0,
					message: '加载中...',
					forbidClick: true
				})

                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: error.toString(),
                    confirmButtonColor: '#269a93'
                })
            }
		},
		scanCodePay(data) {
			// 判断支付方式 如果是 test 模式 支付用测试url 否则用生产url
			if(this.payType == 'alipay_wap') {
				window.location.href = data.expend.pay_info
			} 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
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": payInfo.appId,     //公众号名称，由商户传入
					"timeStamp": payInfo.timeStamp,         //时间戳，自1970年以来的秒数
					"nonceStr": payInfo.nonceStr, //随机串
					"package": payInfo.package,
					"signType": payInfo.signType,         //微信签名方式：
					"paySign": payInfo.paySign //微信签名
				},
				(res) => {
					console.log(res)
					// if(res.err_msg == "get_brand_wcpay_request:ok" ){
						// 使用以上方式判断前端返回,微信团队郑重提示：
						//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					// } else
					// 支付取消或支付失败
					let { orderNo } = this.payMap
					if(res.err_msg == "get_brand_wcpay_request:cancel" || res.err_msg == "get_brand_wcpay_request:fail") {
						// 用户取消支付
						this.$router.replace({
							path: '/levelMusic',
							query: {
								type: "error",
								orderNo: orderNo,
								isBack: "off"
							}
						})
					} else {
						// 使用以上方式判断前端返回,微信团队郑重提示：
						//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						this.$router.replace({
							path: '/levelMusic',
							query: {
								orderNo: orderNo,
								isBack: "off"
							}
						})
					}
				}
			);
		},
		getWxPay() { // 微信公众号支付
			//授权
			let code = getUrlCode('code')
			if (!code) {
				this.goAuth()
			} else {
				this.code = code
				this.getPayment()
			}
		},
		goAuth() { // 用户授权
			let urlNow = encodeURIComponent(window.location.href);
			let scope = 'snsapi_base'; //snsapi_userinfo   //静默授权 用户无感知
			let appid = 'wx751141096e75a4ee';
			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()
	}
}
</script>

<style lang="less" scoped>
	.payWxResult {
		overflow: hidden;
		// background: #fff;
		min-height: 100vh;
	}
	.container {
		background: #fff;
		padding: .15rem 0;
	}
	/deep/.van-cell {
		padding: .12rem .16rem;
	}
	/deep/.van-cell__title, /deep/.van-cell__value {
		flex: auto;
		font-size: .16rem;
		color: #4F4F4F;
	}
	/deep/.van-button {
		font-size: .16rem;
		width: 86%;
		margin: .2rem auto;
	}

	.order-loading {
		padding: .15rem 0;
		margin-top: .15rem;
		background-color: #ffffff;
		text-align: center;
		font-size: .15rem;
		 & > p {
			margin-bottom: .15rem;
		 }
	}
	/deep/.van-loading__spinner {
		width: .5rem;
		height: .5rem;
	}
	.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>
