<template>
	<view class="container">
		
		
		<view class="userHeader">
			<!-- #ifdef APP -->
			<text class="iconfont icon-youjiantou zuojiantou" @click="goBack()" style="left: 20rpx;"></text>
			<!-- #endif -->
			<view class="headerBox">
				<view class="add">
					<text class="iconfont icon-jiahao" ></text>
				</view>
				<view class="avartBox" @click="uploadAvatar()">
					<image :src="optionForm.headPicture ? optionForm.headPicture  :companyLogo" mode="widthFix"></image>
				</view>
			</view>
			
		</view>
		<view class="userInformation">
			<view style="flex: 1;">
				<view class="wave">
					<image src="@/static/images/wave2.png" mode="widthFix"></image>
					<view class="nickNameBox">
						<view class="box">
							<view style="padding-bottom: 20rpx;">昵称</view>
							<input  
								v-model="optionForm.nickName" 
								maxlength="10" 
								type="text"
								placeholder="请输入2~10个字符" 
							/>
						</view>
						
				
					</view>
				</view>
				<view class="shimingBox">
					<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"
								/>
							</view>
							<view class="formItem" @click="this.showIdType = true">
								<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"
								/>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="bottomBox">
					<view class="cancelBtn" @click="$refs.unbindTipPopup.open()">
						取消
					</view>
					<view class="saveBtn" @tap="submitinfo">
						<text class="iconfont icon-save" ></text>
						<text>保存</text>
					</view>
			</view>
		</view>
		<!-- 解绑实名提示 -->
		  <partner-tip-popup 
			ref="unbindTipPopup"
			content="确定撤销所有修改吗？"
			joinText="暂不撤销"
			continueText="确认撤销"
			btnType="horizontal"
			:tipIcon="true"
			@join="continueCancel()"
			@continue="$refs.unbindTipPopup.close()"
		  />
		
	</view>
</template>

