<template>
	<view class="container">
		<view style="flex: 1;">
			<!-- #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 class="wapper" >
				<view class="itemBox">
					<view class="title">
						实名信息
					</view>
					<view class="subTit">
						<text class="iconfont icon-circleDuiHao"></text>
						<text>您提供的身份信息只用于实名制签约和税务申报</text>
					</view>
					<view class="tips">
						姓名和证件号码必须和证件信息相同
					</view>
					<view class="formBox">
						<view class="formItem">
							<view class="left">
								<text class="require">*</text>
								<text>姓名</text>
							</view>
							<input
								class="user-input"  
								maxlength="10" 
								type="text"
								placeholder="请输入"
								v-model="realInfo.shiming.realName"
								@blur="getInfo('1')"
							/>
						</view>
						<view class="formItem" @click="openSelsect('1')">
							<view class="left">
								<text class="require">*</text>
								<text>证件类型</text>
							</view>
							<commonSelect
								:dataList="idTypesList"
								:visible="showIdType"
								:showValue="idTypeIdx"
								@confirm="changeIdTypeSelect"
								@close="showIdType=false"
								v-if="idTypesList.length>1"
							/>
						</view>
						<view class="formItem">
							<view class="left">
								<text class="require">*</text>
								<text>证件号码</text>
							</view>
							<input
								class="user-input"  
								maxlength="18" 
								type="number"
								placeholder="请输入"
								v-model="realInfo.shiming.idNumber"
								@blur="getInfo('2')"
							/>
						</view>
					</view>
				</view>
				<view class="itemBox">
					<view class="title">
						<text v-if="paymentMethod=='2'">绑定支付宝账号</text>
						<text v-if="paymentMethod=='1'">绑定微信账号</text>
					</view>
					<view class="subTit">
						<text class="iconfont icon-circleDuiHao"></text>
						<text>信息仅用于转账使用</text>
					</view>
					
					<view class="formBox">
						<view class="formItem" v-if="paymentMethod=='1'">
							<view class="left">
								<text class="require">*</text>
								<text>真实姓名</text>
							</view>
							<input
								class="user-input"  
								maxlength="10" 
								type="text"
								placeholder="请输入"
								v-model="realInfo.wx.wxPayName"
							/>
							<!-- <text class="error-tip" v-if="errors.wxPayName">{{errors.wxPayName}}</text> -->
						</view>
						<view class="" v-if="paymentMethod=='2'">
							<view class="formItem">
								<view class="left">
									<text class="require">*</text>
									<text>支付宝姓名</text>
								</view>
								<input
									class="user-input"  
									maxlength="10" 
									type="text"
									placeholder="请输入"
									v-model="realInfo.zhifubao.aliPayName"
								/>
							</view>
							<view class="formItem">
								<view class="left">
									<text class="require">*</text>
									<text>支付宝账号</text>
								</view>
								<input
									class="user-input"  
									maxlength="20"
									placeholder="请输入"
									v-model="realInfo.zhifubao.aliPayAccount"
								/>
							</view>
							<view class="formItem" @click="openSelsect('2')">
								<view class="left">
									<text class="require">*</text>
									<text>证件类型</text>
								</view>
								<commonSelect
									:dataList="idTypesList"
									:visible="showZhifubaoIdType"
									:showValue="idZhifubaoTypeIdx"
									@confirm="changeZhifubaoIdTypeSelect"
									@close="showZhifubaoIdType=false"
									v-if="idTypesList.length>1"
								/>
							</view>
							<view class="formItem">
								<view class="left">
									<text class="require">*</text>
									<text>证件号码</text>
								</view>
								<input
									class="user-input"  
									maxlength="18" 
									type="number"
									placeholder="请输入"
									v-model="realInfo.zhifubao.aliPayIdNumber"
								/>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="btnBox">
			<view 
				class="one" 
				@click="$refs.unbindTipPopup.open()"
				v-if="showUnbind"
			>
				解绑实名信息
			</view>
			<view class="two" @click="confirmSubmit()">
				确认提交
			</view>
		</view>
		<!-- 解绑实名提示 -->
		  <partner-tip-popup 
		    ref="unbindTipPopup"
			content="解绑后将无法提现,确认解绑？"
			title="解绑提示"
			joinText="确认解绑"
			continueText="暂不解绑"
			btnType="horizontal"
			:tipIcon="false"
		    @join="continueBind()"
		    @continue="$refs.unbindTipPopup.close()"
		  />
	</view>
	
</template>

