<template>
	<view class="backcor9 pay-syt pd-main">
		<view class="fotct  ">
			<view class="dis-flex flex-center">
				¥<text class=" font28 fontwig6">{{payPrice}}</text>
			</view>
			<view class="fcor666 font14 paddtop10 paddbotm10">
				支付剩余时间<text class="paddleft10">{{countdownm}}:{{countdowns}}</text>
			</view>
		</view>
		<view class="content pd-main backcolorfff border-8r">
			<!-- <radio-group @change="radioChange"> -->
			<view v-for="(item,index) in paytypeList" :key="index" class="">


				<view class="dis-flex bor-b pd15-v" v-if="item == 4" @tap="paytype='4'">
					<image class="pay-img paddtright10" src="/physical-merchants/static/img/yl.png" mode="aspectFit"></image>
					<view class="flex-1 dis-flex flex-sp  ">
						<view class="">
							<view class="">
								银联
							</view>
							<!-- <view class="fcor666">
							建行信用卡支付满40减16,先到先得
						</view> -->
						</view>

						<radio class="radio-ca" :checked="paytype=='4'" color="#FF1A34" />
					</view>
				</view>
				<view class="dis-flex bor-b  pd15-v" v-if="item == 2" @tap="paytype='2'">
					<image class="pay-img paddtright10" src="/physical-merchants/static/img/wechat.png" mode="aspectFit"></image>
					<view class="flex-1 dis-flex flex-sp  ">
						<view class="">
							<view class="">
								微信支付
							</view>

						</view>

						<radio class="radio-ca" :checked="paytype=='2'" color="#FF1A34" />
					</view>
				</view>
				<view class="dis-flex bor-b  pd15-v" v-if="item == 3" @tap="paytype='3'">
					<image class="pay-img paddtright10" src="/physical-merchants/static/img/unioncard.png" mode="aspectFit">
					</image>
					<view class="flex-1 dis-flex flex-sp  ">
						<view class="">
							<view class="">
								汇联通工会卡<text class="font14 fcor666 margle">余额: {{tongCardPrice}}元</text>
							</view>

						</view>

						<radio class="radio-ca" :checked="paytype=='3'" @click="changeRiado()" color="#FF1A34" />
					</view>
				</view>
			</view>
			<!-- </radio-group> -->
		</view>

		<view class="btn-contain backcolorfff">
			<view class="btn-edit fotct fcorfff font18" @click="payMoney()">确认支付<text class="paddleft5">¥{{payPrice}}</text>
			</view>
		</view>

		<ssPaymentPassword ref="paymentPassword" :mode="1" @submit="submitHandle" />
	</view>
</template>

