<template>
	<xn-form-container
		:title="formData.id ? '编辑人员' : '增加人员'"
		:width="800"
		:visible="visible"
		:destroy-on-close="true"
		:body-style="{ 'padding-top': '0px' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-tabs v-model:activeKey="activeTabsKey">
				<a-tab-pane key="1" tab="基础信息" force-render>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="账号：" name="account">
								<a-input v-model:value="formData.account" placeholder="请输入账号" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="姓名：" name="name">
								<a-input v-model:value="formData.name" placeholder="请输入姓名" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="员工编号：" name="empNo">
								<a-input v-model:value="formData.empNo" placeholder="请输入员工编号" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="入职日期：" name="entryDate">
								<a-date-picker v-model:value="formData.entryDate" value-format="YYYY-MM-DD" style="width: 100%" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="性别：" name="gender">
								<a-radio-group v-model:value="formData.gender" :options="genderOptions"> </a-radio-group>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="昵称：" name="nickname">
								<a-input v-model:value="formData.nickname" placeholder="请输入昵称" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="手机号：" name="phone">
								<a-input v-model:value="formData.phone" placeholder="请输入手机" allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="紧急联系人电话：" name="emergencyPhone">
								<a-input v-model:value="formData.emergencyPhone" placeholder="请输入紧急联系人电话"  allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="所在区域：" name="homeAddress">
								<a-cascader
									placeholder="请输入所在区域"
									v-model:value="formData.provinceList"
									@change="areaChange"
									:options="area"
									:fieldNames="{ label: 'name', value: 'name', children: 'children' }"></a-cascader>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="详细地址：" name="detailAddress">
								<a-input v-model:value="formData.detailAddress" placeholder="请输入详细地址"  allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="员工照片" name="avatar">
								<x-img-upload @onImgChange="onImgChange"></x-img-upload>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="身份证号：" name="idCardNumber">
								<a-input v-model:value="formData.idCardNumber" placeholder="请输入身份证号" maxlength="18" allow-clear />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item label="选择组织：" name="orgId">
								<a-tree-select
									v-model:value="formData.orgId"
									style="width: 100%"
									:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
									placeholder="请选择组织"
									allow-clear
									tree-default-expand-all
									:tree-data="treeData"
									:tree-default-expanded-keys="treeDefaultExpandedKeys"
									:field-names="{
										children: 'children',
										label: 'name',
										value: 'id'
									}"
									@select="selePositionData"
								/>
							</a-form-item>
						</a-col>
					</a-row>
				</a-tab-pane>
			</a-tabs>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="formLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import area from '@/assets/json/area.json'
	import userApi from '@/api/sys/userApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import {required, rules} from '@/utils/formRules'
	import tool from '@/utils/tool'
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	const activeTabsKey = ref('1')
	const emit = defineEmits({ successful: null })
	const formLoading = ref(false)
	const treeData = ref([])
	const treeDefaultExpandedKeys = ref([])
	// 分页select组件dom定义
	const xnPositionPageSelectRef = ref()
	const xnUserPageSelectRef = ref()
	const xnChildPositionPageSelectRef = ref()
	const xnChildUserPageSelectRef = ref()
	// 表单数据
	const formData = ref({})

	// 打开抽屉
	const onOpen = (record, orgId) => {
		visible.value = true
		formData.value = {
			gender: '男',
			positionJson: []
		}
		if (orgId) {
			formData.value.orgId = orgId
			// 通过机构再查询职位、主管
			nextTick(() => {
				selePositionData(orgId)
			})
		}
		if (record) {
			convertFormData(record)
		}
		nextTick(() => {
			// 机构选择器数据
			userApi.userOrgTreeSelector().then((res) => {
				if (res !== null) {
					treeData.value = res
					// 默认展开2级
					treeData.value.forEach((item) => {
						// 因为0的顶级
						if (item.parentId === '0') {
							treeDefaultExpandedKeys.value.push(item.id)
							// 取到下级ID
							if (item.children) {
								item.children.forEach((items) => {
									treeDefaultExpandedKeys.value.push(items.id)
								})
							}
						}
					})
				}
			})
		})
	}
	// 关闭抽屉
	const onClose = () => {
		treeData.value = []
		treeDefaultExpandedKeys.value = []
		visible.value = false
	}
	// 回显数据
	const convertFormData = (record) => {
		const param = {
			id: record.id
		}
		// 查询详情
		userApi.userDetail(param).then((data) => {
			if (data.positionJson) {
				// 替换表单中的格式与后端查到的
				data.positionJson = JSON.parse(data.positionJson)
			}
			formData.value = Object.assign(formData.value, data)
			// 这里再写一次是因为上面需要先加载增行，下面再进行循环赋值
			if (data.positionJson) {
				// 遍历进行补充
				data.positionJson.map((item, index) => {
					childOrgSelect(item, 1, index)
					return item
				})
			}
			selePositionData(formData.value.orgId)
		})
	}

	// 默认要校验的
	const formRules = {
		account: [required('请输入账号')],
		name: [required('请输入姓名')],
		sex: [required('请选择性别')],
		orgId: [required('请选择组织')],
		empNo: [required('请输入员工编号')],
		phone: [required('请输入手机号'), rules.phone],
		idCardNumber: [required('请输入身份证号'), rules.idCard],
		entryDate: [required('请选择入职日期')],
		emergencyPhone: [required('请输入紧急联系人手机号'), rules.phone],
		homeAddress: [required('请选择所在区域')],
		detailAddress: [required('请输入详细地址')],
		avatar: [required('请上传员工照片')]
	}
	// 机构选择后查询对应的职位
	const selePositionData = (val) => {
		formData.value.orgId = val
		// if (orgId) {
		// 	const xnPositionPageSelectParam = {
		// 		orgId: orgId
		// 	}
		// 	xnPositionPageSelectRef.value.onPage(xnPositionPageSelectParam)
		// 	xnUserPageSelectRef.value.onPage()
		// 	// 此类型代表选择的时候重置后面的职位
		// 	if (type === 0) {
		// 		formData.value.positionId = undefined
		// 		formData.value.directorId = undefined
		// 	}
		// } else {
		// 	formData.value.positionId = undefined
		// 	formData.value.directorId = undefined
		// }
	}
	// 传递选择组件需要的API
	const selectApiFunction = {
		positionSelector: (param) => {
			return userApi.userPositionSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		userSelector: (param) => {
			return userApi.userSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		childPositionSelector: (param) => {
			return userApi.userPositionSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		childUserSelector: (param) => {
			return userApi.userSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		// 通过id回显数据接口
		echoPosition: (param) => {
			return userCenterApi.userCenterGetPositionListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		echoUser: (param) => {
			return userCenterApi.userCenterGetUserListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}
	// 附属职位信息增行
	const addDomains = () => {
		if (formData.value.positionJson === null) {
			formData.value.positionJson = []
		}
		formData.value.positionJson.push({
			orgId: undefined,
			positionId: undefined,
			directorId: undefined
		})
	}
	// 删减行
	const delDomains = (index) => {
		formData.value.positionJson.splice(index, 1)
	}

	// 子表行内选择机构
	const childOrgSelect = (data, type, index) => {
		// 说明正在切换机构，我们就将他的后面的设置空
		if (type === 0) {
			formData.value.positionJson.filter((item, serial) => {
				if (item.orgId === data.orgId && serial === index) {
					item.positionId = undefined
					item.directorId = undefined
				}
			})
		}
		const param = {
			orgId: data.orgId
		}
		nextTick(() => {
			xnChildPositionPageSelectRef.value[index].onPage(param)
			xnChildUserPageSelectRef.value[index].onPage(param)
		})
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			// 因为不切断，我下面转换数据格式，影响上面表单会报错
			// let formDatas = JSON.parse(JSON.stringify(formData.value))
			// if (formDatas.positionJson && formDatas.positionJson.length > 0) {
			// 	formDatas.positionJson = JSON.stringify(formDatas.positionJson)
			// } else {
			// 	delete formDatas.positionJson
			// }
			formLoading.value = true
			if(formData.value.id) {
				let form = new FormData()
				form.append('id', formData.value.id)
				form.append('account', formData.value.account)
				form.append('name', formData.value.name)
				form.append('orgId', formData.value.orgId)
				form.append('empNo', formData.value.empNo)
				form.append('gender', formData.value.gender)
				form.append('phone', formData.value.phone)
				form.append('idCardNumber', formData.value.idCardNumber)
				form.append('nickname', formData.value.nickname)
				form.append('entryDate', formData.value.entryDate)
				form.append('emergencyPhone', formData.value.emergencyPhone)
				form.append('detailAddress', formData.value.detailAddress)
				form.append('homeAddress', formData.value.homeAddress)
				form.append('avatar', formData.value.avatar)
				userApi
					.editUserPage(form).then(() => {
					onClose()
					emit('successful')
				})
					.finally(() => {
						formLoading.value = false
					})
			} else {
				let form = new FormData()
				form.append('account', formData.value.account)
				form.append('name', formData.value.name)
				form.append('orgId', formData.value.orgId)
				form.append('empNo', formData.value.empNo)
				form.append('gender', formData.value.gender)
				form.append('phone', formData.value.phone)
				form.append('idCardNumber', formData.value.idCardNumber)
				form.append('nickname', formData.value.nickname)
				form.append('entryDate', formData.value.entryDate)
				form.append('emergencyPhone', formData.value.emergencyPhone)
				form.append('detailAddress', formData.value.detailAddress)
				form.append('homeAddress', formData.value.homeAddress)
				form.append('avatar', formData.value.avatar)
				userApi
					.addUserPage(form)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						formLoading.value = false
					})
			}
			// userApi
			// 	.submitForm(formDatas, formDatas.id)
			// 	.then(() => {
			// 		onClose()
			// 		emit('successful')
			// 	})
			// 	.finally(() => {
			// 		formLoading.value = false
			// 	})
		})
	}

	const areaChange = (value) => {
		formData.value.homeAddress = value.join('-')
	}

	const onImgChange = (item) => {
		if (item.length > 0) {
			formData.value.avatar = item[0]
		} else {
			formData.value.avatar = undefined
		}
	}
	// 性别
	const genderOptions = tool.dictList('GENDER')
	// 民族
	const nationOptions = tool.dictList('NATION')
	// 身份证件
	const idcardTypeOptions = tool.dictList('IDCARD_TYPE')
	// 文化程度
	const cultureLevelOptions = tool.dictList('CULTURE_LEVEL')
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>

<style scoped type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
	.form-row {
		background-color: var(--item-hover-bg);
		margin-left: 0px !important;
	}
	.form-row-con {
		padding-bottom: 5px;
		padding-top: 5px;
		padding-left: 15px;
	}
	.form-div {
		padding-top: 10px;
	}
</style>