<script>
	import {
		CommonUpload
	} from '@/util/uploaderFile'
	import api from "@/api/api";
	import common from '../../common/common';
	import {companyInfo,shareURL} from "@/environments/environment";
	import dataHandling from "@/util/dataHandling";
	import { initJssdkShare, setWechatShare } from '@/util/fiveshare';
	import commonSelect from '@/components/commonSelect/commonSelect.vue';
	import PartnerTipPopup from "@/components/commonPopup/PartnerTipPopup.vue";
	export default {
		data() {
			return {
				idTypeIdx: null,//证件默认值
				showIdType:false,//证件类型下拉框
				idTypesList: [{id:null,name:'请选择'}],
				//实名信息
				realInfo:{
					shiming:{},//实名信息
				},
				isComposing: false,
				companyType : companyInfo.companyType,
				companyLogo : '../../static/logo2.png',
				dataForm: {
					loginId: "1",
					targetType: "5",
					targetId: "1",
					targetNo: "6",
					targetUseFor: "12",
					targetSeq: "0"
				},
				optionForm: {},
				tempInfo:{} //暂存信息 ，以便取消恢复未填写之前的数据
				
			}
		},
		components: {
			commonSelect,
			PartnerTipPopup
		},
		onLoad(options) {
			if(this.companyType == '1'){
				this.companyLogo='../../static/myteam/Group1633.png';
			}else if(this.companyType == '2'){
				this.companyLogo='../../static/logo2.png';
			}
			// 使用深拷贝保存初始数据
			  const initialData = JSON.parse(options.customerBasicInfo);
			  this.optionForm = JSON.parse(JSON.stringify(initialData));
			  this.tempInfo.optionForm = JSON.parse(JSON.stringify(initialData));
			  
			  // 初始化 realInfo.shiming 和 tempInfo.shiming
			  this.realInfo.shiming = {};
			  this.tempInfo.shiming = {};
			// this.optionForm = this.tempInfo.optionForm = JSON.parse(options.customerBasicInfo)
		},
		onShow() {
			// #ifdef H5
				initJssdkShare(() => {
				  setWechatShare();
				}, window.location.href);
			// #endif
			this.getIdType()
		},
		methods: {
			continueCancel(){
				// 使用深拷贝还原数据
				  this.optionForm = JSON.parse(JSON.stringify(this.tempInfo.optionForm));
				  this.realInfo.shiming = JSON.parse(JSON.stringify(this.tempInfo.shiming));
				  this.idTypeIdx = this.tempInfo.idTypeIdx;
				  this.$refs.unbindTipPopup.close();
			},
			
			// 改变实名证件类型
			changeIdTypeSelect(value){
				this.idTypeIdx= value;
				this.realInfo['shiming'].idType= this.idTypesList[value].id
				this.showIdType = 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()
					}
				})
			},
			// 查询实名信息
			getImproveInfo(){
				let params = {
					userId:uni.getStorageSync('cffp_userId'),
					oprType:'0'//因为接口不传这个值会报错，所以传一个值，拿到实名信息
				}
				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 = JSON.parse(JSON.stringify(result.realNameAuthResponse));
							        this.tempInfo.shiming = JSON.parse(JSON.stringify(result.realNameAuthResponse));
							// this.realInfo.shiming = this.tempInfo.shiming = result.realNameAuthResponse
						}
						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 = this.tempInfo.idTypeIdx = index
								}
							}
							
						})
						
						console.log('this.tempInfo',this.tempInfo);
						
					}else{
						uni.showToast({
							title: res['message'],
							duration: 2000,
							icon: 'none'
						})
					}
					
				})
			},
			
			goBack() {
				let back = getCurrentPages();
				if (back && back.length > 1) {
					uni.navigateBack({
						delta: 1
					});
				} else {
					history.back();
				}
			},
			uploadAvatar(event) {
				let that = this;
				CommonUpload(that.dataForm).then(res => {
					this.optionForm.headPicture = res.data.filePath
				})
			},
			// 修改后的表单校验方法
			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('证件号码');
				}
				return {
					isValid: emptyFields.length === 0,
					emptyFields
				};
			},
			// 修改个人资料接口
			submitinfo() {
				if (this.optionForm.nickName&&this.optionForm.nickName.length<2) {
					uni.showToast({title: '昵称为2~10个字符',duration: 2000,icon: 'none'});
					return
				}
				// 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
				// 	}
				// }
				this.saveUserInfo();
			},
			
			saveUserInfo() {
			    let UserRequestVO = {
			        id: uni.getStorageSync('cffp_userId'),
			        realName: this.optionForm.realName,
			        nickName: this.optionForm.nickName,
			        headPicture: this.optionForm.headPicture,
			        userDescription: this.optionForm.userDescription
			    }
			    let params = {
			        realNameAuthRequest: {...this.realInfo.shiming},
			        userId: uni.getStorageSync('cffp_userId'),
					oprType:0 //只更新实名
			    }
			    
			    // 创建两个Promise
			    const updateInfoPromise = api.updateinfo(UserRequestVO).then(res => {
			        if (res.success) {
			            uni.showToast({title: '修改成功', duration: 1000, icon: 'none'});
			            dataHandling.pocessTracking(
			                '个人资料',
			                `成功修改个人资料`,
			                '点击',
			                2,
			                '个人资料',
			                'pages/personalCenter/user-information'
			            )
			            uni.$emit("handClick", {data: this.optionForm});
			        }
			        return res;
			    });
			    
			    const improveInfoPromise = api.submitImproveInfo(params).then(res => {
			        if (res['success']) {
			            dataHandling.pocessTracking(
			                '实名认证成功',
			                `在个人中心完成实名认证`,
			                '点击',
			                2,
			                '个人中心实名',
			                'pages/personalCenter/user-information'
			            )
			        } else {
			            uni.showToast({
			                title: res['message'],
			                duration: 2000,
			                icon: 'none'
			            })
			        }
			        return res;
			    });
			    
			    // 等待两个请求都完成
			    Promise.all([updateInfoPromise, improveInfoPromise])
			        .then(() => {
			            setTimeout(() => {
			                uni.navigateBack({delta: 1});
			            }, 1000);
			        })
			        .catch(error => {
			            console.error("请求出错:", error);
			            // 可以在这里添加错误处理逻辑
			        });
			},
		}
	}
</script>

