<template>
	<view class="con-body">
		<view class="con-bg">
			<!-- 头部 -->
			<customHeader ref="customHeaderRef" :title="'销假申请'" :leftFlag="true" :rightFlag="false">
			</customHeader>

			<!-- 高度来避免头部遮挡 -->
			<view class="top-height"></view>

			<view class="white-bg">
				<view class="example">
					<view class="r-list" style="display: flex;font-size: 14px;padding-top: 32rpx;
					background-color: #03aa0315;height: 76rpx;">
						<view class="r-left">
							<label style="color: #03aa03;font-size: 34rpx;
							padding: 32rpx;background-color: #dcd8d933;">
								{{ applyData.days.replace('.0','')}} 天</label>
						</view>
						<view style="margin-top: -20rpx;">

							<view class="r-right" style="margin-left: 30rpx;">
								{{ applyData.startDate }}
								至
								{{ applyData.endDate }}
							</view>
							<view class="r-right" style="margin-left: 30rpx;color: #00000095;">
								{{ applyData.reason }}
							</view>
						</view>
					</view>
					<uni-forms ref="baseForm" :modelValue="baseFormData" :label-width="80"
						style="margin-top: 20rpx;">
						<uni-forms-item label="销假模式">
							<uni-data-select v-model="baseFormData.typeval" :localdata="range"
								@change="change" :clear="false"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="开始日期">
							<uni-datetime-picker type="date" :clear-icon="false"
								placeholder="请输入开始日期" v-model="baseFormData.startDate"
								@change="change" />
						</uni-forms-item>
						<uni-forms-item v-show="baseFormData.typeval==1" label="结束日期">
							<uni-datetime-picker type="date" :clear-icon="false"
								placeholder="请输入结束日期" v-model="baseFormData.endDate"
								@change="change" />
						</uni-forms-item>
						<uni-forms-item label="开始时间" v-show="baseFormData.typeval!='1'">
							<uni-easyinput v-model="baseFormData.startTime" class="inputborder"
								:disabled="true" style="text-align: center;" />
						</uni-forms-item>
						<uni-forms-item label="结束时间" v-show="baseFormData.typeval!='1'">
							<uni-easyinput v-model="baseFormData.endTime" class="inputborder"
								:disabled="true" style="text-align: center;" />
						</uni-forms-item>
						<uni-forms-item label="销假天数">
							<uni-easyinput v-model="baseFormData.days" class="inputborder"
								:disabled="true" style="text-align: center;" />
						</uni-forms-item>
						<uni-forms-item label="详细说明" class="custom-label-height">
							<uni-easyinput type="textarea" v-model="baseFormData.reason" />
						</uni-forms-item>
					</uni-forms>
				</view>
				<view>
					<button type="primary" @click="submit()">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import customHeader from '@/components/customHeader.vue'
	import {
		addBackApply
	} from '@/api/crm/activity/activity';

	// 表单ref
	let baseForm = ref(null);

	const range = ref([{
		"value": 1,
		"text": "全天"
	}, {
		"value": 2,
		"text": "前半个班次"
	}, {
		"value": 3,
		"text": "后半个班次"
	}]);

	let baseFormData = reactive({
		typeName: "全天",
		typeval: 1,
		startDate: getDate(Date.now()),
		endDate: getDate(Date.now()),
		days: 1,
		reason: '',
		startTime: '08:30',
		endTime: '12:30',
	});

	let leaveId = ref(null);
	let applyData = ref(null);

	onLoad((options) => {
		if (options.data) {
			applyData.value = JSON.parse(decodeURIComponent(options.data))
			leaveId.value = applyData.value.leaveId
		}
	})

	// 查询详情
	let item = ref({});
	const submit = async () => {
		try {
			if (baseFormData.days == 0 ||
				(baseFormData.typeval == 1 &&
					(applyData.value.endDate < baseFormData.endDate ||
						applyData.value.startDate > baseFormData.endDate)) ||
				applyData.value.endDate < baseFormData.startDate ||
				applyData.value.startDate > baseFormData.startDate ||
				baseFormData.startDate < getDate(Date.now()) ||
				parseFloat(baseFormData.days) > parseFloat(applyData.value.days) ||
				(parseFloat(applyData.value.days) == 0.5 && baseFormData.typeval != applyData
					.value.typeval)) {
				uni.showToast({
					title: '请确认日期',
					icon: 'error'
				});
			} else {
				if (baseFormData.typeval != 1) {
					baseFormData.endDate = baseFormData.startDate
				}
				// 验证表单
				await baseForm.value.validate();
				// 验证通过后的操作
				uni.showToast({
					title: '验证通过',
					icon: 'success'
				});

				baseFormData.leaveId = leaveId.value

				addBackApply(baseFormData).then(
					res => {
						if (res.code == 200) {
							uni.showToast({
								title: '提交成功',
								duration: 2000
							});
							setTimeout(function() {
								uni.navigateBack({
									success: () => {
										uni.$emit('isRefresh');
									}
								})
							}, 500);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							});
						}
					},
				);
			}


		} catch (err) {
			console.log('表单验证失败:', err);
		}
	}

	function getDate(dateval) {
		const date = new Date(dateval)
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		return `${year}-${addZero(month)}-${addZero(day)}`
	}

	function addZero(num) {
		if (num < 10) {
			num = `0${num}`
		}
		return num
	}

	let change = () => {
		if (baseFormData.typeval != 1) {
			if (baseFormData.typeval == 2) {
				baseFormData.startTime = '08:30'
				baseFormData.endTime = '12:30'
			} else {
				baseFormData.startTime = '13:00'
				baseFormData.endTime = '17:00'
			}

			baseFormData.days = 0.5
		} else {
			let start = baseFormData.startDate
			let end = baseFormData.endDate
			baseFormData.days = getDayDiff(start, end);
		}

		baseFormData.days = baseFormData.days.toString()
	}

	// 计算两个日期的天数差
	function getDayDiff(startDate, endDate) {
		// 处理日期格式（兼容iOS）
		const start = startDate.replace(/-/g, '/');
		const end = endDate.replace(/-/g, '/');

		const date1 = new Date(start).getTime();
		const date2 = new Date(end).getTime();

		if (date2 < date1) {
			return 0
		}

		// 计算天数差（含边界值+1天）
		return Math.floor(Math.abs(date2 - date1) / (24 * 3600 * 1000)) + 1;
	}
