<template>
	<view class="">
		<u-navbar
			title="收银台"
			:placeholder="true"
			@leftClick="leftClick"
			:autoBack="false"
			 :safeAreaInsetTop="true"
		>
		</u-navbar>
		<view class="page-wrap">
			<view class="pay-way page-wrap">
				  <u-radio-group  v-model="params.paymentMode" placement="column" @change="groupChange">
				   <view class="pay-way-item u-flex u-row-between" @click="selectPayment('wx')">
				    	<view class="left u-flex">
				    		<image class="icon" :src="staticUrl+'/img/payway-wx.png'" mode="aspectFill"></image>
				    		<view class="name">微信支付</view>
				    	</view>
				    	<u-radio name="wx" activeColor="#1677FF" size="36rpx"></u-radio>
				    </view>
					<view :class="{disabled:balanceInfo.balance<params.payAmount}" @click="selectPayment('yue')" class="pay-way-item u-flex u-row-between">
						<view class="left u-flex">
							<image class="icon" :src="staticUrl+'/img/pyway-yue.png'" mode="aspectFill"></image>
							<view class="name">账户余额</view>
							¥ {{balanceInfo.balance}}
						</view>
						<u-radio name="yue" :disabled="balanceInfo.balance<params.payAmount" activeColor="#1677FF" size="36rpx"></u-radio>
					</view>
					<view :class="{disabled:balanceInfo.grantSurplus<params.payAmount}" @click="selectPayment('shouxin')" class="pay-way-item u-flex u-row-between">
						<view class="left u-flex">
							<image class="icon" :src="staticUrl+'/img/pyway-shouxin.png'" mode="aspectFill"></image>
							<view class="name">授信余额</view>
							¥ {{balanceInfo.grantSurplus}}
						</view>
						<u-radio name="shouxin" :disabled="balanceInfo.grantSurplus<params.payAmount" activeColor="#1677FF" size="36rpx"></u-radio>
					</view>
				  </u-radio-group>
			</view>
			<view class="full-btn" v-if="params.paymentMode&&cansubmit" @click="payRoute">去支付<text>¥ {{params.payAmount}}</text></view>
			<view class="full-btn gray" v-else>去支付<text>¥ {{params.payAmount}}</text></view>
			<u-popup :show="checkPassShow" @close="checkPassClose" mode="center">
				<view class="check-pass">
					<view class="title">请输入支付密码</view>
					<!-- <view class="name">商城</view> -->
					<view class="number">¥{{params.payAmount}}</view>
					<view class="the-way u-flex u-row-between">
						<view class="left">支付方式</view>
						<view class="right u-flex">
							<u--image class="image" :src="staticUrl+'/img/qian.png'" width="32rpx" height="32rpx"></u--image>
							<text style="margin-left: 10px;">余额</text>
						</view>
					</view>
					<u-code-input v-model="paypass" 
						:space="0"
						:size="40" 
						@finish="checkPayPassword" 
						:maxlength="6" 
						:adjustPosition="true"
						:dot="true"
						:focus="true"
						:disabled-keyboard="false" >
					</u-code-input>
					<!-- <view class="btn-wrap u-flex">
						<u-button text="取消" @click="checkPassShow=false"></u-button>
						<u-button text="确认" @click="checkPassShow=false"></u-button>
					</view> -->
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	import wxH5 from "weixin-jsapi";
	// #endif
	export default {
		data() {
			return {
				staticUrl:this.$commonConfig.staticUrl,
				fromPage:'',
				customBalance:'',
				credit:'',
				params:{
					paymentMode:null,
					orderId:'',
					openid:'',
					payAmount:'',
					payResult:{},
				},
				checkPassShow:false,
				paypass:'',
				noPaypass:true,
				balanceInfo:{
					balance:0,//	用户余额
					grantQuota:0,//	授信额度
					grantUsed:0,//已使用的额度
					grantSurplus:0,//剩余额度
					isSetPayPassword:0,//是否设置支付密码 0-否 1-是
				},
				cansubmit:true,
				needPayQuery:0,
				payerId:'',
			}
		},
		onShow(page) {	
			// console.log('onShow page',page);
			let allPages = getCurrentPages(); //获取当前页面栈的实例；
			// console.log(allPages);
			let lastPages = allPages.length - 1; // 获得倒数第二个元素的索引；
			console.log(lastPages);
			let option = allPages[lastPages].options; // 获得上个页面传递的参数；
			console.log(option);
			if(option.needPayQuery){
				this.cansubmit = false;
				this.payQuery();
			}
			
			this.getBalanceInfo();
		},
		onLoad(page) {
			console.log('page',page);
			this.fromPage = page.fromPage;
			this.params.orderId = page.orderId;
			this.params.openid = this.vuex_wechatOpenid;
			this.params.payAmount = page.payAmount;
			this.params.paymentMode = page.paymentMode;
			this.needPayQuery = page.needPayQuery;
			this.payerId = page.payerId;
			if(page.needPayQuery){
				this.cansubmit = false;
				this.payQuery();
			}
		},
		methods: {
			leftClick(){
				uni.showModal({
				    title: '提示',
				    content: '是否放弃本次付款！',
				    success: res => {
						if (res.confirm) {
							uni.navigateBack()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
				    }
				});
			},
			getBalanceInfo(){
				this.$u.api.balanceInfo({id:this.vuex_user_info.userid,payerId:this.payerId}).then(res=>{
					this.balanceInfo= res.data;
				}).catch(err=>{
					console.log('balanceInfo',err.data);
				})
			},
			checkPassClose(){
				this.checkPassShow = false;
			},
			payRoute(){
				this.cansubmit = false;
				if(this.params.paymentMode!='wx'){
					this.checkExistPayPassword();
				}else{
					this.gotoPay();
				}
			},
			checkExistPayPassword(){
				if(this.balanceInfo.isSetPayPassword==0){
					this.noPaypass = true;
					uni.showModal({
						title: '还未设置支付密码',
						content: '请先设置支付密码！',
						success: res => {
							if (res.confirm) {
								uni.$u.route('/center/setPaypass', {
									from: 'pay',
									backUrl:'/shopping/order'
								});
							}
						}
					})
				}else{
					this.noPaypass = false;
					this.checkPassShow = true
				}
			},
			checkPayPassword(){
				this.$u.api.checkPayPassword({payPassword:this.paypass}).then(res=>{
					// console.log('res',res.data);
					if(res.msg=='操作成功'){//密码正确
						if(this.params.paymentMode=='wx'){
							this.gotoPay();
						}else if(this.params.paymentMode=='yue'){
							this.gotoBalancePay()
						}else if(this.params.paymentMode=='shouxin'){
							this.gotoQuotaPay()
						}
					}else{
						this.paypass = '';
						uni.showToast({
							title:'密码错误',
							icon:'error'
						});
					}
					
				}).catch(err=>{
					this.paypass = '';
					uni.showToast({
						title:'密码错误',
						icon:'error'
					});
					console.log('checkPayPassword',err);
				})
			},
			gotoPay() {
				this.$u.api.gotoPay({...this.params,payerId:this.payerId}).then(res => {
					// this.payResult = res.data.payInfo;
					// this.payResult.package = res.data.payInfo.packageValue;
					
					// ygh
					if(!res.data.needPay){
						//this.payQuery();
						uni.$u.route('/center/orderdetails', {
							type:'redirectTo',
							id: this.params.orderId
						});
					}else {
						window.location.href = res.data.payInfo;
						
						return
						// 以下未微信原生支付
						this.payResult = res.data.payInfo;
						this.payResult.package = res.data.payInfo.packageValue;
						
						// #ifdef H5
						this.initConfig(this.payResult)
						// #endif 
						// #ifdef MP
						this.wxPay()
						// #endif 
					}
					
					// if(this.params.paymentMode==1||this.params.paymentMode==4){
					// 	this.wxPay()
					// }else{
					// 	uni.$u.route('/shopping/paysuccess');
					// }
					// console.log('gotoPayres', res.data);
				}).catch(err => {
					this.cansubmit = true;
					// this.paypass = '';
					// this.checkPassShow = false;
					console.log('gotoPay', err);
				})
			},
			gotoBalancePay(){
				let that = this;
				this.$u.api.balancePay({orderId:this.params.orderId,payerId:this.payerId}).then(res=>{
					// console.log('res',res);
					uni.showToast({
						title:res.msg,
						icon:'none'
					})
					setTimeout(()=>{
						uni.reLaunch({
							url: `/center/orderdetails?type=redirectTo&id=${that.params.orderId}`
						});
					},1500)
				}).catch(err=>{
					console.log('balancePay',err.data);
				})
			},
			gotoQuotaPay(){
				let that = this;
				this.$u.api.quotaPay({orderId:this.params.orderId,payerId:this.payerId}).then(res=>{
					// console.log('res',res);
					uni.showToast({
						title:res.msg,
						icon:'none'
					})
					setTimeout(()=>{
						uni.reLaunch({
							url: `/center/orderdetails?type=redirectTo&id=${that.params.orderId}`
						});
					},1500)
				}).catch(err=>{
					console.log('quotaPay',err.data);
				})
			},
			wxPay(){
				uni.requestPayment({
					... this.payResult,
				    "provider": "wxpay", 
				    "orderInfo": {
				        // "appid": "wx499********7c70e",  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
				        // "noncestr": "c5sEwbaNPiXAF3iv", // 随机字符串
				        // "package": "Sign=WXPay",        // 固定值
				        // "partnerid": "148*****52",      // 微信支付商户号
				        // "prepayid": "wx202254********************fbe90000", // 统一下单订单号 
				        // "timestamp": 1597935292,        // 时间戳（单位：秒）
				        // "sign": "A842B45937F6EFF60DEC7A2EAA52D5A0" // 签名，这里用的 MD5/RSA 签名
				    },
				    success(res) {
						uni.$u.route('/shopping/paysuccess');
					},
				    fail(e) {
						console.log('wxPayfail',e);
					}
				})				
			},
			/**
			 * 公众号微信支付
			 */
			initConfig() {
				// #ifdef H5
				let that = this
				wxH5.config({
					debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false, 
					appId: that.payResult.appId, // 必填，公众号的唯一标识 
					timestamp: that.payResult.timeStamp, // 必填，生成签名的时间戳     
					nonceStr: that.payResult.nonceStr, // 必填，生成签名的随机串 
					signature: that.payResult.paySign, // 必填，签名 
					jsApiList: ['chooseWXPay', 'checkJsApi'] // 必填，需要使用的JS接口列表 
				})
				wxH5.ready(() => {
					wxH5.chooseWXPay({
						timestamp: that.payResult.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符     
						nonceStr: that.payResult.nonceStr, // 支付签名随机串，不长于 32 位         
						package: that.payResult.packageValue, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）     
						signType: 'SHA1', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'     
						paySign: that.payResult.paySign, // 支付签名     
						success: () => {
							// setTimeout(()=>{
							// 	uni.$u.route('/center/orderdetails', {
							// 		type:'redirectTo',
							// 		id: that.params.orderId
							// 	});
							// },1500)
							that.payQuery();
						},
						fail: (e) => {
							uni.$u.route('/center/order', {
								status: 0
							});
							console.log('wxPayfail', e);
						},
						cancel: () => {
							uni.$u.route('/center/order', {
								status: 0
							});
							that.cansubmit = true;
						}
					})
				})
				// #endif
			},
			payQuery(){
				let that = this;
				let retryCount = 0;
				let maxRetryCount = 5; // 设置最大重试次数
				let interval = 2000; // 设置间隔时间为2秒
				let timeout = 10000; // 设置超时时间为10秒
				let timer;
				uni.showLoading({
					title:'支付结果查询中'
				})
				timer = setInterval(() => {
					retryCount++;
					if (retryCount > maxRetryCount || retryCount * interval > timeout) {
						clearInterval(timer);
						  uni.hideLoading();
						console.log("支付查询超时或达到最大重试次数");
						// 在这里添加超时或达到最大重试次数的处理逻辑
						this.reloadList()
					} else {
						console.log("第" + retryCount + "次查询");
						// 调用查询支付状态的方法
						// 如果支付状态为成功，则清除定时器并处理成功的逻辑
						// 如果支付状态为失败，则清除定时器并处理失败的逻辑
						this.$u.api.payQuery({orderId:this.params.orderId}).then(res=>{
							// 0-未支付 1-已支付 2-支付中 3-支付失败 4-支付退款
							let payStatus = res.data.payStatus;
							if(payStatus===1){
								uni.reLaunch({
									url: `/center/orderdetails?type=redirectTo&id=${that.params.orderId}`
								});
							}else if(payStatus===0||payStatus===2){
								this.payQuery()
							}else if(payStatus===3){
								that.cansubmit = true;
								uni.toast('支付失败')
							}
							clearInterval(timer);
						}).catch(err=>{
							that.cansubmit = true;
							console.log('payQuery',err);
						}).finally(()=>{
							uni.hideLoading()
						})
					}
				}, interval);
			},
			groupChange(e){
				console.log('groupChange',e);
			},
			selectPayment(paymentType) {
			    this.params.paymentMode = paymentType;
			},
			
		}
	}
</script>
<style>
	page{
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
.pay-way{
	background-color: #fff;
	border-radius: 8rpx;
	.pay-way-item {
		padding: 30rpx 10rpx;
		.left{
			.icon{
				width: 40rpx;
				height: 40rpx;
				margin-right: 16rpx;
			}
			.name{
				font-weight: bold;
				margin-right: 40rpx;
			}
		}
		&:not(:last-child){
			border-bottom: 0.5px solid #eee;
		}
		&.disabled{
			.left{
				color: #D8D8D8;
			}
		}
	}
	.left{
		font-size: 30rpx;
		font-weight: 500;
		color: #333333;
		line-height: 42rpx;
	}
}
.full-btn{
	margin-top: 100rpx;
}
/deep/ .u-popup__content{
	overflow: hidden;
	border-radius: 8rpx;
}
.check-pass{
	padding: 24rpx 40rpx 40rpx;
 	.title{
		margin-bottom: 30rpx;
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
		line-height: 50rpx;
		text-align: center;
	}
	.name{
		text-align: center;
		font-size: 30rpx;
		font-weight: 400;
		color: #666666;
		line-height: 42rpx;
		margin-bottom: 10rpx;
	}
	.number{
		text-align: center;
		font-size: 58rpx;
		font-weight: 600;
		color: #FF3538;
		line-height: 81rpx;
		margin-bottom: 30rpx;
	}
	.the-way{
		font-size: 30rpx;
		font-weight: 400;
		color: #333333;
		line-height: 42rpx;
		margin-bottom: 25rpx;
	}
	.btn-wrap{
		
	}
}
</style>