<template>
	<view class="wallet">
		<view v-if="XCXIsSelect != '否'">
			<view class="bg bg1">
				<view class="flex align-center justify-between">
					<view style="font-size: 32rpx;color: #222222;">当前余额</view>
					<view v-if="jsczSel != '否'" class="text-lg" style="text-decoration:underline;color: #2FB57A;"
						@tap="goMyLB">我的老板</view>
				</view>
				<view class="flex margin-top-sm">
					<!-- <view class="text-xxl"></view> -->
					<view style="font-size: 48rpx;color: #222222;font-weight: bold;">￥{{money}}元</view>
				</view>
			</view>
			<view class="bg">
				<view style="font-size: 32rpx;color: #222222;margin-bottom: 28rpx;">提现金额</view>
				<view class="padding-bottom-sm">
					<input style="font-size: 36rpx;color: #222222;font-weight: bold;" type="number" placeholder="请输入提现金额" placeholder-style="color:#AAAAAA;font-weight: 500;" v-model="moneyNum">
				</view>
				<view style="width: 654upx;margin: 0 auto;height: 1upx;background: #E6E6E6;"></view>
				<view style="font-size: 24rpx;color: #AAAAAA;margin-top: 24rpx;">{{placeholder}}</view>
				<view style="font-size: 24rpx;color: #F24E4E;margin-top: 24rpx;" v-if="txMsg">*{{txMsg}}</view>
			</view>
			<view class="bg">
				<view>
					<view v-for="(item,index) in openLists" :key='index'>
						<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 0;"
							v-if="item.text === '微信' && wxTxSel != '否'">
							<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;width: 80%;">{{item.text}}
							</view>
							<radio-group name="openWay" style="margin-left: 20upx;transform: scale(.7);" @tap='selectWay(item)'>
								<label class="tui-radio">
									<radio color="#1EDA94" :checked="openWay === item.id ? true : false" />
								</label>
							</radio-group>
						</view>
						<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 0;"
							v-if="item.text === '银联' && ylTxSel != '否'">
							<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;width: 80%;">{{item.text}}
							</view>
							<radio-group name="openWay" style="margin-left: 20upx;transform: scale(.7);" @tap='selectWay(item)'>
								<label class="tui-radio">
									<radio color="#1EDA94" :checked="openWay === item.id ? true : false" />
								</label>
							</radio-group>
						</view>
						<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 0;"
							v-if="item.text === '支付宝'">
							<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;width: 80%;">{{item.text}}
							</view>
							<radio-group name="openWay" style="margin-left: 20upx;transform: scale(.7);" @tap='selectWay(item)'>
								<label class="tui-radio">
									<radio color="#1EDA94" :checked="openWay === item.id ? true : false" />
								</label>
							</radio-group>
						</view>
					</view>
				</view>
			</view>
			<view class="btn" @click="cashMoney">立即提现</view>

		</view>

		<view class="icon-box" v-if="XCXIsSelect != '否'">
			<view class="icon-item" @click="goNav('/my/wallet/zhifubao')">
				<image class="icon" src="/my/static/icon1.png" mode=""></image>
				<view class="label">提现账号</view>
			</view>
			<view class="icon-item" @click="goNav('/my/wallet/mymoneydetail')">
				<image class="icon" src="/my/static/icon2.png" mode=""></image>
				<view class="label">钱包明细</view>
			</view>
			<view class="icon-item" @click="goNav('/my/wallet/cashList')">
				<image class="icon" src="/my/static/icon3.png" mode=""></image>
				<view class="label">提现记录</view>
			</view>
			<view class="icon-item" @click="goNav('/my/wallet/yinhangka')" v-if="ylTxSel != '否'">
				<image class="icon" src="/my/static/icon4.png" mode=""></image>
				<view class="label">银行卡账号</view>
			</view>
		</view>
	</view>
</template>

