<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '请假申请',
	},
	}
</route>
<template>
	<PageLayout navTitle="请假申请">
		<wd-form ref="form" :model="model">
			<wd-cell-group border>
				<wd-input label="职工姓名" prop="username" v-model="userStore.userInfo.realname" readonly
					:rules="[{ required: true, message: '请输入职工姓名' }]" />
				<wd-input label="工作单位" prop="sysOrgCode" v-model="userStore.userInfo.department" readonly
					:rules="[{ required: true, message: '请输入工作单位' }]" />
				<wd-input label="联系方式" prop="phone" v-model="model.phone" readonly
					:rules="[{ required: true, message: '请输入联系方式' }]" />
				<wd-col-picker label="请假类型" prop="type" v-model="model.type" :columns="typeData" @confirm="queryMinDate"
					:column-change="columnChange" :display-format="displayFormat" :rules="[{
					    validator: (val) => validateType(val),
					    message: ifOk ? '请选择请假类型' : '有未销假数据,当前只能选择干部离返濮报备', required: true }]" />
				<wd-calendar label="开始时间" prop="begintime" v-model="model.begintime" @confirm="begintimeConfirm"
					:rules="[{ required: true, message: '请选择开始时间' }]" :min-date="minBegintime" />
				<wd-calendar label="结束时间" prop="endtime" v-model="model.endtime"
					:rules="[{ required: true, message: '请选择结束时间' }]" :min-date="minEndtime" />
				<wd-picker :label="examineleader" prop="examineleader" v-model="model.examineleader"
					:columns="examineleaderData" :rules="[{ required: true, message: '请选择' + examineleader }]" />
				<wd-picker label="单位劳资员" prop="hr" v-model="model.hr" :columns="hrData" v-if="zwmc == '0'"/>
				<SelectUser label="班组长" v-model="model.teamleader" isRadioSelection v-if="zwmc == '0'"></SelectUser>
				<wd-input label="出发地" prop="departure" v-model="model.departure"
					:rules="[{ required: true, message: '请输入出发地' }]" />
				<wd-input label="目的地" prop="destination" v-model="model.destination"
					:rules="[{ required: true, message: '请输入目的地' }]" />
				<wd-input label="请假事由" prop="reason" v-model="model.reason"
					:rules="[{ required: true, message: '请输入请假事由' }]" />
				<wd-cell title="附件" title-width="100px" prop="path">
					<wd-upload v-model:file-list="model.path" :action="uploadUrl" multiple></wd-upload>
				</wd-cell>
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
			</view>
		</wd-form>
	</PageLayout>
</template>

