<!-- 支付页面 -->
<template>
	<view class="container">
		<view class="order_info flex_column_start_start">
			<view class="item b_b flex_row_between_center">
				<text class="tit">{{$L('订单编号')}}</text>
				<text class="order_sn">{{payInfo.paySn}}</text>
			</view>
			<view class="item flex_row_between_center">
				<text class="tit">{{$L('订单金额')}}</text>
				<view class="order_amount">
					<text class="unit">￥</text>
					<text class="price_int">{{payInfo.orderAmount?$getPartNumber(payInfo.orderAmount,'int'):''}}</text>
					<text class="price_decimal">{{payInfo.orderAmount?$getPartNumber(payInfo.orderAmount,'decimal'):''}}</text>
				</view>
			</view>
		</view>
		<view class="pay_part flex_column_start_start">
			<text class="title">{{$L('选择支付方式')}}</text>
			<view v-for="(item,index) in payMethod" :key='index' @click="selectPayMethod(item)" :class="{item:true, b_b:index<payMethod.length-1, flex_row_between_center:true}">
				<view class="left flex_row_start_center">
					<image class="pay_icon" :src="item.payIcon" />
					<text class="tit">{{item.payMethodName}}</text>
				</view>
				<view class="right">
					<text class="balance_available" v-if="item.payMethod == 'balance'" :class="{active:filters.toNum(payInfo.balanceAvailable) >= filters.toNum(payInfo.needPay)}">{{'余额：￥'+$getPartNumber(payInfo.balanceAvailable,'int')+$getPartNumber(payInfo.balanceAvailable,'decimal')}}</text>
					<text :class="{iconfont:true, iconziyuan33:selData.payMethod == item.payMethod,iconziyuan43:selData.payMethod != item.payMethod,has_sel:selData.payMethod == item.payMethod}"></text>
				</view>
			</view>
		</view>
		<!-- 余额支付支付密码 start -->
		<view class="balance_password" v-if="balanceCon">
			<view class="balance_password_title">{{$L('支付密码')}}</view>
			<view class="input_password">
				<view class="input_password_con">
					<input type="password" v-model="passwordVal" :placeholder="$L('请输入支付密码')" @blur="passwordBlur" v-if="!isShowPasw"/>
					<input type="text" v-model="passwordVal" :placeholder="$L('请输入支付密码')" @blur="passwordBlur" v-else/>
					<text :class="{iconfont:true,iconziyuan81:isShowPasw,iconziyuan9:!isShowPasw}" @click="showPasword"></text>
				</view>
			</view>
		</view>
		<!-- 余额支付支付密码 end -->
		<view class="btn_recharge flex_row_center_center" @click="pay" :style="{top:windowHeight - 60 + 'px'}">{{$L('立即支付')}}</view>
	</view>