<script>
	var jwx = require('../../js_sdk/jweixin-1.6.0.js')
	export default {
		data() {
			return {
				XCXIsSelect: '否',
				tablist: [{
					id: 1,
					name: '我的余额'
				}, {
					id: 2,
					name: '我的收益'
				}],
				bankCard: '',
				title_color: 2,
				// bgCol1: '#1E1F31',
				bgCol2: '#2FB57A',
				money: 0,
				avatar: '',
				Profit: 0,
				openLists: [
				// 	{
				// 	image: '../static/zhifubao.png',
				// 	text: '支付宝',
				// 	id: 1
				// }, 
				{
					image: '../static/icon_weixin.png',
					text: '微信',
					id: 3
				}, {
					image: '../static/union.png',
					text: '银联',
					id: 2
				}],
				wxTxSel: '否',
				ylTxSel: '否',
				jsczSel: '否',
				openWay: 3,
				wallet: [{
						id: 1,
						num: '5',
						price: '5',
						isSelect: true
					},
					{
						id: 2,
						num: '20',
						price: '20',
						isSelect: false
					},
					{
						id: 3,
						num: '50',
						price: '50',
						isSelect: false
					},
					{
						id: 4,
						num: '100',
						price: '100',
						isSelect: false
					},
					{
						id: 5,
						num: '200',
						price: '200',
						isSelect: false
					},
					{
						id: 6,
						num: '500',
						price: '500',
						isSelect: false
					}
				],
				moneyNum: null,
				thisSelect: {
					id: 1,
					num: '5',
					price: '5',
					isSelect: true
				},
				ylSel: '否',
				charge: 0, //提现手续费
				maxMoney: 0, //最高提现额度
				minMoney: 0, //最低提现额度
				ratio: '', //金元比例
				placeholder: '',
				renzheng: 0,
				sp: 0,
				txMsg: ''
			}
		},
		onLoad() {
			this.wxTxSel = this.$queue.getData('wxTxSel');
			this.ylTxSel = this.$queue.getData('ylTxSel');
			this.jsczSel = this.$queue.getData('jsczSel');
			this.XCXIsSelect = this.$queue.getData("XCXIsSelect");
			if (this.XCXIsSelect != '否') {
				uni.setNavigationBarTitle({
					title: '我的钱包'
				})
			} else {
				uni.setNavigationBarTitle({
					title: '我的信息'
				})
			}
			this.txMsg = this.$queue.getData('txMsg');
			this.avatar = uni.getStorageSync('avatar')
			this.renzheng = uni.getStorageSync("renzheng")
		},
		onShow() {
			this.ylSel = this.$queue.getData('ylSel');
			this.getMoney()
			this.getCharge()
			this.getMinMoney()
			this.getMaxMoney()
			this.getRatio()
			this.getUserInfo()

		},
		methods: {
			goMyLB() {
				uni.navigateTo({
					url: '/my/wallet/therapist'
				});
			},
			//退保证金
			TuiPrice() {
				let that = this
				let zhiFuBao = uni.getStorageSync('zhiFuBao')
				let zhiFuBaoName = uni.getStorageSync('zhiFuBaoName')

				if (!zhiFuBao && !zhiFuBaoName) {
					uni.navigateTo({
						url: '/my/wallet/zhifubao'
					})

				} else {
					let renzheng = uni.getStorageSync("renzheng")
					console.log(renzheng)
					if (renzheng == 2 || renzheng == 5) {
						uni.showModal({
							title: '提示',
							content: '是否确定退还保证金？退还后将不能发布订单',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									that.$Request.post("/app/userCertification/exitMoney").then(res => {
										console.log(res)
										if (res.msg == '您还有未下架的订单，请先下架！') {
											uni.showToast({
												title: res.msg,
												icon: 'none'
											});
										} else if (res.msg == '您还有未服务的订单，请先完成！') {
											uni.showToast({
												title: res.msg,
												icon: 'none'
											});
										} else if (res.msg == 'success') {
											uni.showToast({
												title: '退还成功',
												icon: 'none'
											});
											uni.switchTab({
												url: '/pages/my/index'
											})
										}
									});
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});

					}

				}

			},
			getUserInfo() {
				this.$Request.get("/app/user/selectUserById").then(res => {
					if (res.code == 0) {
						
						this.avatar = res.data.avatar ? res.data.avatar : '../../static/logo.png'
						uni.setStorageSync('avatar', res.data.avatar)
						if (res.data.bankCard) {
							this.bankCard = res.data.bankCard
						}
					}
				});
			},
			// 提现手续费
			getCharge() {
				this.$Request.get("/app/common/type/152").then(res => {
					if (res.code == 0) {
						this.charge = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最低提现额度
			getMinMoney() {
				this.$Request.get("/app/common/type/112").then(res => {
					if (res.code == 0) {
						this.minMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最高提现额度
			getMaxMoney() {
				this.$Request.get("/app/common/type/153").then(res => {
					if (res.code == 0) {
						this.maxMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 金元比例
			getRatio() {
				this.$Request.get("/app/common/type/154").then(res => {
					if (res.code == 0 && res.data.value) {
						this.ratio = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
						this.wallet.forEach(re => {
							re.num = re.price * res.data.value
						})
					}
				});
			},
			cut(e) {
				this.title_color = e
			},
			goNav(url) {
				uni.navigateTo({
					url
				})
			},
			active(e) {
				this.wallet.forEach(res => {
					if (res.id == e.id) {
						res.isSelect = true
						this.thisSelect = e
					} else {
						res.isSelect = false
					}
				})
			},
			// 我的余额
			getMoney() {
				this.$Request.get("/app/userMoney/selectMyMoney").then(res => {
					if (res.code == 0 && res.data) {
						console.log(res.data.money)
						this.money = res.data.money
					}
				});
			},
			selectWay: function(item) {
				this.openWay = item.id;
			},

			pay() {
				let data = {
					money: this.thisSelect.price
				}
				console.log(data)
				// 获取订单编号
				this.$Request.post("/app/appOrder/insertOrder", data).then(res => {
					console.log(res, '********')
					uni.showLoading({
						title: '支付中...'
					});
					if (res.code == 0) {
						// this.Profit = res.data
						if (this.openWay == 2) {
							// #ifdef APP-PLUS
							// 微信APP支付 根据订单id获取支付信息
							this.$Request.post("/app/wxPay/payAppOrder", {
								id: res.data.id
							}).then(ret => {
								this.isCheckPay(ret.code, 'wxpay', JSON.stringify(ret.data));
							});
							// #endif

							// #ifdef MP-WEIXIN
							// 微信小程序支付
							this.$Request.post('/app/wxPay/wxPayJsApiOrder', {
								orderId: res.data.id
							}).then(ret => {
								uni.hideLoading()
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: ret.data.timestamp,
									nonceStr: ret.data.noncestr,
									package: ret.data.package,
									signType: ret.data.signType,
									paySign: ret.data.sign,
									success: function(suc) {
										console.log('success:' + JSON.stringify(suc));
										uni.showToast({
											title: '支付成功',
											icon: 'success'
										})
										setTimeout(d => {
											uni.navigateBack(1)
										}, 1000);
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										uni.showToast({
											title: '支付失败',
											icon: 'none'
										})
									}
								});
							});
							// #endif

							// #ifdef H5
							let ua = navigator.userAgent.toLowerCase();
							if (ua.indexOf('micromessenger') !== -1) {
								this.$Request.post('/app/wxPay/wxPayMpOrder?orderId=' + res.data.id).then(res => {
									if (res.code == 0) {
										this.callPay(res.data);
									} else {
										uni.showToast({
											icon: 'none',
											title: '支付失败!'
										});
									}
								});
							} else {
								this.$Request.post('/app/aliPay/payOrder?orderId=' + res.data.id).then(
									res => {
										if (res.code === 0) {
											const div = document.createElement('div')
											div.innerHTML = res.data //此处form就是后台返回接收到的数据
											document.body.appendChild(div)
											document.forms[0].submit()
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											})
											setTimeout(d => {
												uni.navigateBack(1)
											}, 1000);
										} else {
											uni.showToast({
												icon: 'none',
												title: '支付失败!'
											});
										}
									});
							}
							// #endif

						} else {
							// APP支付宝支付
							this.$Request.post("/app/aliPay/payApp", {
								id: res.data.id
							}).then(ret => {
								console.log(ret)
								this.isCheckPay(ret.code, 'alipay', ret.data);
							});
						}
					}
				});
			},
			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;
				}
				console.log(response, '++++++++')
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						console.log(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(status, name, order) {
				if (status == 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误',
						icon: 'none'
					});
				}
			},
			setPayment(name, order) {
				console.log('*-*-*')
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						console.log(res)
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
						setTimeout(d => {
							uni.navigateBack(1)
						}, 1000);
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			// 提现
			cashMoney() {
				
				if (!this.moneyNum) {
					uni.showToast({
						icon: 'none',
						title: '请输入提现金额'
					})
					return
				}
				if (this.moneyNum < this.minMoney * 1) {
					uni.showToast({
						icon: 'none',
						title: '最低可提现'+this.minMoney+'元'
					})
					return
				}
				if (this.moneyNum > this.money * 1) {
					uni.showToast({
						icon: 'none',
						title: '您的余额不足'
					})
					return
				}
				// if (this.moneyNum*1+this.charge*this.moneyNum > this.money*1) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '您的手续费不足'
				// 	})
				// 	return
				// }

				let zhiFuBao = uni.getStorageSync('zhiFuBao')
				let zhiFuBaoName = uni.getStorageSync('zhiFuBaoName')

				if (!zhiFuBao && !zhiFuBaoName && this.openWay == 1) {
					uni.navigateTo({
						url: '/my/wallet/zhifubao'
					})
					return
				}

				if (!this.bankCard && this.openWay == 2) {
					uni.navigateTo({
						url: '/my/wallet/yinhangka'
					})
					return
				}

				let that = this
				that.sp = (that.moneyNum * this.charge).toFixed(2)
				uni.showModal({
					title: '提示',
					content: '本次提现' + that.moneyNum + '元，服务费' + this.sp + '元，是否确认提现？',
					success: function(res1) {
						if (res1.confirm) {
							uni.showLoading({
								title:'提现中'
							})
							that.$Request.get("/app/cash/cashMoney", {
								money: that.moneyNum,
								userType: 2,
								classify: that.openWay
							}).then(res => {
								if (res.code == 0) {
									that.openWay==3&&that.$Request.get("/app/wxTransfer/wxMerchantTransferToUser", {
										orderNumber:res.orderNumber
									}).then(r=>{
										that.$Request.get("/app/wxTransfer/wxConfig", {
											url:'https://master.dstapp.cn/sqx_fast/app/wxTransfer/wxConfig'||window.location.href
										}).then(data=>{
											uni.hideLoading()
											if(data.code == 0){
												let {timestamp,appId,nonceStr,signature} = data
												jwx.config({
												  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
												  appId, // 必填，服务号的唯一标识
												  timestamp, // 必填，生成签名的时间戳
												  nonceStr, // 必填，生成签名的随机串
												  signature,// 必填，签名
												  jsApiList: ['chooseWXPay','checkJsApi'] // 必填，需要使用的JS接口列表
												});
											}
										})
									
										
										jwx.ready(function () {
										  jwx.checkJsApi({
										    jsApiList: ['requestMerchantTransfer'],
										    success: function (res) {
												console.log('checkJsApi',res);
										      if (res.checkResult['requestMerchantTransfer']) {
										        WeixinJSBridge.invoke('requestMerchantTransfer', {
										            mchId: '1723757626',
										            appId: 'wxbcba29ef4f698074',
										            package: r.data.package_info,
										          },
										          function (res) {
										            if (res.err_msg === 'requestMerchantTransfer:ok') {
										              // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
													  uni.showToast({
													  	icon: 'none',
													  	title: '提现申请成功，请耐心等待！'
													  })
													  that.moneyNum = null
										            }
										          }
										        );
										      } else {
										        alert('你的微信版本过低，请更新至最新版本。');
										      }
										    }
										  });
										});
										
									})
									// uni.showToast({
									// 	icon: 'none',
									// 	title: '提现申请成功，请耐心等待！'
									// })
									// that.moneyNum = null
								} else {
									uni.hideLoading()
									uni.showToast({
										icon: 'none',
										title: res.msg
									})
								}
								that.getMoney()
							});
						} else if (res1.cancel) {
							console.log('用户点击取消');
						}
					}
				});


			}
		}
	}
</script>

<style lang="scss">
	.wallet {
		background: #F5F6F6;
		padding: 20rpx 32rpx;
		min-height: 100vh;
		.icon-box{
			display: flex;
			justify-content: space-between;
			padding: 28rpx;
			background: #FFFFFF;
			border-radius: 32rpx 32rpx 32rpx 32rpx;
			margin-top: 20rpx;
			.icon-item{
				width: 20%;
				text-align: center;
				.icon{
					width: 40rpx;
					height: 40rpx;
				}
				.label{
					font-size: 24rpx;
					color: #222222;
					margin-top: 20rpx;
				}
			}
		}
		
	}
	.bg.bg1{
		background: linear-gradient( 90deg, #FFC8D6 0%, #BAFFF3 63%, #FFE6ED 100%);
	}

	.bg {
		background-color: #FFFFFF;
		padding: 28rpx;
		border-radius: 32rpx;
		margin-bottom: 20rpx;
	}

	.active {
		border: 1px solid #2FB57A !important;
		color: #2FB57A !important;
	}

	.title_btn {
		height: 78upx;
		line-height: 78upx;
		/* background: #f7f7f7; */
	}

	.btn {
		width: 686rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		background: #1EDA94;
		border-radius: 86rpx 86rpx 86rpx 86rpx;
		font-weight: bold;
		font-size: 32rpx;
		color: #FFFFFF;
	}

	.bgCol2 {
		color: #2FB57A;
	}
</style>