<script setup>
	import {
		useMessage,
		useToast
	} from 'wot-design-uni'
	import {
		useAppStore
	} from '@/store';
	import {
		useUserStore
	} from '@/store/user'
	import {
		getCategoryItemsApi
	} from '@/api/system'
	import {
		queryZwmcAndExaApi,
		addApi,
		queryHisDateApi
	} from '@/api/humanResource/absence'
	import {
		queryPostByUserIdApi,
		queryUserByOrgRoleApi
	} from '@/api/system/user'
	import {
		getEnvBaseUrl
	} from '@/utils/index'
	import {
		startMutilProcessApi
	} from '@/api/process'

	const message = useMessage()
	const toast = useToast()
	const appStore = useAppStore();
	const userStore = useUserStore();
	const model = reactive({
		contractNumber: userStore.userInfo.workNo,
		sysOrgCode: userStore.userInfo.orgCode,
		username: userStore.userInfo.username,
		phone: userStore.userInfo.phone,
		type: [], //用[]、0无法正常被验证  就是不选请假类型时也能通过表单验证 所以在form中使用自定义验证
		begintime: null,
		endtime: null,
		examineleader: '',
		hr: '',
		teamleader: '',
		departure: appStore.location,
		destination: '',
		reason: '',
		path: []
	})
	const form = ref()
	const data = ref([])
	const typeData = ref([])
	const examineleaderData = ref([])
	const hrData = ref([])
	/**判断显示审批 / 分管领导*/
	const examineleader = ref('')
	const zwmc = ref('')
	const ifOk = ref(true)
	const minBegintime = ref(0)
	const minEndtime = ref(0)
	/**返回的最新一条请假结束时间*/
	const resDate = ref('')
	const loading = ref(false)
	const uploadUrl = getEnvBaseUrl() + '/sys/common/upload?appPath=职工请假/' + userStore.userInfo.department + '/' +
		userStore.userInfo.realname
	const columnChange = ({
		selectedItem,
		resolve,
		finish
	}) => {
		const areaData = findChildren(data.value, selectedItem.value)
		if (areaData && areaData.length) {
			resolve(
				areaData.map((item) => {
					return {
						value: item.name,
						label: item.name
					}
				})
			)
		} else {
			finish()
		}
	}
	const findChildren = (data, code) => {
		if (!code) {
			return data
		}
		for (const item of data) {
			if (item.name === code) {
				return item.children || null
			}
			if (item.children) {
				const childrenResult = findChildren(item.children, code)
				if (childrenResult) {
					return childrenResult
				}
			}
		}
		return null
	}
	const displayFormat = (selectedItems) => {
		if (selectedItems.length > 0) {
			return selectedItems[selectedItems.length - 1].label
		}
	}
	const validateType = (val) => {
		if (!val || val.length === 0) return false // 必须选择
		const selectedType = val[val.length - 1] // 获取最后一级选中的类型
		// ifOk为true时可以选任何类型，为false时只能选"干部离返濮报备"
		return ifOk.value ? true : selectedType === '干部离返濮报备'
	}

	const handleSubmit = () => {
		if (loading.value) return
		form.value.validate().then(({
			valid,
			errors
		}) => {
			if (valid) {
				const submitData = {
					...model,
					type: model.type[model.type.length - 1], // 取最后一级
					begintime: formatDate(model.begintime),
					endtime: formatDate(model.endtime),
					zwmc: zwmc.value,
					path: model.path.map(item => {
						const response = JSON.parse(item.response);
						return response.message;
					}).join(',')
				}
				message
					.confirm({
						msg: '确认提交请假申请？',
						title: '提示',
					})
					.then(() => {
						loading.value = true
						addApi(submitData).then(res => {
							if (res.success) {
								startMutilProcess(res.message)
							} else {
								toast.warning(res.message)
							}
						})
					})
					.catch(() => {
						loading.value = false
					})
			}
		})
	}

	const startMutilProcess = (id) => {
		startMutilProcessApi({
			flowCode: "dev_cxc_qxj",
			id,
			formUrl: "modules/qxj/modules/CxcQxjBpmModel",
			formUrlMobile: "leaveApplication"
		}).then((res) => {
			if (res.success) {
				toast.success(res.message)
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			}
		}).catch((err) => {
			console.log(err);
		})
	}

	function formatDate(date) {
		date = new Date(date)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		return `${year}-${month}-${day}`
	}

	/*获取请假类型*/
	const getTypeList = () => {
		getCategoryItemsApi('1838487445813645313').then((res) => {
			if (res.success) {
				data.value = res.result
				typeData.value = [data.value.map(item => {
					return {
						value: item.name,
						label: item.name
					}
				})]
			}
		})
	}

	const getZwmcAndExa = () => {
		queryZwmcAndExaApi(userStore.userInfo.username).then((res) => {
			if (res.success) {
				examineleaderData.value = res.result.list.map(item => {
					return {
						label: item.realname,
						value: item.username
					}
				})
				zwmc.value = res.result.zwmc
				if (zwmc.value == '2') {
					examineleader.value = '分管领导';
				} else {
					examineleader.value = '审批领导';
				}
			} else {
				toast.warning(res.message)
				setTimeout(() => {
					handleClickLeft()
				}, 1000)
			}
		})
	}

	const queryHisDate = () => {
		queryPostByUserIdApi(userStore.userInfo.userid).then(ress => {
			queryHisDateApi(userStore.userInfo.username).then(res => {
				if (ress == '员工') { // 员工需要先销假，才能新增请假信息
					if (res.endtime != null && res.resumptiontime == null) {
						toast.warning('请先销假上一条请假信息!')
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)
						return
					}
				} else { //基层干部请假
					if (res.endtime != null && res.resumptiontime == null) {
						ifOk.value = false; //ifOk为false时，说明 有未销假数据 ，只能请 '干部离返濮'
					} else {
						ifOk.value = true;
					}
				}
				resDate.value = res.resumptiontime ? dateStringToTimestamp(res.resumptiontime) :
					res.endtime ? dateStringToTimestamp(res.endtime, 2) : null
				queryMinDate();
			});
		})
	}

	const queryMinDate = () => {
		const today = new Date();
		const threeMonthsAgo = new Date(today);
		threeMonthsAgo.setMonth(today.getMonth() - 3);
		if (resDate.value && model.type[model.type.length - 1] !== '干部离返濮报备') {
			minBegintime.value = resDate.value;
		} else {
			minBegintime.value = threeMonthsAgo.getTime();
		}
		model.begintime = resDate.value ?
			(resDate.value > dateStringToTimestamp() ? resDate.value : dateStringToTimestamp()) :
			dateStringToTimestamp(null, 1);
		minEndtime.value = model.begintime;
	};

	/**
	 * 将日期字符串转换为13位时间戳（支持yyyymmdd和yyyy-mm-dd格式）
	 * @param {string} dateStr 
	 * @returns {number} 13位时间戳（毫秒）
	 */
	function dateStringToTimestamp(dateStr, flag) {
		const date = new Date();
		if (flag === 1) {
			date.setDate(date.getDate() + 1);
		} else if (dateStr) {
			const normalized = dateStr.replace(/-/g, '');
			date.setFullYear(
				parseInt(normalized.substring(0, 4)),
				parseInt(normalized.substring(4, 6)) - 1,
				parseInt(normalized.substring(6, 8))
			);
			if (flag === 2) {
				date.setDate(date.getDate() + 1);
			}
		}
		date.setHours(0, 0, 0, 0);
		return date.getTime();
	}

	const begintimeConfirm = () => {
		/*将结束时间置空*/
		model.endtime = null
		/*改变结束时间最小值*/
		minEndtime.value = model.begintime
	}

	const getHrList = () => {
		queryUserByOrgRoleApi({
			roleId: '1554379432313397250',
			orgCode: userStore.userInfo.orgCode
		}).then(res => {
			model.hr = res.result[0].username
			hrData.value = res.result.map(item => {
				return {
					label: item.realname,
					value: item.username
				}
			})
		})
	}

	onLoad(() => {
		/*获取请假类别*/
		getTypeList()
		/*获取审批领导*/
		getZwmcAndExa()
		/*获取劳资员*/
		getHrList()
		/*获取*/
		queryHisDate()
	});
</script>

<style lang="scss" scoped>
	.footer {
		padding: 12px;
	}
</style>