<template>
	<view class="cash">
		<view class="cash-top">
			<view class="leiji">可用余额</view>
			<text class="num" style="font-weight: bold;font-size: 60upx;color: #000;margin-bottom: 10px">￥{{ walletmoney }}</text>
			<!-- #ifdef H5 -->
			<view class="tishi">支持支付宝充值，输入充值金额，最低1元</view>
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<view class="tishi">支持微信、支付宝充值，输入充值金额，最低1元</view>
			<!-- #endif -->
		</view>
		<view style="height: max-content;background-color: #FFFFFF;box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;margin: 0upx 30upx;border-radius: 20upx;">
			<view style="display: flex;flex-direction: row;padding: 35upx 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">充值金额</view>
			</view>
			<view style="display: flex;flex-direction: row;padding: 0upx 20upx; margin-top: 10upx;">
				<view style="font-size: 28upx;color: #333333;display: flex;align-items: center;">¥</view>
				<input type="number" v-model="money" placeholder="请输入金额" style="font-size: 30upx;color: #333333;text-align: left;margin-left: 10upx;width: 100%;" />
			</view>
			<view style="background: #E6E6E6;width: 100%;height: 1upx;"></view>

			<view style="display: flex;flex-direction: row;padding: 20upx;margin-top: 20upx;">
				<view style="font-size: 28upx;color: #333333;font-weight: bold;">选择充值方式</view>
			</view>

			<view style="padding: 0 20upx;" v-if="openLists.length > 0">
				<view style="display: flex;height: 100upx;align-items: center;padding-bottom: 20upx;" v-for="(item,index) in openLists"
				 :key='index'>
					<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
					<view style="font-size: 30upx;color: #333333;margin-left: 20upx;width: 70%;">{{item.text}}</view>
					<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
						<label class="tui-radio">
							<radio color="#FF332F" :checked="openWay === item.id ? true : false" />
						</label>
					</radio-group>
				</view>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
	<!-- 	<button style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" @click="recharge" v-if="openid!=''">确认支付</button>
		<button  v-else style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" class='bottom' open-type="getUserInfo" withCredentials="true"
		 lang="zh_CN" @getuserinfo="wxGetUserInfo">
			立即登录
		</button> -->
		<!-- <button style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" @click="recharge" v-if="openid!=''">确认支付</button> -->
		<button   style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" class='bottom' open-type="getUserInfo" withCredentials="true"
		 lang="zh_CN" @getuserinfo="wxGetUserInfo">
			确认支付
		</button>
		<!-- #endif --> 
		<!-- #ifndef MP-WEIXIN -->
		<button style="background: #FF332F;margin: 30upx; border-radius: 50upx;color: #FFFFFF;" @click="recharge">确认支付</button>
		<!-- #endif -->
		
	
	</view>
</template>