</script>

<style scoped>
	.white-bg {
		width: 690rpx;
		margin: 0;
		border-radius: 8px 8px 0 0;
	}

	.white-bg.white-bg-2 {
		border-radius: 0;
		margin-bottom: 20rpx;
	}

	:deep(.tabs-header) {
		/* background: none !important; */
		border-bottom: none !important;
		margin: 0 auto;
		gap: 5rpx;
	}

	:deep(.tab-item) {
		color: #919191;
		font-size: 32rpx;
		font-weight: bold;
		/* flex:none; */
		/* margin: 0 -50rpx; */
		/* padding: 0 50rpx; */
	}

	:deep(.tab-item:first-child) {
		text-align: right;
		margin-left: 230rpx;
	}

	:deep(.tab-item:last-child) {
		text-align: left;
		margin-right: 230rpx;
	}

	:deep(.tab-item.active) {
		color: #3384DF;
		font-weight: bold;
	}

	:deep(.tab-item.active::after) {
		width: 100rpx;
		height: 8rpx;
	}

	:deep(.is-disabled) {
		background-color: rgba(255, 255, 255, 1) !important;
		color: #333;
	}

	.btn-success {
		background-color: #67c23a;
		border: 1rpx solid #67c23a;
		color: #fff;
		/* padding: 0rpx 60rpx; */
	}

	.btn-warning {
		background-color: #e6a23c;
		border: 1rpx solid #e6a23c;
		color: #fff;
		/* padding: 0rpx 60rpx; */
	}

	:deep(.uni-forms-item__label) {
		padding: 0 20rpx;
		background-color: rgba(230, 162, 60, 0.2);
	}

	:deep(.custom-label-height .uni-forms-item__label) {
		height: 190rpx;
	}

	::v-deep .uni-easyinput__content-textarea {
		height: 152rpx !important;
	}
</style>