<template>
	<view class="payMoney">
		<view class="step_row">
			<!-- orderStatus1>0表示已支付 -->
			<view class="step" :class="{hui: info.orderStatus>0}"><text>驾校<br>培训费支付</text></view>
			<!-- examinationStatus 0-未支付，1-已支付 2、已开票 -->
			<view class="step step2" :class="{active: info.orderStatus>0&&info.examinationStatus==0}" v-if="info.examinationPrice"><text>场地<br>培训费支付</text></view>
		</view>
		<view class="ul">
			<view class="li">
				<view class="lab">驾校名称</view>
				<view class="txt">{{ info.schoolName}}</view>
			</view>
			<view class="li">
				<view class="lab">班型</view>
				<view class="txt">{{ info.className }}</view>
			</view>
			<view class="li"  v-if="info.orderStatus<1||!info.examinationPrice">
				<view class="lab">学费</view>
				<view class="txt" v-if="schoolPayInfo.price">{{ $u.utils.priceTo(schoolPayInfo.price) }}</view>
			</view>
			<view class="li" v-if="info.orderStatus>0&&info.examinationPrice">
				<view class="lab">训练费</view>
				<view class="txt">{{  $u.utils.priceTo(info.examinationPrice) }}</view>
			</view>
			
			
		</view>
		<!-- <uni-link href="alipays://platformapi/startapp?qrcode=https://pay.hzbank.com.cn/ifsp-payweb/appPayReceive/F67A35324B6C4C2A9591642FD40B46F8" text="https://uniapp.dcloud.io/">666669999</uni-link> -->
		<!-- <a href="alipays://platformapi/startapp?qrcode=https://pay.hzbank.com.cn/ifsp-payweb/appPayReceive/F67A35324B6C4C2A9591642FD40B46F8">搜索720834239</a> -->

		<view class="payWay">
			<view class="h1">请选择支付方式</view>
			<view class="zfb" @click="changePayWay(2)">
				<view class="leftCon">
					<view class="icon">
						<image src="../../../static/images/icon/jiaofei_zfbIphone@2x.png" mode=""></image>
					</view>
					<view class="text">
						支付宝支付
					</view>
					<view class="recommendIcon">
						<image src="../../../static/images/icon/third_img_tuijianIphone@2x.png" mode=""></image>
					</view>
				</view>
				<view class="rightStatusIcon">
					<image src="../../../static/images/icon/jiaofei_zhifu_selectIphone@2x.png" mode="" v-if="payWay==2">
					</image>
					<image src="../../../static/images/icon/jiaofei_zhifu_unselectIphone@2x.png" mode="" v-else></image>
				</view>
			</view>
			<view class="otherWay" @click="showOtherWay=true" v-if="!showOtherWay">
				<view class="txt">其它付款方式</view>
				<view class="icon">
					<image src="@/static/images/icon/third_icon_gengduoIphone@2x.png" mode=""></image>
				</view>
			</view>
			<view class="zfb" @click="changePayWay(1)" v-else>
				<view class="leftCon">
					<view class="icon">
						<image src="../../../static/images/icon/jiaofei_wxIphone@2x.png" mode=""></image>
					</view>
					<view class="text">
						微信支付
					</view>
				</view>
				<view class="rightStatusIcon">
					<image src="../../../static/images/icon/jiaofei_zhifu_selectIphone@2x.png" mode="" v-if="payWay==1">
					</image>
					<image src="../../../static/images/icon/jiaofei_zhifu_unselectIphone@2x.png" mode="" v-else></image>
				</view>
			</view>
		</view>
		
		
		
		
		<view class="" v-if="info.examinationPrice&&info.orderStatus>0&&info.examinationStatus==0">
			<view class="infoTps" >
				<view class="redbg">
					场训时间使用说明: <br>
					一、您选择的场训时间可抵扣科目二培训学时，在考前学员驾驶有教练员随车施教的教练车，进入考场进行适应性训练: <br>
					二、选择场训时间的学员可提前预约公安的科目二考试; <br>
					三、享受优先安排进场考前训练
				</view>
			</view>
			<view class="footBox">
				<view class="btn border" @click="cancelPay" >取消本次支付</view>
				<view class="btn" @click="buyAdaptabilityOrderFn">确认支付</view>
			</view>
		</view>
		
		<!-- <a href='alipays://platformapi/startapp?appId=20000067&url=支付宝收款码支付地址'> 跳转支付宝支付</a> -->

		<view class="payBtnBox" v-if="info.orderStatus==0">
			<!-- <view class="payBtn" @click="goPay">支付</view> -->
			<oneBtn text="支付" @oneBtnClick="goPay"></oneBtn>
		</view>
	</view>
</template>