<script>
	export default {
		data() {
			return {
				money: '',
				walletmoney: '0',
				providerList: [],
				provider: '',
				disc:'',
				openWay: '1',
				wallet: [],
				CheckRechargevalue: '1',
				openLists: [],
				openid:''
			};
		},
		onShow() {
			this.getwalletMoney();
		},
		onNavigationBarButtonTap() {
			this.goDetail();
		},
		onLoad(params) {
			let openid=this.$queue.getData("openid")
			 this.openid=openid;
			 
			this.getCheckRecharge();
			if (params.title) {
				uni.setNavigationBarTitle({
					title: params.title
				})
			}
			this.getwalletMoney();

			// #ifdef  H5
			let openId = this.$queue.getData('openid');
			let userId = this.$queue.getData('userId');
			let that = this;
			if (userId) {
				if (!openId) {
					if (window.location.href.indexOf('?code=') !== -1 || window.location.href.indexOf('&code=') !== -1) {
						let code;
						if (window.location.href.indexOf('?code=') !== -1) {
							code = window.location.href.split('?code=')[1].split('&')[0];
						} else {
							code = window.location.href.split('&code=')[1].split('&')[0];
						}
						if (userId) {
							that.$Request.getT('/user/openId/' + code + '/' + userId).then(res => {
								that.$queue.setData('openid', res.data);
							});
						}
					}
				}
			}
			// #endif
			uni.getProvider({
				service: 'payment',
				success: e => {
					console.log('payment success:' + JSON.stringify(e));
					let providerList = [];
					e.provider.map(value => {
						switch (value) {
							case 'alipay':
								providerList.push({
									name: '支付宝',
									id: value,
									loading: false
								});
								break;
							case 'wxpay':
								providerList.push({
									name: '微信',
									id: value,
									loading: false
								});
								break;
							default:
								break;
						}
					});
					this.providerList = providerList;
				},
				fail: e => {
					console.log('获取支付通道失败：', e);
				}
			});
		},
		methods: {
			wxGetUserInfo(e){
				 
					let that = this;
					uni.showLoading({
						title: '请等待',
						mask: false
					})
				if (e.detail.errMsg == "getUserInfo:ok") { 
					 uni.hideLoading()
				 
						that.login() 
					
				}else{
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: '您已拒绝授权，请重新点击并授权！',
						showCancel: false,
						confirmText: "确定",
						confirmColor: "#FF2A46",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							}
						}
					});
				}
			}, 
			login() {
				let that = this;
				let url = "/wx/mp/login";
				uni.showLoading({
					title: ''
				});
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) { 
						let code = loginRes.code 
						that.$Request.getT('/appLogin/wx/login?code=' + code).then(res =>{ 
							console.log('request',res)
							if(res.code === 0){
								let openid=res.data.open_id
								that.openid=openid;
								// console.log('that.openid',this.openid)
								// recharge
								uni.hideLoading();
								that.recharge()
								
							}else{
								
							}
						}); 
					},
				});
			},
			// pay(openid){
				
			// },
			getCheckRecharge() {
				this.$Request.getT('/common/type/97').then(res => {
					if (res.code === 0) {
						this.CheckRechargevalue = res.data.value; //1,企业	2，个人
						this.openLists = [];
						if (res.data.value == 1) {
							// #ifdef MP-WEIXIN
							this.disc = '支持微信充值，输入充值金额，最低1元';
							this.openWay = '2';
							let data1 = {};
							data1.id = '2';
							data1.image = '../../static/img/share/icon_weixin.png';
							data1.text = '微信';
							this.openLists.push(data1);
							// #endif
							// #ifdef APP-PLUS
							this.disc = '支持微信、支付宝充值，输入充值金额，最低1元';
							let data = {};
							data.id = '1';
							// data.image = '../../static/img/my/zhifubao.png';
							data.image = '';
							data.text = '支付宝';
							this.openLists.push(data);
							let data1 = {};
							data1.id = '2';
							data1.image = '../../static/img/share/icon_weixin.png';
							data1.text = '微信';
							this.openLists.push(data1);
							// #endif
							// #ifdef H5
							let target = navigator.userAgent.toLowerCase();
							let ua = navigator.userAgent.toLowerCase();
							this.openLists = [];
							if (ua.indexOf('micromessenger') !== -1) {
								this.disc = '支持微信充值，输入充值金额，最低1元';
								this.openWay = '2';
								let data1 = {};
								data1.id = '2';
								data1.image = '../../static/img/share/icon_weixin.png';
								data1.text = '微信';
								this.openLists.push(data1);
							} else {
								this.disc = '支持支付宝充值，输入充值金额，最低1元';
								this.openWay = '1';
								let data = {};
								data.id = '1';
								// data.image = '../../static/img/my/zhifubao.png';
								data.image = '';
								data.text = '支付宝';
								this.openLists.push(data);
							}
							// #endif
						 
						} else {
							this.disc = '支持支付宝充值，输入充值金额，最低1元';
							this.openWay = '1';
							let data = {};
							data.id = '1';
							// data.image = '../../static/img/my/zhifubao.png';
							data.image = '';
							data.text = '支付宝';
							this.openLists.push(data);
						}
					}
				});
			},
			selectWay: function(item) {
				this.openWay = item.id;
				console.log(this.openWay)
			},
			//获取获取额度
			goDetail() {
				uni.navigateTo({
					url: './rechargeDetail'
				});
			},
			getwalletMoney() {
				let userId = this.$queue.getData('userId');
				this.$Request.getJ('/userMoney/selectUserMoney?userId=' + userId).then(res => {
					if (res.code === 0) {
						this.walletmoney = res.data.money;
						this.wallet.push(res.data);
					}
					uni.hideLoading();
				});
			},
			recharge() {
				let that=this;
				if (!/^\d+$/.test(this.money)) {
					uni.showToast({
						icon: 'none',
						title: '请输入正确金额，不能包含中文，英文，特殊字符和小数'
					});
					return;
				}
				if (this.money < 1) {
					uni.showToast({
						icon: 'none',
						title: '金额必须大于1元'
					});
					return;
				}
				if (this.openWay == undefined) {
					uni.showToast({
						icon: 'none',
						title: '请选择支付方式'
					});
					return;
				}
				uni.showLoading({
					title: '支付中...'
				});
				let userId = this.$queue.getData('userId');
				if (this.CheckRechargevalue == '1') {
					//1，支付宝，2，微信
					if (this.openWay == '1') {
						// #ifdef APP-PLUS
						this.$Request.postJson('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(res => {
							this.isCheckPay(res.code, 'alipay', res.data);
						});
						// #endif
						// #ifdef MP-WEIXIN
						// 支付
						// let openid=that.openid
						
						let userId=that.$queue.getData('userId');
						console.log(this.openid,userId,this.money)
						that.$Request.postT('/api/order/wxPayWx?userId='+userId+'&wxId='+this.openid+'&money='+this.money*100).then(res=>{
							 
							console.log(res)
							uni.requestPayment({
							    provider: 'wxpay',
							    timeStamp: res.timestamp,
							    nonceStr: res.noncestr,
							    package: res.package,
							    signType: res.signType,
							    paySign:  res.sign,
							    success: function (res) {
							        console.log('success:' + JSON.stringify(res));
									uni.showToast({
										title:'支付成功',
										icon:'success'
									})
												  
							    },
							    fail: function (err) {
							        console.log('fail:' + JSON.stringify(err));
									uni.showToast({
										title:'支付失败',
										icon:'none'
									})
							    }
							});
						})
						// #endif
						// #ifdef H5
						this.$Request.postT('/api/aliPay/payH5?money=' + this.money + '&userId=' + userId).then(res => {
							if (res.code === 0) {
								const div = document.createElement('div')
								div.innerHTML = res.data //此处form就是后台返回接收到的数据
								document.body.appendChild(div)
								document.forms[0].submit()
							} else {
								uni.showToast({
									icon: 'none',
									title: '支付失败!'
								});
							}
						});
						// #endif
					} else if (this.openWay == '2') {
						// #ifdef H5
						this.$Request.postJson('/api/order/wxPayJsApi?userId=' + userId + '&money=' + this.money * 100).then(res => {
							this.callPay(res);
						});
						// #endif
						// #ifdef APP-PLUS
						this.$Request.postJson('/api/order/wxPayApp?userId=' + userId + '&money=' + this.money * 100).then(res => {
							this.isCheckPay(res.code, 'wxpay', JSON.stringify(res.data));
						});
						// #endif
						// #ifdef MP-WEIXIN
						// 支付
						
						let userId=that.$queue.getData('userId');
						that.$Request.postT('/api/order/wxPayWx?userId='+userId+'&wxId='+this.openid+'&money='+this.money*100).then(res=>{
							 
							console.log('支付接口',res)  
								uni.requestPayment({
								    provider: 'wxpay',
								    timeStamp: res.timestamp,
								    nonceStr: res.noncestr,
								    package: res.package,
								    signType: res.signType,
								    paySign:  res.sign,
								    success: function (res) {
								        console.log('success:' + JSON.stringify(res));
										uni.showToast({
											title:'支付成功',
											icon:'success'
										})
										uni.navigateBack({
											delta:1
										})
								    },
								    fail: function (err) {
								        console.log('fail:' + JSON.stringify(err));
										uni.showToast({
											title:'支付失败',
											icon:'none'
										})
								    }
								});
								
						})
						// #endif
					}
				} else if (this.CheckRechargevalue == '2') {
					// #ifdef APP-PLUS
					this.$Request.postJson('/api/aliPay/payApp?userId=' + userId + '&money=' + this.money).then(res => {
						this.isCheckPay(res.code, 'alipay', res.data);
					});
					// #endif
					// #ifdef MP-WEIXIN
					// 支付
					
					let userId=that.$queue.getData('userId');
					that.$Request.postT('/api/order/wxPayWx?userId='+userId+'&wxId='+this.openid+'&money='+this.money*100).then(res=>{
						 console.log(userId,this.openid,this.money*100)
						console.log('支付接口',res)
						 
						 
							uni.requestPayment({
							    provider: 'wxpay',
							    timeStamp: res.timestamp,
							    nonceStr: res.noncestr,
							    package: res.package,
							    signType: res.signType,
							    paySign:  res.sign,
							    success: function (res) {
							        console.log('success:' + JSON.stringify(res));
									uni.showToast({
										title:'支付成功',
										icon:'success'
									})
										  
							    },
							    fail: function (err) {
							        console.log('fail:' + JSON.stringify(err));
									uni.showToast({
										title:'支付失败',
										icon:'none'
									})
							    }
							});
							
					})
					// #endif
					// #ifdef H5
					this.$Request.postT('/api/aliPay/payH5?money=' + this.money + '&userId=' + userId).then(res => {
						if (res.code === 0) {
							const div = document.createElement('div')
							div.innerHTML = res.data //此处form就是后台返回接收到的数据
							document.body.appendChild(div)
							document.forms[0].submit()
						} else {
							uni.showToast({
								icon: 'none',
								title: '支付失败!'
							});
						}
					});
					// #endif
				} else {
					this.$Request.postJson('/pays/pay?price=' + this.money + '&istype=' + this.openWay + '&userId=' + userId).then(
						res => {
							if (res.data) {
								let data = res.data;
								var url = 'https://pay.paysapi.com?goodsname=' + data.goodsname + '&istype=' + data.istype + '&key=' + data.key +
									'&notify_url=' + data
									.notify_url + '&orderid=' + data.orderid + '&price=' + data.price + '&return_url=' + data.return_url +
									'&uid=' + data.uid + '&orderuid=' + data.orderuid;
								this.$queue.setData('rechargeUrl', url);
								uni.navigateTo({
									url: '../member/webview?url=' + url
								});
							}
						});
				}
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				// d
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(code, name, order) {
				if (code === 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误'
					});
				}
			},
			setPayment(name, order) {
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(this.getwalletMoney(), 3000);
					},
					fail: function(err) {
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			}
		}
	};