<style scoped lang="scss">
	.input-tip {
	  color: #ff5a5f;
	  font-size: 12px;
	  margin-left: 10px;
	}
	.container{
		padding-top: 20rpx;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		box-sizing: border-box;
		.userHeader{
			position: relative;
			height: 300rpx;
			width: 100%;
			box-sizing: border-box;
			.headerBox{
				margin-top: -20rpx;
				margin-left: 100rpx;
				position: absolute;
				bottom: 15%;
				left: 14%;
				z-index: 99;
				.add{
					position: absolute;
					bottom: 2%;
					right: 3%;
					background-color: #20269B;
					z-index: 2;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 8rpx;
					border-radius: 50%;
					box-sizing: border-box;
					.icon-jiahao{
						font-size: 28rpx;
						color: #fff;
					}
				}
				.avartBox{
				    width: 200rpx;
				    height: 200rpx;
				    border-radius: 50%;
					border: 10rpx solid #fff;
				    box-sizing: border-box;
				    box-shadow: 0 0 30rpx 15rpx rgba(150, 150, 150, 0.1);
				    position: relative;
					/* 添加以下属性强制硬件加速 */
					transform: translateZ(0);
					-webkit-transform: translateZ(0);
					backface-visibility: hidden;
					-webkit-backface-visibility: hidden;
					overflow: hidden;
					
				    image{
				        display: block; /* 确保图片是块级元素 */
				        width: 100%;    /* 宽度填满容器 */
				        height: 100%;   /* 高度填满容器 */
				        // border-radius: 50%; /* 保持圆形 */
				        object-fit: cover; /* 防止图片变形（可选） */
						/* 同样为图片添加硬件加速 */
						transform: translateZ(0);
						-webkit-transform: translateZ(0);
				    }
				}
			}
			
		}
		.userInformation {
		    position: relative;
		    flex: 1;
			width: 100%;
			display: flex;
			flex-direction: column;
		    .wave {
		        box-sizing: border-box;
		        min-width: 100%;
		        height: 120rpx;
				position: relative;
		        padding: 0;
		        border: none;
				box-shadow: 0 0 30rpx 100rpx rgba(253, 248, 245, 0.4);
		        image {
					position: absolute;
					top: -80%;
		            display: block;
		            min-width: 100%;
		            height: 100%;
		            object-fit: fill; /* 或 cover/contain 根据需求调整 */
		        }
				.nickNameBox{
					color: #333;
					box-sizing: border-box;
					width: 100%;
					position: absolute;
					top: -10%;
					left: 0;
					z-index: 88;
					padding: 0rpx 30rpx 20rpx 30rpx;
					font-size: 30rpx;
					.box{
						border-bottom: 1rpx solid #E4E4E4;
						padding-bottom: 20rpx;
					}
				}
		    }
			.shimingBox{
				padding: 30rpx;
				background-color: #fff;
				color: #333;
				position: relative;
				.itemBox{
					z-index: 100;
					margin-bottom: 20rpx;
					font-size: 28rpx;
					.title{
						font-size: 32rpx;
						font-weight: 600;
						color: block;
					}
					.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;
								padding-right: 20rpx;
								width: 70%;
							}
							
						}
					}
				}
			}
			.bottomBox{
				box-sizing: border-box;
				padding: 40rpx;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 30rpx;
				.cancelBtn{
					padding: 30rpx 100rpx;
					border: 1rpx solid #E4E4E4;
					color: #3F4870;
					border-radius: 100rpx;
				}
				.saveBtn{
					padding: 30rpx 100rpx;
					background-color: #20269B;
					color: #fff;
					border-radius: 100rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.icon-save{
						color: #fff;
						font-size: 28rpx;
						margin-right: 10rpx;
					}
				}
			}
		}
	}
	
	
	
	
	
	.content {
		padding-top: 20rpx;
		width: 100vw;
	}

	// .user-input {
	// 	text-align: right;
	// 	padding-right: 15rpx;
	// 	flex: 1;
	// }

	.user-textarea {
		border: 1px solid #C7C7C7;
		width: 540rpx;
		height: 270rpx;
		border-radius: 10rpx;
	}

	.band {
		margin: 0 20rpx;
		font-size: 26rpx;
	}

	.header {
		display: flex;
		justify-content: center;
	}

	.headportrait {
	  width: 200rpx;
	  height: 200rpx;
	  border-radius: 50%;
	  overflow: hidden;
	  position: relative;
	  /* 添加以下属性强制硬件加速 */
	  transform: translateZ(0);
	  -webkit-transform: translateZ(0);
	  backface-visibility: hidden;
	  -webkit-backface-visibility: hidden;
	}
	
	.headportrait image {
	  width: 100%;
	  height: 100%;
	  object-fit: cover;
	  /* 同样为图片添加硬件加速 */
	  transform: translateZ(0);
	  -webkit-transform: translateZ(0);
	}
	.contentItem {
		margin-top: 40rpx;
		display: flex;
		justify-content: space-between;
		border-bottom: 2rpx solid #E4E4E4;
		padding: 20rpx;
		.left{
			width: 120rpx;
		}
	}

	.footer {
		width: 500rpx;
		height: 80rpx;
		opacity: 1;
		margin: 80rpx auto;
	}

	.user-button {
		color: #FFFFFF;
		background: #20269B;
		border-radius: 80px;
	}
</style>