<script>
	import learnDriveApi from '@/api/learnDrive.js'
	import businessHanldApi from '@/api/businessHandling'
	var UPPay = uni.requireNativePlugin('UP-Pay');
	let polling = null
	let timerNum = 0
	export default {
		data() {
			return {
				trainingOrderId: '',
				trainingApplyId: '',
				info: {},
				schoolPayInfo: {},
				payWay: 2,
				payInfo: {},
				sweixin: null,
				currenPoll: 1,//1轮询培训费, 2轮询场地
				showOtherWay: false,
			}
		},
		computed: {
			showStep2() {
				if(this.info.examinationPrice) return true
				return false
			}
		},
		onLoad(options) {
			// this.trainingOrderId = options.trainingOrderId
			this.trainingApplyId = options.trainingApplyId
			this.getTrainingApplyDetailsFn()
			this.initWx()
		},
		onBackPress() {
			
		},
		onShow() {
			
		},
		beforeDestroy() {
			clearInterval(polling)
			polling = null
			console.log('stop停stop停stop停stop停stop停stop停stop停')
		},
		onPullDownRefresh() {
			this.getTrainingApplyDetailsFn()
			setTimeout(()=>{
				uni.stopPullDownRefresh()
			},1200)
		},
		methods: {
			// 轮询
			async getPrepaidResultFn() {
				if(this.currenPoll==1) {
					await learnDriveApi.getPrepaidResult({trainingOrderId: this.trainingOrderId})
				}else {
					await learnDriveApi.getKwzxPrepaidResult({trainingOrderId: this.trainingOrderId})
				}
				await this.getOrderDetailsFn('poll')
			},
			initWx() {
				// #ifdef APP-PLUS
				console.log("...........");
				plus.share.getServices((s) => {
					var shares = {};
					for (var i = 0; i < s.length; i++) {
						var t = s[i];
						console.log("...........", t);
						shares[t.id] = t;
					}
					var sweixin = shares['weixin'];
					this.sweixin = sweixin
				}, function(e) {
					console.log("获取分享服务列表失败：" + e.message);
				});
				
				//初始化场地支付插件
				    UPPay.initialize({
				        appId:"wx4689f34e374ae2e",//开放平台appid
				        universalLink:"https://payconfig.jaxc.cn/",//微信通用连接(ios端),
				        aliMiniPayScheme: 'kwZxProject',//支付宝小程序AppScheme(ios端),
				    });
				// #endif
			},
			// 获取订单信息
			async getOrderDetailsFn(poll) {
				if(!this.trainingOrderId) return
				const [err, res] = await learnDriveApi.getOrderDetails({
					trainingOrderId: this.trainingOrderId
				})
				console.log('******')
				console.log(res.data)
				this.info = res.data
				if(!poll) return
				if(this.info.orderStatus !=0&&this.currenPoll==1) {
					console.log('停止订单轮询')
					clearInterval(polling)
					polling = null
					timerNum = 1
					if(!info.examinationPrice) {
						uni.navigateTo({
							url: 'pages/learnDriveStep/payMoney/payMoneySuccess'
						})
					}else {
					}
				}
				if(this.info.examinationStatus !=0&&this.currenPoll==2) {
					console.log('停止考务轮询')
					console.log(polling)
					clearInterval(polling)
					polling = null
					uni.navigateTo({
						url: 'pages/learnDriveStep/payMoney/payMoneySuccess'
					})
				}
				console.log('订单详情')
				console.log(res)
			},
			// 切换支付方式
			changePayWay(num) {
				this.payWay = num
			},
			// 创建培训费支付
			async createPrepaidFn() {
				const latLng = await this.$u.utils.getLocation()
				let obj = {
					clientIp: '127.0.0.1',
					deviceId: 'IMEI',
					deviceType: '1',
					ipType: '04',
					riskType: '01',
					verifyRt: '01',
					verifyTp: '01',
					latitude: latLng.lat,
					longitude: latLng.lng,
					payType: this.payWay,
					fromAppurl: 'paymoney://car:8898/carstep',
					rechargeAmount: this.schoolPayInfo.price,
					trainingOrderId: this.trainingOrderId,
					// adaptability: this.info.adaptability,
					// adaptabilityGround: this.info.adaptabilityGround,
				}
				console.log(obj)
				const [err, res] = await learnDriveApi.createPrepaid(obj)
				this.payInfo = res.data
				console.log('this.payInfo支付信息')
				console.log(this.payInfo)
			},
			// 点击去支付培训费
			async goPay() {
				
				// window.location.href = oehurl
				// this.$store.commit('updateWebVeiwUrl', url)
				// uni.navigateTo({
				// 	url: '/pages/commeWebView/indexBusWebView'
				// })
				
				console.log('点击了支付')
				uni.showLoading({
					title: '创建订单...'
				})
				await this.createPrepaidFn()
				if (this.payWay == 1) {
					this.wxPay()
				} else {
					this.zfbPay()
				}
			},
			// 轮询定时
			pollFn() {
				polling = setInterval(async ()=>{
					timerNum ++
					if(timerNum>30) {
						clearInterval(polling)
						polling = null
					}
					await this.getPrepaidResultFn()
				},1000)
				
			},
			zfbPay() {
				uni.hideLoading()
				this.currenPoll = 1
				let url = encodeURIComponent(this.payInfo.appURL)
				this.pollFn()
				// this.pollFn() &scope=auth_base&redirect_uri=回调网址（用于跳转返回app）&state=init'
				// let urls = `alipays://platformapi/startapp?appId=10000007&redirect_uri=com.junan.zhelixueche&scope=auth_base&state=init&qrcode=${url}`
				let urls = `alipays://platformapi/startapp?appId=10000007&qrcode=${url}`
				// let url = encodeURIComponent(this.payInfo.appURL)
				console.log('支付宝路径')
				console.log(this.payInfo.appURL)
				console.log(urls)
				
				// #ifdef APP-PLUS
				plus.runtime.openURL(urls)
				// #endif
				
				// let qrcode = 'https://pay.hzbank.com.cn/ifsp-payweb/appPayReceive/8904853EF97242D09DC1D7F6EE8F3B9D'
				// let urlencodeUrls = encodeURIComponent(qrcode)
				// let url = `alipays://platformapi/startapp?appId=10000007&qrcode=${urlencodeUrls}`
				// #ifdef H5
				window.open(urls)
				// #endif
				
				
			},
			wxPay() {
				this.currenPoll = 1
				this.pollFn()
				// #ifdef APP-PLUS
				this.sweixin ? this.sweixin.launchMiniProgram({
					// path: '/pages/payment/payment?paymoney='+this.info.price+'&ordersn='+this.payInfo.outTradeNo+'&tokenCode='+ this.payInfo.tokenCode, //跳转小程序页面路径 pages/index/index
					path: '/pages/payment/payment?tokenCode=' + this.payInfo.tokenCode, //跳转小程序页面路径 pages/index/index
					type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
					id: 'gh_012fd4bda1c2' //小程序的原始id
				}) : plus.nativeUI.alert('当前环境不支持微信操作!');
				// #endif
				
				
				uni.hideLoading()
			},
			openApp() {
				this.isIos = uni.getSystemInfoSync().platform //判断是否安卓、ios
				if (this.isIos == 'android') {
					let ifr = document.createElement("iframe");
					ifr.src =
						"hbuilder://"; // 这里的hbuilder在manifest.json中配置->“App常用其它设置” -> “Android设置” -> “UrlSchemes” 项中进行设置
					ifr.style.display = "none";
					document.body.appendChild(ifr);
				} else {
					// window.location = "https://apps.apple.com/cn/app/idxxxxxxx" //你的苹果应用app链接 
				}
			},
			// 查询报名详情-
			async getTrainingApplyDetailsFn() {
				if(!this.trainingApplyId) return
				const [err, res] = await learnDriveApi.getTrainingApplyDetails({ trainingApplyId: this.trainingApplyId })
				console.log('查询报名详情')
				console.log(res)
				this.schoolPayInfo = res.data
				this.trainingOrderId = res.data.trainingOrderId
				
				if(!this.trainingOrderId) {
					// // 创建订单
					let obj = {
						trainingApplyId: res.data.trainingApplyId,
						trainingClassId: res.data.trainingClassId,
						trainingSchoolId: res.data.trainingSchoolId,
					}
					const [err2, res2] = await learnDriveApi.createOrder(obj)
					console.log('****创建的订单***')
					console.log(res2)
					this.trainingOrderId = res2.data
					setTimeout(()=>{
						 this.getOrderDetailsFn()
					},1000)
				}
				
				await this.getOrderDetailsFn()
				
			},
			// 取消本次训场支付
			cancelPay() {
				uni.showModal({
					content: '确认要取消适应性训练订单吗？',
					success: async function (res) { 
						if (res.confirm) {
							const [err, res] = await learnDriveApi.cancelAdaptabilityOrder({trainingApplyId: this.trainingApplyId})
							console.log('用户点击了取消训场订单');
							console.log(res)
							if(res.code==0) {
								uni.navigateTo({
									url: 'pages/learnDriveStep/payMoney/payMoneySuccess'
								})
							}
						}
					}
				});
			},
			// 点击训场支付 创建订单
			async buyAdaptabilityOrderFn() {
				const latLng = await this.$u.utils.getLocation()
				let obj = {
					deviceId: 'IMEI',
					clientIp: '127.0.0.1',
					deviceType: '1',
					ipType: '04',
					riskType: '01',
					verifyRt: '01',
					verifyTp: '01',
					latitude: latLng.lat+'',
					longitude: latLng.lng+'',
					payType: this.payWay,
					fromAppurl: 'com.junan.zhelixueche',
					rechargeAmount: this.info.examinationPrice,
					trainingOrderId: this.info.trainingOrderId, 
					
				}	
				const [err, res] = await learnDriveApi.createKwzxPrepaid(obj)
				console.log('创建厂地订单信息')
				console.log(res)
				if(res.code!=0) return
				let resInfo = res.data.appPayRequest
				var payChannel = this.payWay==1?'01':'04'
				this.currenPoll = 2
				this.pollFn()
				//支付渠道 01微信 04支付宝小程序
				var payData = JSON.stringify(resInfo);//服务端下单获取
				UPPay.upPay(payChannel, payData, function(res){
					// 这是支付成功的回调吗?
					console.log('这是训场支付成功的回调吗?')
				    console.log(res);
					if(res.resultCode=='0000') {
						_this.$u.toast(res.resultInfo)
						setTimeout(()=>{
							uni.navigateTo({
								url: 'pages/learnDriveStep/payMoney/payMoneySuccess'
							})
						},1500)
					}
				    
				});
			}
 		}
	}