<script>
	import api from '../../api/api';
	import commonSelect from '@/components/commonSelect/commonSelect.vue';
	import PartnerTipPopup from "@/components/commonPopup/PartnerTipPopup.vue";
	import common from '@/common/common.ts';
	import dataHandling from "@/util/dataHandling";
	export default{
		components: {
			commonSelect,
			PartnerTipPopup
		},
		data(){
			return {
				paymentMethod:'',//提现方式  1.微信  2.支付宝
				showIdType:false,//证件类型下拉框
				idTypeIdx: null,//证件默认值
				showZhifubaoIdType:false,//支付宝证件类型下拉框
				idZhifubaoTypeIdx:null,//证件默认值
				idTypesList: [{id:null,name:'请选择'}],
				// 错误信息
				errors: {
					realName: '',
					idType: '',
					idNumber: '',
					wxPayName: '',
					aliPayName: '',
					aliPayAccount: '',
					aliPayIdType: '',
					aliPayIdNumber: ''
				},
				//实名信息
				realInfo:{
					shiming:{},//实名信息
					wx:{},// 微信信息
					zhifubao:{}//支付宝信息
				},
				showUnbind:false
			}
		},
		onLoad(options){
			if(options.paymentMethod){
				this.paymentMethod = options.paymentMethod
			}
			
		},
		onShow(){
			this.getIdType()
			
		},
		methods:{
			continueBind(){
				let params = {
					userId:uni.getStorageSync('cffp_userId'),
					oprType:this.paymentMethod
				}
				api.unbindImproveInfo(params).then((res)=>{
					if(res['success']){
						dataHandling.pocessTracking(
						  '解绑实名',
						  `成功解绑提现实名`,
						  '点击',
						  2,
						  '积分提现实名',
						  'myPackageA/integralExchange/authenticaInfo'
						)
						uni.navigateTo({
							url:`/myPackageA/integralExchange/exchange?paymentMethod=${this.paymentMethod}`
						})
					}else{
						uni.showToast({
							title: res['message'],
							duration: 2000,
							icon: 'none'
						})
					}
					
				})
			},
			
			getInfo(type){
				switch (type){
					case '1':
							if(this.paymentMethod =='2'){
								this.realInfo.zhifubao.aliPayName = this.realInfo.shiming.realName
							}else if(this.paymentMethod =='1'){
								this.realInfo.wx. wxPayName= this.realInfo.shiming.realName
							}
						
						break;
					case '2':
						this.realInfo.zhifubao.aliPayIdNumber = this.realInfo.shiming.idNumber
						break;
					default:
						break;
				}
			},
			// 修改后的确认提交方法
			confirmSubmit(){
			  const validateResult = this.validateForm();
			  if(!validateResult.isValid) {
				let message = '请完善以下信息：\n';
				validateResult.emptyFields.forEach((field, index) => {
				  message += `${index + 1}. ${field}\n`;
				});
				
				uni.showModal({
				  title: '提示',
				  content: message,
				  showCancel: false,
				  confirmText: '我知道了'
				});
				return;
			  }
			  if (!common.nameValid(this.realInfo.shiming.realName)) {
			  	uni.showToast({title: '请填写真实姓名',duration: 2000,icon: 'none'});
			  	this.realInfo.shiming.realName = ''
			  	return
			  }
			  if(this.realInfo.shiming.idType == 'IDENTITY_CARD'&&this.realInfo.shiming.idNumber.length<18 ){
			  	uni.showToast({title: '请输入18位实名身份证号',duration: 2000,icon: 'none'});
			  	return
			  }
			  if(this.realInfo.shiming.idType == 'IDENTITY_CARD'  ){
			  	let obj = common.IdCodeValid(this.realInfo.shiming.idNumber)
			  	if(!obj.pass){
			  		uni.showToast({title: '请输入有效的实名身份证号',duration: 2000,icon: 'none'});
			  		return
			  	}
			  }
			  
			  
			  if(this.paymentMethod == '1'){
				  if (!common.nameValid(this.realInfo.wx.wxPayName)) {
				  	uni.showToast({title: '请填写微信真实姓名',duration: 2000,icon: 'none'});
				  	this.realInfo.wx.wxPayName = ''
				  	return
				  }
			  }
			  
			  
			  if(this.paymentMethod == '2'){
				  if (!common.nameValid(this.realInfo.zhifubao.aliPayName)) {
				  	uni.showToast({title: '请填写真实支付宝姓名',duration: 2000,icon: 'none'});
				  	this.realInfo.zhifubao.aliPayName = ''
				  	return
				  }
				  
				   if (!common.alipayAccountValid(this.realInfo.zhifubao.aliPayAccount)) {
					   uni.showToast({title: '请输入有效的手机号或邮箱',duration: 2000,icon: 'none'});
				       
				        return ;
				      }
				  if(this.realInfo.zhifubao.aliPayIdType == 'IDENTITY_CARD'&&this.realInfo.zhifubao.aliPayIdNumber.length<18 ){
				  	uni.showToast({title: '请输入18位支付宝身份证号',duration: 2000,icon: 'none'});
				  	return
				  }
				  if(this.realInfo.zhifubao.aliPayIdType == 'IDENTITY_CARD'&&this.realInfo.zhifubao.aliPayIdNumber.length<18 ){
				  	let obj = common.IdCodeValid(this.realInfo.zhifubao.aliPayIdNumber)
				  	if(!obj.pass){
				  		uni.showToast({title:'请输入有效的支付宝证件号码',duration: 2000,icon: 'none'});
				  		return
				  	}
				  }
			  }
			  let params = {
			  		realNameAuthRequest : {...this.realInfo.shiming},
					userId:	uni.getStorageSync('cffp_userId'),
					oprType:this.paymentMethod	  
			  }
			  if(this.paymentMethod == '1'){
				  params.bindAgCffpWxPayAccountRequest = {...this.realInfo.wx}
			  }else if(this.paymentMethod == '2'){
				   params.bindAgCffpAliPayAccountRequest = {...this.realInfo.zhifubao}
			  }
			  // 校验通过，继续提交逻辑
			  // console.log('params',params);
			  // return
			  api.submitImproveInfo(params).then((res)=>{
			  	if(res['success']){
					dataHandling.pocessTracking(
					  '实名认证成功',
					  `提现已完成实名认证`,
					  '点击',
					  2,
					  '积分提现实名',
					  'myPackageA/integralExchange/authenticaInfo'
					)
			  		uni.navigateTo({
			  			url:`/myPackageA/integralExchange/exchange?paymentMethod=${this.paymentMethod}`
			  		})
			  	}else{
			  		uni.showToast({
			  			title: res['message'],
			  			duration: 2000,
			  			icon: 'none'
			  		})
			  	}
			  })
			},
						
			// 修改后的表单校验方法
			validateForm() {
				const emptyFields = [];
				
				// 实名信息校验
				if(!this.realInfo.shiming.realName || this.realInfo.shiming.realName.trim() === '') {
					emptyFields.push('姓名');
				}
				
				if(!this.realInfo.shiming.idType) {
					emptyFields.push('证件类型');
				}
				
				if(!this.realInfo.shiming.idNumber || this.realInfo.shiming.idNumber.trim() === '') {
					emptyFields.push('证件号码');
				}
				
				// 根据支付方式校验不同字段
				if(this.paymentMethod === '1') {
					// 微信支付校验
					if(!this.realInfo.wx.wxPayName || this.realInfo.wx.wxPayName.trim() === '') {
						emptyFields.push('微信真实姓名');
					}
				} else if(this.paymentMethod === '2') {
					// 支付宝支付校验
					if(!this.realInfo.zhifubao.aliPayName || this.realInfo.zhifubao.aliPayName.trim() === '') {
						emptyFields.push('支付宝姓名');
					}
					
					if(!this.realInfo.zhifubao.aliPayAccount || this.realInfo.zhifubao.aliPayAccount.trim() === '') {
						emptyFields.push('支付宝账号');
					}
					
					if(!this.realInfo.zhifubao.aliPayIdType) {
						emptyFields.push('支付宝证件类型');
					}
					
					if(!this.realInfo.zhifubao.aliPayIdNumber || this.realInfo.zhifubao.aliPayIdNumber.trim() === '') {
						emptyFields.push('支付宝证件号码');
					}
				}
				
				return {
					isValid: emptyFields.length === 0,
					emptyFields
				};
			},
			
			// 查询实名信息
			getImproveInfo(){
				this.showUnbind = false
				let params = {
					userId:uni.getStorageSync('cffp_userId'),
					oprType:this.paymentMethod
				}
				api.improveInfo(params).then((res)=>{
					if(res['success']){
						let result = res['data']
						for (let key in result) {
							if(key!='userId'&&!result[key]){
								result[key] = {}
							}
						}
						if(JSON.stringify( result.realNameAuthResponse)!='{}'){
							this.realInfo.shiming = result.realNameAuthResponse
						}
						
						if(this.paymentMethod=='1' &&JSON.stringify( result.bindAgCffpWxPayAccountResponse)!='{}'){
							this.realInfo.wx = result.bindAgCffpWxPayAccountResponse
						}else if(this.paymentMethod=='2'&&JSON.stringify( result.bindAgCffpAliPayAccountResponse)!='{}'){
							this.realInfo.zhifubao = result.bindAgCffpAliPayAccountResponse
						}
						if(JSON.stringify(this.realInfo.shiming)!='{}'&&((this.paymentMethod == '1'&&JSON.stringify(this.realInfo.wx)!='{}') || (this.paymentMethod == '2'&&JSON.stringify(this.realInfo.zhifubao)!='{}'))){
							this.showUnbind = true
						}else {
							this.showUnbind = false
						}
						this.$nextTick(()=>{
							if(JSON.stringify(this.realInfo.shiming) != '{}'){
								console.log(' this.idTypesList', this.idTypesList);
								let index = this.idTypesList.findIndex(item=>item.id==this.realInfo.shiming.idType)
								
								if(index !== -1){
									this.idTypeIdx = index
									
								}
							}
							if(JSON.stringify(this.realInfo.zhifubao) != '{}'){
								let index = this.idTypesList.findIndex(item=>item.id==this.realInfo.zhifubao.aliPayIdType)
								if(index !== -1){
									this.idZhifubaoTypeIdx = index
								}
							}
						})
						
						// console.log('this.realInfo',this.realInfo);
						
					}else{
						uni.showToast({
							title: res['message'],
							duration: 2000,
							icon: 'none'
						})
					}
					
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1  
				});
			},
			openSelsect(type){
				if(type == '1'){
					this.showIdType = true
					return
				}
				if(type == '2'){
					this.showZhifubaoIdType = true
				}
			},
			// 改变实名证件类型
			changeIdTypeSelect(value){
				this.idTypeIdx=this.idZhifubaoTypeIdx = value;
				this.realInfo['shiming'].idType=this.realInfo['zhifubao'].aliPayIdType = this.idTypesList[value].id
				this.showIdType = false
			},
			changeZhifubaoIdTypeSelect(value){
				this.idZhifubaoTypeIdx  = value;
				this.realInfo['zhifubao'].aliPayIdType = this.idTypesList[value].id
				this.showZhifubaoIdType = false
			},
			getIdType(){
				api.dropOptionsQuery({code:'SYS_ID_TYPE'}).then((res)=>{
					if(res['success']&&res['data']['dropMasterInfoList'][0]['dropOptionsInfoList'].length>0){
						const result = res['data']['dropMasterInfoList'][0]['dropOptionsInfoList']
						result.forEach(item=>{
							this.idTypesList.push({name:item.dropOptionName,id:item.dropOptionCode})
						})
						this.getImproveInfo()
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		color: #333333;
		display: flex;
		flex-direction: column;
		.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;
			}
		}
		.wapper{
			padding: 20rpx;
			box-sizing: border-box;
			.itemBox{
				background-color: #fff;
				padding: 15rpx 30rpx;
				border-radius: 10rpx;
				margin-bottom: 20rpx;
				font-size: 28rpx;
				.title{
					font-size: 32rpx;
					font-weight: 500;
					
				}
				.subTit{
					color: #666666;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					padding-bottom: 10rpx;
					border-bottom: 1rpx solid #EFEFEF;
					margin-top: 10rpx;
					
					.icon-circleDuiHao{
						font-size: 26rpx;
						color: #666666;
						margin-right: 5rpx;
					}
				}
				.tips{
					color: #F43530;
					margin: 15rpx 0;
				}
				.formBox{
					.formItem{
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-bottom: 1rpx solid #E8E8E8;
						height: 100rpx;
						position: relative;
						.left{
							font-size: 26rpx;
						}
						.require{
							color: #F43530;
						}
						.user-input{
							color: black;
							font-size: 26rpx;
							text-align: right;
							
						}
						.error-tip{
							position: absolute;
							right: 0;
							bottom: -30rpx;
							color: #F43530;
							font-size: 22rpx;
						}
					}
				}
			}
		}
		.btnBox{
			width: 100%;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			flex-direction: column;
			margin-top: auto;
			margin-bottom: 20rpx;
			.one{
				width: 50%;
				text-align: center;
				border: 1rpx solid #20269B;
				color: #20269B;
				padding: 20rpx 0;
				border-radius: 40rpx;
				margin-bottom: 20rpx;
			}
			.two{
				width: 50%;
				text-align: center;
				background-color:#20269B ;
				color: #fff;
				padding: 20rpx 0;
				border-radius: 40rpx;
			}
		}
	}
</style>