<template>
	<view class="container">
		<!-- #ifdef APP -->
		<view class="backArrow">
			<text class="iconfont icon-youjiantou zuojiantou" style="left: 5rpx;" @click="goBack()"></text>
			<text style="font-size: 30rpx;">积分提现</text>
		</view>
		<!-- #endif -->
		
		<view style="padding: 20rpx;">
			<view class="top">
				<view class="one">
					<view style="font-size: 28rpx;font-weight: 500;">
						提现金额：
					</view>
					<view class="middle">
						{{queryResult.yesExchangeFortune || '0.00'}}
					</view>
					<view class="">
						当前待结算积分：{{queryResult.notExchangeFortune || '0.00'}}
					</view>
				</view>
				<view class="two">
					<view class="">
						提现说明
					</view>
					<view class="">
						1、金额低于1元时无法提现;
					</view>
					<view style="margin: 10rpx 0;">
						<view class="">
							2、当前可提金额是您的税前收入，具体计税规则可参考 
						</view>
						<view style="color: #20269B;">
							<text class="rule" @click="gotoRule()">《劳务报酬税缴纳规则》</text>
							<!-- <navigator  url="/myPackageA/ruleAndContract/taxRules">《劳务报酬税缴纳规则》;</navigator> -->
						</view>
					</view>
					
					<view class="" @click="consult()">
						3、如需帮助，请 <text style="color: #20269B;">点击此处</text> 联系客服
					</view>
				</view>
			</view>
		</view>
		
		<view style="padding: 0 20rpx;">
			<view class="content_wrapper tixian">
				<h4>提现方式</h4>
				<view class="paymentBox" >
					<view 
						class="paymentItem" 
						:class="{active:paymentMethod === '2' }" 
						@click="selectPaymentMethod('2')"
					>
						<view>
							<i class="iconfont icon-zhifubao2"></i>
							<text style="font-size: 28rpx;">支付宝</text>
						</view>
						<view class="selectRadio" :class="{'actived':paymentMethod==='2'}">
							<i class="iconfont icon-duihao" style="font-size: 28rpx;"></i>
						</view>
						
					</view>
					<!-- 微信提现暂未开发 暂时隐藏微信提现入口-->
					<!-- <view 
						class="paymentItem" 
						@click="selectPaymentMethod('1')"
						:class="{active:paymentMethod === '1' }" 
					>
						<view>
							<i class="iconfont icon-weixin"></i>
							<text>微信</text>
						</view>
						<view class="selectRadio" :class="{'actived':paymentMethod==='1'}">
							<i class="iconfont icon-duihao"></i>
						</view>
					</view> -->
				</view>
				
				<view 
					class="warn" 
					@click="realName()"
					v-if="showUnbind"
				>
					<view class="">
						<text class="iconfont icon-point oneIcon"></text>
						<text style="color: #999;">账户信息待完善，认证通过后即可提现</text>
					</view>
					<view style="color: #20269B;">
						<text>去完善</text>
						<text class="iconfont icon-jiantou2"></text>
					</view>
					
				</view>
				<view
					v-else
					@click="realName()"
					style="color: #20269B;font-size: 28rpx;text-align: right;margin-top: 10rpx;"
				>
					<text>去查看认证信息</text>
					<text class="iconfont icon-jiantou2"></text>
				</view>
				<view style="display: flex;align-items: center;justify-content: center;">
					<view class="bottomBtn" @click="confirmWithdrawal()" :class="{'gray':readonlyFlag}" >
						确认提现
					</view>
				</view>
			
				
			</view>
		</view>
		
	</view>
</template>