</script>

<style lang="scss" scoped>
	.payMoney {
		min-height: 100vh;

		.step_row {
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			background-color: #fff;

			.step {
				width: 188rpx;
				height: 86rpx;
				background: url('../../../static/images/icon/leimuyiIphone@2x.png');
				background-size: 100% 100%;
				text-align: center;
				font-size: 24rpx;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				&.hui {
					background: url('../../../static/images/icon/third_bg_huizhi@2x.png');
					background-size: 100% 100%;
					color: #333;
				}

				&.step2 {
					background: url('../../../static/images/icon/leimuyi2Iphone@2x.png');
					background-size: 100% 100%;
					color: #333;
					
					&.active {
						background: url('../../../static/images/icon/jinxingzhongiphone@2x.png');
						background-size: 100% 100%;
						color: #fff;
					}
				}
			}
		}

		.ul {
			width: 100%;
			padding: 0 30rpx;
			background-color: #fff;

			.li {
				width: 100%;
				font-size: 26rpx;
				height: 78rpx;
				line-height: 78rpx;
				display: flex;
				justify-content: space-between;

				.lab {}

				.txt {}
			}
		}

		.payWay {
			padding: 0 32rpx;

			.h1 {
				padding: 40rpx 0 20rpx 0;
			}
			.otherWay {
				display: flex;
				background-color: #fff;
				border-radius: 16rpx;
				padding: 0 16px;
				height: 100rpx;
				justify-content: center;
				align-items: center;
				.txt {
					font-size: 28rpx;
					color: #999;
				}
				.icon {
					width: 20rpx;
					height: 12rpx;
					image {
						width: 100%;
						height: 100%;
						display: block;
					}
					margin-left: 16rpx;
				}
			}
			.zfb {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 0 16px;
				height: 110rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.leftCon {
					display: flex;
					align-items: center;

					.icon {
						width: 48rpx;
						height: 48rpx;

						image {
							display: block;
							width: 100%;
							height: 100%;
						}
					}

					.text {
						font-size: 32rpx;
						color: #333;
						margin: 0 10rpx 0 20rpx;
					}

					.recommendIcon {
						width: 64rpx;
						height: 34rpx;

						image {
							width: 100%;
							height: 100%;
							display: block;
						}
					}
				}

				.rightStatusIcon {
					width: 42rpx;
					height: 42rpx;

					image {
						display: block;
						width: 100%;
						height: 100%;
					}
				}
			}
		}
	}

	.payBtnBox {
		position: fixed;
		bottom: 0;
		left: 0;
		padding: 32rpx;
		width: 100vw;

		// .payBtn {
		// 	width: 100%;
		// 	height: 110rpx;
		// 	border-radius: 8rpx;
		// 	background-color: #5d47ff;
		// 	line-height: 110rpx;
		// 	text-align: center;
		// 	font-size: 32rpx;
		// 	color: #fff;
		// }
	}
	
	.infoTps {
		padding: 32rpx  ;
		.redbg {
			background: #FFEFEF;
			font-size: 26rpx;
			color: #FE5859;
			padding: 16rpx;
			border-radius: 8rpx;
			line-height: 1.5em;
		}
		
	}
	.footBox {
		display: flex;
		padding: 0 32rpx;
		justify-content: space-between;
		.btn {
			width: 48%;
			height: 98rpx;
			background: #2168FC;
			border-radius: 16rpx;
			color: #fff;
			text-align: center;
			line-height: 98rpx;
			&.border {
				background: none;
				border: 1px solid #2168FC;
				color: #2168FC;
				
			}
		}
	}
</style>