</template>
<!-- '@vue/cli-plugin-babel/preset' -->
<script module="filters" lang="wxs" src="@/utils/filter.wxs"></script>
<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				paySn:'',//支付单号
				payInfo:{},//订单信息
				selData: {},
				payMethod: [], //支付方式
				client: 'wxbrowser',//支付发起来源 pc==pc,mbrowser==移动设备浏览器,app==app,wxxcx==微信小程序,wxbrowser==微信内部浏览器
				payMethodType: 'create',//从哪里进入支付，create 下单，orderList 订单列表 orderDetail 订单详情 recharge 充值
				isAllowAutoPay: true,//当浏览器地址有code时，是否允许自动支付，如果支付失败的话置为false
				autoPayInterval: '',//定时器
				wxBrowerCode: '',//微信浏览器支付的code
				balanceCon:false,	//输入余额支付密码的框是否显示
				passwordVal:'',	//密码值
				isShowPasw:false,	//支付密码是否可见
				hasSetPassword:false,	//用户是否已经设置了余额支付支付密码
				oriUrl:'',//不带code的页面地址
				windowHeight:'',
				ifOnShow:false
			}
		},
		computed: {
			...mapState(['hasLogin', 'userInfo'])
		},
		onHide(){
			this.ifOnShow = true
		},
		onShow(){
			if(this.ifOnShow){
				this.isSetPassword()
			}
		},
		onLoad(option) {
			this.initClient();
			this.paySn = option.paySn;

			//#ifdef H5
			//判断code地址的参数 start
			let cur_code = this.$getQueryVariable('code');
			if(cur_code){
				uni.showLoading({
					title: '支付中...',
					mask: true,
				})
				let oriUrl = option.ori_url+'pages/order/pay';
				let tmp_data = '';
				for(let i in option){
					if(i!='ori_url'){
						tmp_data += i+'='+option[i]+'&'
					}
				}
				oriUrl += '?'+tmp_data;
				this.oriUrl = oriUrl;
				if(this.client == 'wxbrowser'){
					//微信浏览器的话要把浏览器地址里面的code去掉
					history.replaceState({},'',this.oriUrl);
				}
				this.wxBrowerCode = cur_code;
			}
			//判断code地址的参数 end
			//#endif

			this.payMethodType = option.payMethodType!=undefined?option.payMethodType:this.payMethodType;
			this.getPayMethod();
			this.getPayInfo();
			this.isSetPassword();
			uni.getSystemInfo({
			    success:(res)=>{
			        this.windowHeight = res.windowHeight;
			    }
			});
		},
		onUnload(){
			if(this.autoPayInterval){
				 clearInterval(this.autoPayInterval)
			}
		},
		methods: {
			//初始化终端类型
			initClient() {
				//#ifdef APP-PLUS
				this.client = 'app';
				//#endif
				//#ifdef H5
				this.client = this.$isWeiXinBrower()?'wxbrowser':'mbrowser';
				//#endif
				//#ifdef MP-WEIXIN
				this.client = 'wxxcx';
				//#endif
			},
			//获取支付方式
			getPayMethod() {
				let { client,payMethodType,wxBrowerCode } = this;
				this.$request({
					url: 'v3/integral/front/integral/orderPay/payMethod',
					data: {
						source: client,
						type: payMethodType == 'create' || payMethodType == 'orderList' || payMethodType == 'orderDetail' ?1:2,//支付发起类型 1==下单支付，2==余额充值/订单列表
					},
				}).then(res => {
					if (res.state == 200) {
						res.data.map(item => {
							item.payIcon = getApp().globalData.imgUrl+`pay/${item.payMethod}_pay_icon.png`;
						});
						this.payMethod = res.data;
						if(!wxBrowerCode){
							this.selData = this.payMethod[0];
						}else{
							//有code的话要默认选中微信支付，并直接提交订单
							this.selData = this.payMethod.filter(item=>item.payMethod == 'wx')[0];
							let _this = this;
							if(this.isAllowAutoPay){
								this.autoPayInterval = setInterval(function(){
									if(_this.payInfo.needPay!=undefined){
										_this.pay();
										//清除倒计时
										clearInterval(_this.autoPayInterval)
									}
								},1000);

							}
						}

					}
				}).catch((e) => {
				})
			},
			//选择支付方式事件
			selectPayMethod(val) {
				if(val.payMethod == 'balance'){	//余额支付
					if(this.hasSetPassword){
						if(Number(this.payInfo.balanceAvailable) < Number(this.payInfo.needPay)){	//余额小于订单金额
							uni.showToast({
								title:'您的余额不足,请选择其他支付方式！',
								icon:'none'
							})
						}else{
							this.balanceCon = true;
							this.selData = val;
						}
					}else{
						uni.showModal({
							title:'温馨提示!',
							content:'未设置支付密码',
							confirmColor:'#FC1E1C',
							confirmText:'立即设置',
							success:function(res){
								if(res.confirm){
									uni.navigateTo({
										url:'/pages/account/managePwd?source=set_pay'
									})
								}else if(res.cancel){

								}
							}
						})
					}

				}else{
					this.selData = val;
				}
			},
			//余额支付是否已设置过密码
			isSetPassword(){
				this.$request({
					url: 'v3/integral/front/integral/orderPay/payPwdCheck',
					method:'GET',
				}).then(res => {
					if (res.state == 200) {
						this.hasSetPassword = res.data;
					}
				}).catch((e) => {

				})
			},
			//获取支付信息
			getPayInfo(){
				this.$request({
					url: 'v3/integral/front/integral/orderPay/payInfo',
					data: {
						paySn: this.paySn,
						payFrom:this.payMethodType == 'create'?1:2
					},
				}).then(res => {
					if (res.state == 200) {
						this.payInfo = res.data;
					}
				}).catch((e) => {
				})
			},
			//失焦,获取输入密码值
			passwordBlur(e){
				this.passwordVal = e.detail.value;
				var reg = /^[\w.]{6,20}$/;
				//密码的验证 6～20位，英文、数字或符号
				let flag = reg.test(this.passwordVal);
				if(!flag){
					uni.showToast({
						title:'请输入6~20位英文、数字或符号',
						icon:'none',
						duration:1000
					})
					this.passwordVal = ''
				}
			},
			//密码是否可见
			showPasword(){
				this.isShowPasw = !this.isShowPasw
			},
			//立即支付事件
			pay() {
				const {
					selData,client,wxBrowerCode
				} = this;
				let _this = this;
				let param = {};
				param.url = 'v3/integral/front/integral/orderPay/doPay';
				param.method = 'POST';
				param.data = {};
				param.data.payType = selData.payType;
				param.data.payMethod = selData.payMethod;
				param.data.paySn = this.payInfo.paySn;
				if(selData.payMethod == 'balance'){
					//余额支付
					param.data.payPwd = this.passwordVal;	//支付密码,使用余额时必传
				}else{
					if(client == 'wxxcx'){
						//微信小程序支付
					uni.login({
							 success: code => {
								param.data.code = code.code;
								param.data.codeSource = 1 ;//用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
								this.$request(param).then(res => {
									if (res.state == 200) {
										let tmp_data = res.data.payData;
										if(res.data.actionType == null){
											//微信小程序支付
											uni.requestPayment({
												'timeStamp': tmp_data.timeStamp,
												'nonceStr': tmp_data.nonceStr,
												'package': tmp_data.packageValue,
												'signType': 'MD5',
												'paySign': tmp_data.paySign,
												success: function(res) {
													_this.payTip('success');
												},
												fail: function(res) {
													_this.payTip('fail');
												}
											});
										}

									}else{
										_this.$api.msg(res.msg);
									}
								}).catch((e) => {
								})
							}
						});
						return false;
					}else if(client == 'wxbrowser'){
						//微信h5支付
						if(!wxBrowerCode){
							let tar_url = location.href;
							tar_url += location.href.indexOf('?')>-1?'&':'?';
							tar_url += 'ori_url='+location.href;
							let uricode = encodeURIComponent(tar_url)
							window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+getApp().globalData.h5AppId+'&redirect_uri=' + uricode + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
							return false;
						}else{
							param.data.code = wxBrowerCode;
							param.data.codeSource = 2 ;//用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
						}
					}
				}

				this.$request(param).then(res => {
					if (res.state == 200) {
						if(selData.payMethod == 'balance'){
							uni.showToast({
								title:'支付成功!',
								duration:700
							})
							setTimeout(()=>{
								uni.redirectTo({
									url:'/standard/point/order/list'
								})
							},1000)
						}else{
							let tmp_data = res.data.payData;
							if(res.data.actionType == 'redirect'){
								window.location.href = tmp_data;
							}else if(res.data.actionType == null){
								if(client == 'wxbrowser'){
									uni.hideLoading();
									this.wxBrowerCode = '';
									//微信h5支付
									this.$weiXinBrowerPay({
										timestamp: tmp_data.timeStamp,
										nonceStr: tmp_data.nonceStr,
										package: tmp_data.packageValue,
										signType: 'MD5',
										paySign: tmp_data.paySign,
										appId: tmp_data.appId, //此参数可不用
										success: function(r) {
											if (r.errMsg == "chooseWXPay:ok") {
												_this.payTip('success');
											} else {
												_this.payTip('fail');
												_this.isAllowAutoPay = false;//支付失败后禁止自动支付
											}
										},
										cancel: function(r) {
											_this.payTip('fail');
											_this.isAllowAutoPay = false;//支付失败后禁止自动支付
										}
									});
								}else if(client == 'wxxcx'){
									//微信小程序支付
									uni.requestPayment({
										'timeStamp': tmp_data.timeStamp,
										'nonceStr': tmp_data.nonceStr,
										'package': tmp_data.packageValue,
										'signType': 'MD5',
										'paySign': tmp_data.paySign,
										'success': function(res) {
											_this.payTip('success');
										},
										'fail': function(res) {
											_this.payTip('fail');
										}
									});
								}else if(client == 'app'){
									//APP支付
									let provider = '';
									let orderInfo = {};
									if(selData.payMethod == 'wx'){
										provider = 'wxpay';
										orderInfo.appid = tmp_data.appId;
										orderInfo.noncestr = tmp_data.nonceStr;
										orderInfo.package = tmp_data.packageValue;
										orderInfo.partnerid = tmp_data.partnerId;
										orderInfo.prepayid = tmp_data.prepayId;
										orderInfo.timestamp = tmp_data.timeStamp;
										orderInfo.sign = tmp_data.sign;
									}else if(selData.payMethod == 'alipay'){
										provider = 'alipay';
									}
									uni.requestPayment({
										provider: provider,
										orderInfo: provider=='alipay'?res.data.payData:orderInfo, //订单数据
										success: function(res) {
											_this.payTip('success');
										},
										fail: function(err) {
											_this.payTip('fail');
										}
									});

								}
							}else if(res.data.actionType == 'autopost'){
								document.write(res.data.payData);
							}
						}
					}else{
						this.$api.msg(res.msg);
						if(this.passwordVal != ''){
							this.passwordVal = '';
						}
					}
				}).catch((e) => {
				})
			},

			//支付操作完成提示
			payTip(type){
				//如果来自下单，直接跳转订单列表，否则返回上一级页面（订单列表或者订单详情），并更新数据
				if(type == 'success'){
					//提示支付成功
					uni.showToast({
						title:'支付成功!',
						duration:700
					})
				}else if(type == 'fail'){
					//提示支付失败
					this.$api.msg('支付失败,请重试～');
				}
				if(this.client == 'wxbrowser'){
					uni.reLaunch({
					  url: '/pages/order/list?state=0'
					});
					return;
				}
				if(this.payMethodType == 'create'){	//下单
					setTimeout(()=>{
						uni.redirectTo({
							url:'/pages/order/list?state=0'
						})
					},1000)
				}else{
					const pages = getCurrentPages(); //当前页面栈
					if (pages.length > 1) {
						const beforePage = pages[pages.length - 2]; //获取上一个页面实例对象
						if(this.payMethodType == 'orderList'){
							beforePage.$vm.loadData(); //触发上个面中的方法获取订单列表 *loadData为上个页面的方法*
						}else if(this.payMethodType == 'orderDetail'){
							beforePage.$vm.getOrderDetail(); //触发上个面中的方法获取订单详情 *getOrderDetail为上个页面的方法*
						}
					}
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #FFFFFF;
		width: 750rpx;
		margin: 0 auto;
	}

	.container {
		display: flex;
		flex-direction: column;
		flex: 1;

		.order_info {
			border-top: 20rpx solid #F5F5F5;
			width: 750rpx;
			background: #fff;
			.item{
				position: relative;
				height: 100rpx;
				width: 100%;
				padding: 0 20rpx;
				.tit{
					color: $main-font-color;
					font-size: 30rpx;
				}
				.order_sn{
					color: #2D2D2D;
					font-size: 26rpx;
				}
				&.b_b:after{
					left: 20rpx;
				}
				.order_amount{
					color: $main-color;
					font-weight: bold;

					.unit,
					.price_decimal {
						font-size: 24rpx;
						margin-right: 3rpx;
						line-height: 24rpx;
					}
					.price_int {
						font-size: 34rpx;
						line-height: 34rpx;
					}
				}
			}
		}

		.pay_part {
			border-top: 20rpx solid #F5F5F5;
			background: #fff;
			flex: 1;

			.title {
				color: $main-font-color;
				font-size: 32rpx;
				margin-top: 30rpx;
				margin-left: 20rpx;
			}

			.item {
				width: 100%;
				padding: 20rpx;
				position: relative;

				.left {
					.pay_icon {
						width: 80rpx;
						height: 80rpx;
					}

					.tit {
						color: $main-font-color;
						font-size: 28rpx;
						margin-left: 20rpx;
					}

				}
				.right{
					.balance_available{
						font-size: 28rpx;
						color: #999;
						margin-right: 20rpx;
					}
					.active{
						color: #FC1C1C;
					}

					.iconfont {
						color: $main-third-color;
						font-size: 32rpx;
					}

					.has_sel {
						color: $main-color;
					}

					&.b_b:after {
						left: 20rpx;
					}
				}

			}
		}
		.balance_password{
			border-top: 20rpx solid #F5F5F5;
			.balance_password_title{
				width:750rpx;
				height: 100rpx;
				display: flex;
				align-items: center;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
				line-height: 39rpx;
				padding-left: 20rpx;
				box-sizing: border-box;
				border-bottom: 1rpx solid #F5F5F5;
				background: #FFFFFF;
			}
			.input_password{
				width: 750rpx;
				height: 86rpx;
				background: #FFFFFF;
				.input_password_con{
					margin: 0 41rpx;
					height: 86rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1rpx solid #F5F5F5;
					input{
						font-size: 26rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #999999;
						line-height: 39rpx;
					}
					text{
						color: #666666;
						font-size: 20rpx;
					}
				}
			}
		}

		.btn_recharge {
			width: 670rpx;
			height: 88rpx;
			background: #F30300;
			border-radius: 44rpx;
			color: #fff;
			font-size: 36rpx;
			position: absolute;
			// left: 40rpx;
			margin: 0 auto;
			left: 0;
			right: 0;
		}
	}
</style>