<script>
	import api from '../../api/api';
	import dataHandling from "@/util/dataHandling";
	export default{
		
		data(){
			return {
				exchangeAmount:null,
				partnerTradeNo:null,
				taxAmount:null,
				noTaxAmount:null,
				paymentMethod:'2',//2初始化支付宝提现  1微信提现
				aliWithdrawalResVO:null,
				wxWithdrawalResVO:null,
				readonlyFlag:false,
				queryResult:{},
				realInfo:{
					bindAgCffpAliPayAccountResponse:null
				},//实名信息
				showUnbind:false,
			}
		},
		onLoad(options){
			if(options.paymentMethod){
				this.paymentMethod = options.paymentMethod
			}
			
		},
		onShow(){
			this.queryByUserIdFortuneStatistic()
			this.getImproveInfo()
			
		},
		methods:{
			
			gotoRule(){
				dataHandling.pocessTracking(
				  '查看',
				  `查看劳务报酬税缴纳规则`,
				  '点击',
				  2,
				  '积分提现',
				  'myPackageA/integralExchange/authenticaInfo'
				)
				uni.navigateTo({
					url:'/myPackageA/ruleAndContract/taxRules'
				})
			},
			// 查询实名信息
			getImproveInfo(){
				
				let params = {
					userId:uni.getStorageSync('cffp_userId'),
					oprType:this.paymentMethod
				}
				api.improveInfo(params).then((res)=>{
					if(res['success']){
						this.realInfo.realNameAuthResponse = res['data']['realNameAuthResponse']
						if(this.paymentMethod=='2'&&res['data']['bindAgCffpAliPayAccountResponse']){
							this.realInfo.bindAgCffpAliPayAccountResponse = res['data']['bindAgCffpAliPayAccountResponse']
						}else if(this.paymentMethod=='1'&&res['data']['bindAgCffpWxPayAccountResponse']){
							this.realInfo.bindAgCffpWxPayAccountResponse = res['data']['bindAgCffpWxPayAccountResponse']
						}
						if(!this.realInfo.realNameAuthResponse||((this.paymentMethod == '1'&&!this.realInfo.bindAgCffpWxPayAccountResponse) || (this.paymentMethod == '2'&&!this.realInfo.bindAgCffpAliPayAccountResponse))){
							this.showUnbind = true
						}else {
							this.showUnbind = false
						}
					}else{
						uni.showToast({
							title: res['message'],
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			// 查询兑换得钱数和待结算得积分
			queryByUserIdFortuneStatistic(){
				api.queryByUserIdFortuneStatistic({userId:uni.getStorageSync('cffp_userId')}).then((res)=>{
					if(res['success']){
						this.queryResult = res['data']
						if(this.queryResult.yesExchangeFortune){
							this.queryResult.yesExchangeFortune = Number(this.queryResult.yesExchangeFortune).toFixed(2)
						}
						if(this.queryResult.notExchangeFortune){
							this.queryResult.notExchangeFortune = Number(this.queryResult.notExchangeFortune).toFixed(2)
						}
						this.goFortuneWithdrawal()
					}
				})
			},
			realName(){
				dataHandling.pocessTracking(
				  `${this.showUnbind?'认证':'查看'}`,
				   `${this.showUnbind?'认证实名信息':'查看实名信息'}`,
				  '点击',
				  2,
				  '积分提现',
				  'myPackageA/integralExchange/exchange'
				)
				uni.navigateTo({
					url:`/myPackageA/integralExchange/authenticaInfo?paymentMethod=${this.paymentMethod}`
				})
			},
			//联系客服
			consult(){
				dataHandling.pocessTracking(
				  '联系客服',
				  `用户点击联系客服`,
				  '点击',
				  2,
				  '积分提现',
				  'myPackageA/integralExchange/exchange'
				)
				// 现在还没转化成小程序，暂时放在这
					// #ifdef MP-WEIXIN
					uni.openCustomerServiceChat({
					  extInfo: {
						url: 'https://work.weixin.qq.com/kfid/kfc08c55f4170e7fc9e'
					  },
					  corpId: 'ww43cac1cf9dd6a3d0', // 客服会话按钮打开后，在微信客服会话按钮处理的事件类型
					  showMessageCard: true,
					  sendMessageTitle: (uni.getStorageSync('hoservice_mobileNo')?(uni.getStorageSync('hoservice_mobileNo')+"，") :"" ) + "进入个人中心-->咨询客服",
					  sendMessagePath: `/pages/index/mySelf.html`,
					  //sendMessageImg: cardItem.value['list'][0]['itemImg']
					});
					// #endif
					// #ifndef MP-WEIXIN
					window.open('https://work.weixin.qq.com/kfid/kfc08c55f4170e7fc9e')
					// #endif
			},
			goBack() {
				uni.navigateBack({
					delta: 1  
				});
			},
			goFortuneWithdrawal(){
				const param = {
					userId:uni.getStorageSync('cffp_userId'),
					exchangeAmount:this.queryResult.yesExchangeFortune,
					partnerTradeNo:this.partnerTradeNo?this.partnerTradeNo:null
				}
				api.goFortuneWithdrawal(param).then((res)=>{
					if(res['success']){
						const data = res['data']
						this.exchangeAmount = data.exchangeAmount;
						this.partnerTradeNo = data.partnerTradeNo;
						this.taxAmount = data.taxAmount;
						this.noTaxAmount = data.noTaxAmount;
						this.aliWithdrawalResVO = data['aliWithdrawalResVO'];
						this.wxWithdrawalResVO = data['wxWithdrawalResVO'];
					}else{
						this.exchangeAmount = 0;
						this.partnerTradeNo = null;
						this.taxAmount = 0;
						this.noTaxAmount = 0;
						uni.showModal({
						    content: res['message'],
							success: function (res) {
						   		if (res.confirm) {
						   			console.log('用户点击确定');
						   		} else if (res.cancel) {
									console.log('用户点击取消');
						   		}
							}
						});
					}
				})
			},
			selectPaymentMethod(value){
				this.paymentMethod = value;
				this.getImproveInfo()
				
			},
			//支付宝去提现
			aliWithdrawal(){
				this.readonlyFlag = true;
				//#ifdef H5
				let aliWithdrawalResVOParam = {
					...this.aliWithdrawalResVO,
					dataSource:2,
					orderNo:this.partnerTradeNo,
					amount:this.exchangeAmount,
					userId:uni.getStorageSync('cffp_userId'),
				}
				//#endif
				// #ifdef APP-PLUS
				let aliWithdrawalResVOParam = {
					...this.aliWithdrawalResVO,
					dataSource:2,
					orderNo:this.partnerTradeNo,
					amount:this.exchangeAmount,
					userId:uni.getStorageSync('cffp_userId'),
				}
				//#endif
				api.aliWithdrawal(aliWithdrawalResVOParam).then((res)=>{
					this.readonlyFlag = false;
					if(res['success']){
						uni.showModal({
						    content: '提现成功！',
							showCancel: false, // 不显示取消按钮
							success: function (res) {
						   		if (res.confirm) {
						   			uni.switchTab({
						   				url:'pages/personalCenter/personalCenter'
						   			})
						   		} else if (res.cancel) {
									console.log('用户点击取消');
						   		}
							}
						});
					}else{
						dataHandling.pocessTracking(
						  '提现提交审核',
						  `提现提交审核`,
						  '点击',
						  2,
						  '积分提现',
						  'myPackageA/integralExchange/exchange'
						)
						uni.showModal({
						    content: res['message'],
							showCancel: false, // 不显示取消按钮
							success: function (res) {
						   		if (res.confirm) {
						   			uni.switchTab({
						   				url:'/pages/personalCenter/personalCenter'
						   			})
						   		} else if (res.cancel) {
									console.log('用户点击取消');
						   		}
							}
						});
					}
					
				})
			},
			//微信去提现
			wxWithdrawal(){
				// APP：
				// #ifdef APP-PLUS
				uni.login({
				    provider: 'weixin',
				    success: function (loginRes) {
				        // 登录成功
						// alert(JSON.stringify(loginRes))
				        uni.getUserInfo({
				            provider: 'weixin',
				            success: function(info) {
				                // 获取用户信息成功, info.authResult保存用户信息
								console.log(info)
								this.wxWithdrawalResVO.openId=info.openId;
								const wxWithdrawalResVO = {
									...this.wxWithdrawalResVO,
									userId:uni.getStorageSync('cffp_userId'),
								}
								api.wxWithdrawal(wxWithdrawalResVO).then((res)=>{
									console.log(res)
								})
				            }
				        })
				    },
				    fail: function (err) {
				        // 登录授权失败  
				        // err.code是错误码
				    }
				})
				// #endif
			},
			confirmWithdrawal(){
				if(!!this.showUnbind){
					uni.showModal({
						    content: '账户信息待完善，认证通过后即可提现',
							showCancel: false,
							confirmText: '我知道了'
						});
						return
				}
				// return
				// 原先的提现逻辑
				if(!this.queryResult.yesExchangeFortune || this.queryResult.yesExchangeFortune<1){
					uni.showModal({
					  title: '提示',
					  content: '金额低于1元时无法提现',
					  showCancel: false,
					  confirmText: '我知道了'
					});
					return false;
				}
				//#ifdef H5
				this.aliWithdrawal();
				//#endif
				// #ifdef APP-PLUS
				if(!this.readonlyFlag){
					this.readonlyFlag = true;
					this.aliWithdrawalResVO = {
						...this.aliWithdrawalResVO,
						orderNo:this.partnerTradeNo,
						amount:this.exchangeAmount,
						userId:uni.getStorageSync('cffp_userId'),
					}
					api.isAuth(this.aliWithdrawalResVO).then((res)=>{
								this.readonlyFlag = false;
								if(res['success']){
									this.aliWithdrawalResVO.aliUserId = res['data']['aliUserId'];
									if(res['data']['isAuth'] == 1){
										if(this.paymentMethod == 1){
											this.wxWithdrawal();
										}
										if(this.paymentMethod == 2){
											this.aliWithdrawalResVO.aliAuthUrl=res['data']['aliAuthUrl'];
											// APP：
											// #ifdef APP-PLUS
											let urls= this.aliWithdrawalResVO.aliAuthUrl;
											urls=encodeURIComponent(urls);
											// 判断平台
											if (plus.os.name == 'Android') {
											  plus.runtime.openURL(
											    'alipays://platformapi/startapp?appId=20000067&url=' + urls,
											    res => {
												//这里写打开URL地址失败后的处理
											      console.log(res);
											      uni.showModal({
											        content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
											        success: function (res) {
											          if (res.confirm) {
											            //plus.runtime.openURL();
											          }
											        }
											      });
											    },
											    'com.eg.android.AlipayGphone'
											  );
											} else if (plus.os.name == 'iOS') {
											  plus.runtime.openURL(
											    'alipay://platformapi/startapp?appId=20000067&url=' + urls,
											    res => {
											      console.log(res);
											      uni.showModal({
											        content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
											        success: function (res) {
											          if (res.confirm) {
											            //plus.runtime.openURL(url);
											          }
											        }
											      });
											    },
											    'com.eg.android.AlipayGphone'
											  );
											}
											// #endif
										}
									}else{
										if(this.paymentMethod == 1){
											this.wxWithdrawal();
										}
										if(this.paymentMethod == 2){
											this.aliWithdrawal();
										}
										
									}
								}else{
									uni.showModal({
									    content: res['message'],
										success: function (res) {
									   			if (res.confirm) {
									   				console.log('用户点击确定');
									   			} else if (res.cancel) {
													console.log('用户点击取消');
									   			}
										}
									});
								}
							});
					}
				// #endif
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		box-sizing: border-box;
		color: #333333;
		.backArrow{
			background-color: #fff;
			box-sizing: border-box;
			display: flex;
			height: 100rpx;
			justify-content: space-between;
			align-items: center;
			position: relative;
			width: 100%;
			text:nth-child(2){
				width: 100%;
				text-align: center;
				position: absolute;
			}
		}
	}
	.top{
		width: 100%;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		font-size: 26rpx;
		box-sizing: border-box;
		
		.one{
			.middle{
				font-size: 40rpx;
				color: #0A2F99;
				margin: 10rpx 0;
				border-bottom: 1rpx solid #EFEFEF;
				padding-bottom: 10rpx;
			}
		}
		.two{
			margin-top: 20rpx;
			background-color: #FAFAFA;
			padding: 10rpx;
			border-radius: 10rpx;
			font-size: 26rpx;
			box-sizing: border-box;
			
		}
	}
	.content_wrapper{
		border-radius: 10rpx;
		background: #fff;
		
		padding:0 30rpx;
		.item{
			display: flex;
			padding: 20rpx 0;
			border-bottom: 2rpx solid #F2F2F2;
			justify-content: space-between;
			font-size: 28rpx;
		}
		h4{
			font-size: 32rpx;
			margin-bottom: 20rpx;
		}
		.paymentBox{
			display: flex;
			align-items: center;
			justify-content: space-between;
			.paymentItem{
				width: 46%;
				padding: 20rpx;
				border-radius: 10rpx;
				border: 1rpx solid #FAFAFA;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 10rpx;
				&.active{
					background-color: #FAFAFA;
				}
				view{
					display: flex;
					align-items: center;
				}
				.icon-zhifubao2{
					color: #5A9EF7;
					font-size: 60rpx;
					margin-right: 20rpx;
				}
				.icon-weixin{
					color: #09BB07;
					font-size: 60rpx;
					margin-right: 20rpx;
				}
				.selectRadio{
					width: 40rpx;
					height: 40rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50%;
					border: 1px solid #D8D8D8;
					color: transparent;
					&.actived{
						background-color: #0A2F99;
						color: #fff;
					}
				}
			}
		}
		.warn{
			margin-top: 10rpx;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			justify-content: space-between;
			.oneIcon{
				background-color: #F43530;
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				color: #fff;
				padding: 5rpx;
				font-size: 24rpx;
				margin-right: 5rpx;
			}
		}
		.bottomBtn{
			padding: 20rpx;
			margin-top: 50rpx;
			margin-bottom: 10rpx;
			width: 60%;
			background-color: #3639A9;
			text-align: center;
			font-size: 30rpx;
			color: #fff;
			font-weight: 500;
			border-radius: 50rpx;
		}
		.bottomBtn.gray{
			background: #666;
		}
		.withdrawal_content{
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			.icon-py_weixinzhifu{
				color:#09BB07;
				font-size: 80rpx;
				margin-right: 30rpx;
			}
			.icon-gou{
				font-size: 48rpx;
				color: #2A36AD;
			}
			
		}
		.tips_wrapper{
			font-size: 26rpx;
			view{
				color: #666666;
				margin-bottom: 10rpx;
			}
			.rule{
				color: #2A36AD
			}
		}
	}
	.tixian{
		padding: 20rpx;
	}
</style>