<template>
	<view class="jz-content-box">
		<view class="upload-img-box">
			<jiazhengUpload @getFileUrl="getFileUrl" changjingType="shenfenzheng"></jiazhengUpload>
		</view>
		<view class="form-label-input">
			<view class="phone-form-label"><text class="form-label-require">*</text>手机号</view>
			<uni-easyinput type="number" v-model="formData.userName" placeholder="请输入手机号" maxlength="11" />
		</view>

		<view class="form-label-input">
			<view class="phone-form-label"><text class="form-label-require">*</text>姓名</view>
			<uni-easyinput v-model="formData.realName" placeholder="请输入姓名" />
		</view>

		<view class="form-label-input">
			<view class="phone-form-label">
				<text class="form-label-require">*</text>
				<text v-if="formData.idtype ==1">身份证号</text>
				<text v-if="formData.idtype ==2">护照号</text>
				<icon @click="idCardChange" class="change-icon">切换</icon>
			</view>
			<uni-easyinput v-model="formData.idcard" placeholder="请输入身份证号或护照号" maxlength="18" />
		</view>

		<view class="form-label-select">
			<view class="phone-form-label"><text class="form-label-require">*</text>生日</view>
			<uni-datetime-picker type="line" v-model="formData.birthday">
				<view class="form-radio-select">
					<view>{{formData.birthday}}</view>
					<icon></icon>
				</view>
			</uni-datetime-picker>
		</view>

		<view class="form-label-select">
			<view class="phone-form-label"><text class="form-label-require">*</text>籍贯</view>
			<picker mode="multiSelector" :range="multiArray" :range-key="'label'" :value="multiIndex"
				@columnchange="bindMultiPickerColumnChange" @change="onPickerConfirm" class="select-picker-box">
				<view class="form-radio-select">
					<view>{{ formData.jiguanShengName}} {{formData.jiguanShiName}}</view>
					<icon></icon>
				</view>
			</picker>
		</view>
		<view class="form-label-input">
			<view class="phone-form-label"><text class="form-label-require">*</text>身份证地址</view>
			<uni-easyinput v-model="formData.hujiDizhi" placeholder="请输入身份证地址" />
		</view>
		<view class="form-label-select">
			<view class="phone-form-label"><text class="form-label-require">*</text>民族</view>
			<picker :range="minzuList" mode='selector' :value="formData.minzuIndex" range-key="name"
				@change="minzuChange" @cancel="minzuCancel" class="select-picker-box">
				<view class="form-radio-select">
					<view>{{ formData.minzu.name }}</view>
					<icon></icon>
				</view>
			</picker>
		</view>
		<view class="form-label-radio">
			<view class="phone-form-label"><text class="form-label-require">*</text>性别</view>
			<view class="form-radio-group">
				<view class="form-radio-item" :class="{genderActive: formData.gender==1}" @click="genderSelect(1)">
					男</view>
				<view class="form-radio-item" :class="{genderActive: formData.gender==2}" @click="genderSelect(2)">
					女</view>
			</view>
		</view>
		<view class="form-label-radio form-top-margin flex-start-row">
			<view class="phone-form-label"><text class="form-label-require">*</text>学历</view>
			<dataChecked :list="xueliList" :selectedIds='formData.xueli.id' mode="single" :showAdd="false"
				@change="selectChangeXueliList"/>
		</view>
		<view class="form-label-radio flex-start-row">
			<view class="phone-form-label"><text class="form-label-require"></text>婚姻 </view>
			<dataChecked :list="hunyinList" mode="single" :selectedIds='formData.hunyin.id' :showAdd="false"
				@change="selectChangeHunyinList" />
		</view>


	<view class="form-label-input">
			<view class="phone-form-label"><text class="form-label-require"></text>通讯地址</view>
			<view @click="openMap" class="input-text-row">
				<view >{{formData.juzhuDizhi}}</view>
				<icon></icon>
			</view>
		<!-- 	<picker :range="shuxiangList" mode='selector' :value="formData.shuxiangIndex" range-key="name"
				@change="shuxiangChange" @cancel="shuxiangCancel" class="select-picker-box">
				<view class="form-radio-select">
					<view>{{ formData.juzhuDizhi  }}</view>
					<icon></icon>
				</view>
			</picker> -->
		</view>

		<view class="form-label-select">
			<view class="phone-form-label"><text class="form-label-require"></text>星座</view>
			<picker :range="xingzuoList" mode='selector' :value="formData.xingzuoIndex" range-key="name"
				@change="xingzuoChange" @cancel="xingzuoCancel" class="select-picker-box">
				<view class="form-radio-select">
					<view>{{ formData.xingzuo.name  }}</view>
					<icon></icon>
				</view>
			</picker>
		</view>
		<view class="form-label-select">
			<view class="phone-form-label"><text class="form-label-require"></text>属相</view>
			<picker :range="shuxiangList" mode='selector' :value="formData.shuxiangIndex" range-key="name"
				@change="shuxiangChange" @cancel="shuxiangCancel" class="select-picker-box">
				<view class="form-radio-select">
					<view>{{ formData.shuxiang.name  }}</view>
					<icon></icon>
				</view>
			</picker>
		</view>

		<view class="form-label-switch">
			<view class="phone-form-label"> <text class="form-label-require"></text>星座属相展示到简历 </view>
			<view>展示
				<switch @change="switchXingzuoChange" :checked="formData.xingzuoFlag" color="#3fd2a1"
					style="transform:scale(0.7)" />
			</view>
		</view>

		<view class="agree-section-box form-top-margin">
			<checkbox-group @change="handleAgree">
				<label class="checkbox">
					<checkbox :checked="formData.agree" color="#3fd2a1" style="transform:scale(0.65)" />
					<text>已征得本人同意，将其个人资料信息录入平台</text>
				</label>
			</checkbox-group>
			<button type="default" v-if="status =='add'" @click="goNext" class="phone-green-btn">下一步</button>
			<button type="default" v-if="status =='edit'" @click="editSave" class="phone-green-btn">保存</button>
		</view>
		<uni-popup  ref="popupMap" background-color="#fff" :is-mask-click="false" :mask-click="false" >
				<customMap  style="100vh" @xuanzeAdress="xuanzeAdress" @close="mapClose"></customMap>
		</uni-popup>
	</view>