</script>

<style lang="less" scoped>
	@import '../../static/css/index.css';

	page {
		background: #F2F2F2;
	}

	#shareit {
		-webkit-user-select: none;
		position: fixed;
		/*width: 100%;*/
		height: 2000px;
		background: rgba(0, 0, 0, 0.85);
		text-align: center;
		top: 0;
		left: 0;
		z-index: 999;
	}

	#shareit img {
		max-width: 100%;
	}

	.arrow {
		width: 100px;
		height: 150px;
		position: absolute;
		right: 5%;
		top: 1%;
	}

	#follow {
		margin-right: 60px;
		margin-left: 30px;
		width: 90%;
		height: 50px;
		line-height: 50px;
		text-align: left;
		text-decoration: none;
		font-size: 18px;
		color: white;
		float: left;
		margin-top: 160px;
	}

	.cash {
		position: absolute;
		background-size: 100%;
		width: 100%;
		height: 225upx;
		border-bottom-left-radius: 20upx;

		.cash-top {
			border-radius: 20upx;
			margin: 30upx 30upx 30upx 30upx;
			height: 260upx;
			padding: 30upx 32upx 70upx 30upx;
			width: 92%;
			box-shadow: rgba(183, 183, 183, 0.3) 0px 1px 10px;
			/* border-bottom: 1px solid gainsboro; */
			//background: #e64340;
			//background-image: url(../../static/img/my/rechargeback.png);
			background: #FFFFFF;
			background-size: 100%;
		}

		.leiji {
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}

		.tishi {
			margin-top: 25upx;
			font-size: 24upx;
			color: #000;
			margin-bottom: 10px;
		}
	}

	.tui-radio {
		display: inline-block;
		padding-left: 28rpx;
		font-size: 36rpx;
		vertical-align: middle;
	}

	.myRadio {
		// height: 16upx;
		// width: 16upx;
		margin-top: 16upx;
		margin-right: 16upx;
	}
</style>