<script>
	import {
		getThirdPartyByDetail,
		findUser,
		getHuiLianTongCardBalance,
		wechatPay,
		cardPay
	} from '@/Utils/Api.js'
	import ssPaymentPassword from '@/components/sanshui-payment-password/index.vue'
	const app = getApp();
	// #ifdef H5
	var jweixin = require('jweixin-module');
	// #endif
	export default {
		data() {
			return {
				// 倒计时
				countdownh: '', //倒计时时
				countdownm: '', // 倒计时分
				countdowns: '', //倒计时秒
				timers: null,
				recinfo: {
					createTime: 1680774642959,
				},

				//start
				orderNo: '', //订单id 20230420145524695497
				payPrice: '', //需要支付的金额
				paytypeList: [], //支付方式

				tongCardPrice: 0, //汇联通工会卡余额
				paytype: '', //选择的支付方式，
				user: '', //用户信息

				PaymentPassword: '',


			}
		},
		components: {
			ssPaymentPassword
		},
		onShow() {
			// 待支付状态
			// if(this.status == 0){
			this.timers = setInterval(() => {
				this.showtime()
			}, 1000)
			// }

			this.findUser()
			this.getThirdPartyByDetail()
		},
		onLoad(options) {
			let obj =JSON.parse(options.obj) 
			this.orderNo = obj.orderNo;
			this.recinfo.createTime = obj.createTime;
			this.payPrice = obj.payPrice

		},
		methods: {
			//查询我的资料
			findUser() {
				let params;
				findUser(params).then(res => {
					if (res.return_code == '000000') {
						app.globalData.userInfo = res.return_data;
						this.user = res.return_data;
						this.getHuiLianTongCardBalance(); //查询工会卡余额
						uni.setStorage({
							key: "user",
							data: res.return_data
						})
					}
				});
			},
			//汇联通工会卡的radioChange
			changeRiado() {
				if (!this.user.setHltCard) {
					uni.showToast({
						icon: 'none',
						title: '当前账号还未绑定,前往绑定',
						duration: 2000,
						success() {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/user/bindingCard/bindingCard'
								})
							}, 1000)
						}
					});
					return;
				}
			},
			//查询工会卡余额
			getHuiLianTongCardBalance() {

				if (this.user.setHltCard && this.user.hltCardNo && this.user.hltCardNo.cardNo) {
					let params = {
						cardNo: this.user.hltCardNo.cardNo
					}
					getHuiLianTongCardBalance(params).then(res => {
						if (res.return_code == '000000') {
							this.tongCardPrice = res.return_data.balance;
						}

					});
				}

			},
			onUnload() {
				clearInterval(this.timers);
			},
			//查询支付方式
			getThirdPartyByDetail() {
				// #ifdef H5
				this.showType = 2;
				// #endif
				// #ifdef MP
				this.showType = 1;
				// #endif
				let datas = {
					platformId: this.showType,
					"companyId": app.globalData.companyId,
					productType: 10
				}
				getThirdPartyByDetail(datas).then(res => {
					if (res.return_code == '000000') {
						this.paytypeList = res.return_data.productPayType.split(',');
						this.paytypeList = this.paytypeList.slice(0, this.paytypeList.length - 1);
						// console.log(this.paytypeList, "this.paytypeList1111111111111111111")
					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}
				});
			},

			// 倒计时
			showtime() {
				var nowtime = (new Date()).getTime(); //获取当前时间
				var endtime = this.recinfo.createTime + 600000; //定义结束时间 600000是10分钟
				var lefttime = endtime - nowtime; //距离结束时间的毫秒数
				var leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)); //计算天数
				var lefth = Math.floor((lefttime / (1000 * 60 * 60) % 24) + leftd * 24) < 10 ? "0" + Math.floor((lefttime /
					(1000 * 60 * 60) % 24) + leftd * 24) : Math.floor((lefttime / (1000 * 60 * 60) % 24) + leftd *
					24); //计算小时数
				var leftm = Math.floor(lefttime / (1000 * 60) % 60) < 10 ? "0" + Math.floor(lefttime / (1000 * 60) % 60) :
					Math.floor(lefttime / (1000 * 60) % 60); //计算分钟数
				var lefts = Math.floor(lefttime / 1000 % 60) < 10 ? "0" + Math.floor(lefttime / 1000 % 60) : Math.floor(
					lefttime / 1000 % 60); //计算秒数
				this.countdownh = lefth; //返回倒计时的字符串
				this.countdownm = leftm; //返回倒计时的字符串
				this.countdowns = lefts; //返回倒计时的字符串
				// 倒计时结束时，显示00:00:00
				if (lefttime <= 0) {
					clearInterval(this.timers);
					uni.redirectTo({
						url:'/pages/user/order_list/order_list?tbIndex='+'-1'
					})
					this.countdownh = this.countdownm = this.countdowns = "00";
					
				}
			},

			//changeCheckBox
			// radioChange(e) {
			// 	// this.yhqType = e.detail.value;

			// },

			//确认支付
			payMoney() {
				
				let that = this;
				if (that.paytype == '') {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if (that.paytype == '2') {
					// #ifdef H5
					let params = {
						"orderNo": that.orderNo,
						"openId": app.globalData.openId,
						"openIdType": 2
					}
					// #endif
					// #ifdef MP
					let params = {
						"orderNo": that.orderNo,
						"openId": app.globalData.openId,
						"openIdType": 1
					}
					// #endif
					wechatPay(params).then(res => {
						if (res.return_code == '000000') {
							// #ifdef MP
							uni.showLoading({
								title: '支付中...'
							})
							uni.requestPayment({
								"appId": res.return_data.appId,
								"nonceStr": res.return_data.nonceStr,
								"package": res.return_data.package,
								"paySign": res.return_data.sign,
								"signType": "MD5",
								"timeStamp": res.return_data.timeStamp,
								success: function(res) {
									
									uni.hideLoading();
									uni.showToast({
										title: '支付成功'
									})
									uni.redirectTo({
										url: "/physical-merchants/classify/order/paymentResult?id=" + that
											.orderNo
										// url: '../../user/order_details/order_details?id=' +that.orderNo
									});
								},
								fail: function(err) {
									uni.hideLoading();
									uni.navigateBack({})
								},
							});
							// #endif

							//判断是否是公众号
							// #ifdef H5
							//判断微信浏览器
							that.payRequest(res);
							// #endif

						} else {
							// that.cancel();
							uni.showToast({
								title: res.return_msg,
								icon: 'none'
							})
						}
					})
					return;
				}
				//使用汇联通支付时需要填写支付密码
				if (that.paytype == '3') {
					if (!that.user.isSetPayPwd) {
						uni.navigateTo({
							url: '/pages/login/updatePas/updatePas'
							// url: '../../login/updatePas/updatePas'
						})
						return;
					}
					if (!that.user.setHltCard) {
						uni.showToast({
							icon: 'none',
							title: '当前账号还未绑定,前往绑定',
							duration: 2000,
							success() {
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/user/bindingCard/bindingCard'
										// url: '../../user/bindingCard/bindingCard'
									})
								}, 1000)
							}
						});
						return;
					}
					that.$refs.paymentPassword.modalFun('show');
				}
				

			},
			payRequest: function(self) {
				let that = this;
				uni.showLoading({
					title: '支付中...'
				})
				jweixin.config({
					// debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: self.return_data.appId, // 必填，公众号的唯一标识
					timestamp: self.return_data.timeStamp, // 必填，生成签名的时间戳
					nonceStr: self.return_data.nonceStr, // 必填，生成签名的随机串
					signature: self.return_data.sign, // 必填，签名，见附录1
					jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				uni.hideLoading();
				jweixin.ready(function() {
					jweixin.checkJsApi({
						jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
						success: function(res) {},
						fail: function(res) {}
					});
					jweixin.chooseWXPay({
						appId: self.return_data.appId,
						timestamp: self.return_data
							.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
						nonceStr: self.return_data.nonceStr, // 支付签名随机串，不长于 32 位
						package: self.return_data
							.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
						signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
						paySign: self.return_data.sign, // 支付签名
						success: function(res) {
							// 支付成功后的回调函数
							uni.showToast({
								title: '支付成功'
							})
							uni.redirectTo({
								url: "/physical-merchants/classify/order/paymentResult?id=" + that
									.orderNo
								// url: '../../user/order_details/order_details?id=' +that.orderNo
							});
						},
						cancel: function(r) {
							uni.navigateBack({})
						},
						fail: function(res) {
							uni.navigateBack({})
						},
						complete: function(res) {

						}
					});
				});

				jweixin.error(function(res) {
					uni.showToast({
						icon: 'none',
						title: '支付失败了',
						duration: 4000
					});
					// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
					/*alert("config信息验证失败");*/
				});
			},

			//输入密码完成
			submitHandle(e) {
				this.PaymentPassword = e.value;
				if (this.PaymentPassword == '') {
					uni.showToast({
						title: '请勿手动关闭弹窗',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				uni.showLoading({
					title: '支付中...'
				})


				let cardNo;
				if (this.paytype == 3) {
					cardNo = this.user.hltCardNo.cardNo;
				}

				let params = {
					"orderNo": this.orderNo,
					"cardNo": cardNo,
					"password": this.PaymentPassword,
					"carLicensePlate": ''
				}
				cardPay(params).then(res => {
					uni.hideLoading();
					if (res.return_code == '000000') {
						uni.showToast({
							title: '支付成功'
						})
						uni.redirectTo({
							url: "/physical-merchants/classify/order/paymentResult?id=" + that.orderNo
							// url: '../../user/order_details/order_details?id=' +this.orderNo
						})
						return;
					}
					// if (res.return_code == '102130') {
					// 	// this.cancel();//取消订单
					// 	uni.navigateTo({
					// 		url: '../../login/updatePas/updatePas'
					// 	})
					// 	return;
					// }
					// if (res.return_code == '102132') {
					// 	// this.cancel();
					// 	uni.showToast({
					// 		title: res.return_msg,
					// 		icon: 'none'
					// 	})
					// 	return;
					// }
					uni.navigateBack({})
					uni.showToast({
						title: res.return_msg,
						icon: 'none'
					})
				})
				return;
			},

		

		// pay(type) {
		// 	uni.navigateTo({
		// 		url: "/physical-merchants/classify/order/paymentResult?type=" + type
		// 	})
		// }
	}
	}
</script>

<style lang="scss" scoped>
	.bor-b {
		border-bottom: 1px solid #666666;

		&:last-of-type {
			border-bottom: none;
		}
	}

	.pay-syt {
		height:calc(100vh - 60px);
		overflow: auto;
	}

	.pay-img {
		width: 30px;
		height: 30px;
	}

	.pd15-v {
		padding: 15px 0;
	}

	.btn-contain {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px;
		box-sizing: border-box;
	}

	.btn-edit {

		height: 50px;
		border-radius: 25px;
		line-height: 50px;
		background-color: #EA3E44;
		margin-bottom: 10px;
	}
</style>