</template>

<script>
	import dataChecked from './common/dataChecked.vue';
	import jiazhengUpload from "./common/jiazhengUpload.vue"
	import customMap from "@/components/customMap/customMap.vue"
	import {
		getJiazhengXueli,
		getJiazhengHunyin,
		getJiazhengMinzu,
		getJiazhengShuxiang,
		getJiazhengXingzuo,
		getJiazhengJiguan,
		jiazhengIdcard
	} from "@/api/jiazheng.js";
	export default {
		components: {
			dataChecked,
			jiazhengUpload,
			customMap
		},
		props: {
			status: {
				type: String,
			}
		},
		data() {
			return {
				formData: {
					userName: '',
					realName: '',
					idcard: '',
					icon: '',
					birthday: '',
					hujiDizhi: '',
					idtype: '1',
					gender: '',
					juzhuDizhi: '',
					shenfenzhengUrl: '',
					minzu: {},
					shuxiang: {

					},
					xingzuo: {

					},
					hunyin: {
						name: '',

					},
					xueli: {

					},
					jiguanObj: {},
					jiguanShengId: '',
					jiguanShiId: '',
					jiguanShiName: '',
					jiguanShengName: '',
					agree: false,
					xingzuoIndex: 0,
					minzuIndex: 0,
					shuxiangIndex: 0,
					xingzuoFlag: false

				},
				selectedIds: [],
				ceshidata: '',
				xueliList: [],
				hunyinList: [],
				shuxiangList: [],
				xingzuoList: [],
				minzuList: [],
				//	areaTree: [],
				multiArray: [
					[],
					[]
				], // 初始化两列数据
				multiIndex: [0, 0], // 初始化选中索引
				allData: [], // 存储后端返回的完整数据

			}
		},
		created() {
			uni.showLoading({
				title: '加载中'
			});
			this.initRequests()
		},
		methods: {
			xuanzeAdress(data){
				console.log('data',data);
				this.formData.juzhuDizhi = data
				this.mapClose()
			},
			openMap(){
				this.$refs.popupMap.open('bottom')
			},
			mapClose(){
				this.$refs.popupMap.close()
			},
			async initRequests() {
				try {
					await Promise.all([
						this.getXueli(),
						this.getHunyin(),
						this.getMinzu(),
						this.getXingzuo(),
						this.getShuxiang(),
						this.getJiguan(),
					]);
					uni.hideLoading();
					if (this.status == 'edit') {
						this.$emit('finishDom', 'gerenZiliao');
					}
				} catch (e) {
					uni.hideLoading();
					uni.showToast({
						title: `请求失败！`,
						icon: 'none',
						duration: 2000
					})
				}
			},
			editinfo(data) {
				this.$nextTick(() => {
					this.formData.userName = data.userName
					this.formData.realName = data.realName
					this.formData.idcard = data.idcard
					this.formData.idtype = data.idtype
					this.formData.jiguanObj.jiguanShengId = data.jiguanShengId
					this.formData.jiguanShengName = data.jiguanShengName
					this.formData.jiguanObj.jiguanShiId = data.jiguanShiId
					this.formData.jiguanShiName = data.jiguanShiName
					this.formData.juzhuDizhi = data.juzhuDizhi
					this.formData.birthday = data.birthday
					this.formData.minzu = this.dataForId(this.minzuList, data.minzu) || ''
					this.formData.gender = data.gender
					this.formData.xueli = this.dataForId(this.xueliList, data.xueli) || ''
					this.formData.hunyin = this.dataForId(this.hunyinList, data.hunyin) || ''
					this.formData.hujiDizhi = data.hujiDizhi
					this.formData.juzhuDizhi = data.juzhuDizhi
					this.formData.xingzuo = this.dataForId(this.xingzuoList, data.xingzuo) || ''
					this.formData.shuxiang = this.dataForId(this.shuxiangList, data.xingzuo) || ''
					this.formData.xingzuoFlag = data.xingzuoFlag

				})
			},
			dataForId(list, id) {
				return list.find(item => item.id == id);
			},

			idCardChange(data) {
				this.formData.idtype = this.formData.idtype == 1 ? 2 : 1;
			},
			getJiguan() {
				getJiazhengJiguan({}).then(res => {
					//	this.areaTree = res.data
					//	this.pickerData = this.formatData(res.data);
					this.allData = res.data;
					const provinces = this.allData.map(province => ({
						label: province.lable,
						value: province.id,
						children: province.children,
					}));

					const cities = this.allData[0].children.map(city => ({
						label: city.lable,
						value: city.id,
					}));
					// 回显已选中的城市（假设已选中的城市 id 是 1301）
					//this.setSelectedCity(1301);

					this.multiArray = [provinces, cities];
					//console.log('this.pickerData', this.pickerData);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},



			bindMultiPickerColumnChange(e) {
				const {
					column,
					value
				} = e.detail;

				// 更新 multiIndex
				this.multiIndex[column] = value;

				// 如果是第一列（省份）发生变化，更新第二列（城市）
				if (column === 0) {
					const selectedProvince = this.multiArray[0][value];
					const cities = selectedProvince.children.map(city => ({
						label: city.lable,
						value: city.id,
					}));

					// 更新 multiArray 和 multiIndex
					this.multiArray[1] = cities;
					this.multiIndex[1] = 0; // 重置城市列为第一个选项
				}

				// 强制更新视图
				//this.$forceUpdate();
			},
			// 确认选择时获取完整数据
			onPickerConfirm() {
				const [provinceIndex, cityIndex] = this.multiIndex;
	
				const selectedProvince = this.multiArray[0][provinceIndex];
				const selectedCity = this.multiArray[1][cityIndex];
				console.log("选中的省份完整数据：", selectedProvince);
						console.log("选中的城市完整数据：", selectedCity);
				this.formData.jiguanShengId = selectedProvince?selectedProvince.value:''
				this.formData.jiguanShiId = selectedCity?selectedCity.value:''
				this.formData.jiguanShiName =selectedCity?selectedCity.label:''
				this.formData.jiguanShengName = selectedProvince?selectedProvince.label:''
				this.formData.jiguanObj.jiguanShengId = selectedProvince?selectedProvince.value:''
				this.formData.jiguanObj.jiguanShiId = selectedCity?selectedCity.value:''
		
			},
			setSelectedCity(cityId) {
				for (let i = 0; i < this.allData.length; i++) {
					const province = this.allData[i];
					for (let j = 0; j < province.children.length; j++) {
						const city = province.children[j];
						if (city.id === cityId) {
							// 设置选中的省份和城市索引
							this.multiIndex = [i, j];

							// 更新 multiArray 的第二列（城市）
							const cities = province.children.map(city => ({
								label: city.lable,
								value: city.id,
							}));
							this.multiArray[1] = cities;

							// 强制更新视图
							this.$forceUpdate();
							return;
						}
					}
				}
			},

			checkAllFields() {
				const requiredFields = [{
						key: 'userName',
						name: '手机号'
					},
					{
						key: 'realName',
						name: '姓名'
					},
					{
						key: 'idcard',
						name: '身份证号'
					},
					{
						key: 'birthday',
						name: '生日'
					},
					// {
					// 	key: 'hometown',
					// 	name: '家乡',
					// 	type: 'array'
					// },
					// {
					// 	key: 'hujiDizhi',
					// 	name: '身份证地址'
					// },
					{
						key: 'gender',
						name: '性别'
					},
					// {
					// 	key: 'juzhuDizhi',
					// 	name: '通讯地址'
					// },
					{
						key: 'minzu',
						name: '民族',
						type: 'object'
					},
					{
						key: 'jiguanObj',
						name: '籍贯',
						type: 'object'
					},
					{
						key: 'xueli',
						name: '学历',
						type: 'object'
					},
					// {
					// 	key: 'shuxiang',
					// 	name: '属相',
					// 	type: 'object'
					// },
					// {
					// 	key: 'xingzuo',
					// 	name: '星座',
					// 	type: 'object'
					// },
				]

				for (const field of requiredFields) {
					const value = this.formData[field.key]

					// 根据不同类型进行存在验证
					if (field.type === 'array' && !value?.length) {
						this.showAlert(field.name)
						return false
					}
					if (field.type === 'object' && !Object.keys(value).length) {
						this.showAlert(field.name)
						return false
					}
					if (field.type === 'boolean' && value !== true) {
						this.showAlert(field.name)
						return false
					}
					if (!field.type && !value?.toString().trim()) {
						this.showAlert(field.name)
						return false
					}
				}
				return true
			},
			showAlert(fieldName) {
				uni.showToast({
					title: `${fieldName}不能为空`,
					icon: 'none',
					duration: 2000
				})
			},

			getXueli() {
				getJiazhengXueli({}).then(res => {
					this.xueliList = res.data
					//	console.log('xueliList', this.xueliList);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},
			getXingzuo() {
				getJiazhengXingzuo({}).then(res => {
					this.xingzuoList = res.data
					//			console.log('xingzuoList', this.xingzuoList);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},
			getShuxiang() {
				getJiazhengShuxiang({}).then(res => {
					this.shuxiangList = res.data
					//		console.log('shuxiangList', this.shuxiangList);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},
			getHunyin() {
				getJiazhengHunyin({}).then(res => {
					this.hunyinList = res.data
					//	console.log('hunyinList', this.hunyinList);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},
			getMinzu() {
				getJiazhengMinzu({}).then(res => {
					this.minzuList = res.data
					//		console.log('minzuList', this.minzuList);
				}).catch(error => {
					console.error('获取技能类型失败:', error);
				});
			},
			getFileUrl(data) {
				this.formData.shenfenzhengUrl = data
				console.log('data', data);
				jiazhengIdcard({
					url: this.formData.shenfenzhengUrl
				}).then(res => {
					console.log('res', res);
					if (res.code == 0) {





						this.formData.realName = res.data.name
						this.formData.gender = res.data.genderId
						this.formData.minzu.name = res.data.ethnicity
						this.formData.minzu.id = res.data.minzuId
						this.formData.birthday = res.data.birthDate
						this.formData.hujiDizhi = res.data.address
						this.formData.idcard = res.data.idNumber
						this.formData.shuxiang.id = res.data.shuxiangId
						this.formData.shuxiang.name = res.data.shuxiangName
						this.formData.xingzuo.id = res.data.xingzuoId
						this.formData.xingzuo.name = res.data.xingzuoName
						this.formData.jiguanShengId = res.data.jiguanShengId
						this.formData.jiguanShiId = res.data.jiguanShiId
						this.formData.jiguanShengName = res.data.jiguanShengName
						this.formData.jiguanShiName = res.data.jiguanShiName
						this.formData.jiguanObj.jiguanShengId = res.data.jiguanShengId
						this.formData.jiguanObj.jiguanShiId = res.data.jiguanShiId
					}
				})
			},
			minzuChange(e) {
				const index = e.detail.value
				this.formData.minzu = this.minzuList[index]
				//console.log('this.formData.minzu', this.formData.minzu);

			},
			minzuCancel() {
				this.formData.minzuIndex = 0
			},
			xingzuoChange(e) {
				const index = e.detail.value
				this.formData.xingzuo = this.xingzuoList[index]
				//	console.log('this.formData.xingzuo', this.formData.xingzuo);

			},
			xingzuoCancel() {
				this.formData.xingzuoIndex = 0
			},
			shuxiangChange(e) {
				const index = e.detail.value
				this.formData.shuxiang = this.shuxiangList[index]
				//console.log('this.formData.shuxiang', this.formData.shuxiang);

			},
			shuxiangCancel() {
				this.formData.shuxiangIndex = 0
			},
			selectChangeXueliList(data) {
				this.formData.xueli = data[0]
			},
			genderSelect(data) {
				this.formData.gender = data
			},
			selectChangeHunyinList(data) {
				console.log('data', data[0]);
				this.formData.hunyin = data[0]
			},
			switchXingzuoChange(e) {
				this.formData.xingzuoFlag = e.detail.value
			},
			goNext() {
				console.log('formData', this.formData);

				if (!this.checkAllFields()) {
					return false
				}
				if (!this.formData.agree) {
					uni.showToast({
						title: "请勾选本人同意！",
						icon: 'none',
						duration: 2000
					})
					return false
				}
				this.$emit('goNext', this.formData, 0);
			},
			editSave() {
				console.log('formData', this.formData);

				if (!this.checkAllFields()) {
					return false
				}
				if (!this.formData.agree) {
					uni.showToast({
						title: "请勾选本人同意！",
						icon: 'none',
						duration: 2000
					})
					return false
				}
				this.$emit('editSave', this.formData);
			},

			handleAgree(e) {
				this.formData.agree = e.detail.value.length > 0
			},
		}
	}
</script>