<template>
	<div class="system-holidayConfig-container layout-pd">
		<el-card shadow="never">
			<el-calendar v-model="today" :range="dateRange" v-loading="loading">
				<template #header="{ date }">
					<div class="flex-center-center">
						<span class="mr5">选择月份：</span
						><el-date-picker v-model="month" type="month" :clearable="false" placeholder="请选择月份" @change="selectMonth" />
					</div>
					<el-button-group v-auth="'system:holiday:workDay'">
						<el-button type="primary" @click="setHoliday" :disabled="!multipleDates.length">
							<SvgIcon name="ele-Sunny" class="mr3" /> 设定休息日<span v-if="multipleDates?.length">({{ multipleDates.length }})</span></el-button
						>
						<el-button type="primary" @click="setWorkDay" :disabled="!multipleDates.length">
							<SvgIcon name="ele-Monitor" class="mr3" /> 设定工作日<span v-if="multipleDates?.length">({{ multipleDates.length }})</span></el-button
						>
						<el-button type="primary" @click="clearSelect" :disabled="!multipleDates.length"
							><SvgIcon name="ele-Delete" class="mr3" /> 清空选择<span v-if="multipleDates?.length">({{ multipleDates.length }})</span></el-button
						>
					</el-button-group>
					<!--					<el-button-group>
            <el-button @click="setWorkTime"><SvgIcon name="ele-AlarmClock" class="mr3" /> 设定工作时间</el-button>
          </el-button-group>-->
				</template>
				<template #date-cell="{ data }">
					<template v-for="item in state.calendarData">
						<div v-if="data.day === item.currantTime" class="h100">
							<el-checkbox v-model="item.checked" class="w100 h100">
								<div>
									{{ dayjs(data.day).format('D')
									}}<span :class="item.isWorkDay ? 'color-primary' : 'color-success'">（{{ item.isWorkDay ? '工作日' : '休息日' }}）</span>
								</div>
								<div class="lunar" :class="{ 'color-danger font-bold': isFestival(data) }">{{ solarToLunar(data) }}</div>
							</el-checkbox>
						</div>
					</template>
				</template>
			</el-calendar>
		</el-card>
		<!--  工作时间设置  -->
		<el-dialog title="设定工作时间" v-model="dialogVisible" width="600px" draggable>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="120px">
				<el-row :gutter="35">
					<el-col>
						<el-form-item label="休息日工作时间" prop="time" :rules="[{ required: true, message: '请选择休息日工作时间', trigger: 'change' }]">
							<el-time-picker v-model="state.ruleForm.time" is-range range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="工作日工作时间" prop="time1" :rules="[{ required: true, message: '请选择工作日工作时间', trigger: 'change' }]">
							<el-time-picker v-model="state.ruleForm.time1" is-range range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="holidayConfig">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import dayjs from 'dayjs';
import calendar from '@/utils/calendar.js';
import { getDaysSetting, setHolidayApi } from '@/api/system/holiday';

const state = reactive<any>({
	ruleForm: {
		time: '',
		time1: '',
	},
	calendarData: [], // 日历数据
});
const today = ref(new Date()); // 当前日期
const month = ref(new Date()); // 月份
const dialogVisible = ref(false); // 是否显示弹窗
const loading = ref(false); // 加载状态
// 选择月份
const selectMonth = async (val: Date) => {
	state.calendarData = [];
	const days: number = dayjs(val).daysInMonth();
	state.calendarData = Array.from({ length: days }, (_, i) => ({
		currantTime: dayjs(val).startOf('month').add(i, 'day').format('YYYY-MM-DD'),
		checked: false,
		isWorkDay: ![0, 6].includes(dayjs(val).startOf('month').add(i, 'day').day()),
	}));
	dateRange.value = [new Date(dayjs(val).startOf('month').format('YYYY-MM-DD')), new Date(dayjs(val).endOf('month').format('YYYY-MM-DD'))];
	await getSetting(dayjs(val).format('YYYY'), dayjs(val).format('MM'));
	today.value = val;
};
// 日期范围
const dateRange = ref([
	new Date(dayjs(today.value).startOf('month').format('YYYY-MM-DD')),
	new Date(dayjs(today.value).endOf('month').format('YYYY-MM-DD')),
]); // 日期范围
// 设置休息日
const setHoliday = () => {
	ElMessageBox.confirm(`您确定要将【${multipleDates.value.map((item: any) => dayjs(item).format('YYYY-MM-DD')).join(',')}】设为休息日吗？`, '提示', {
		type: 'warning',
		draggable: true,
	})
		.then(() => {
			setHolidayApi({
				list: multipleDates.value,
				isWorkDay: false,
			}).then(() => {
				ElMessage.success('设置成功');
				selectMonth(today.value);
			});
		})
		.catch(() => {});
};
// 设置工作日
const setWorkDay = () => {
	ElMessageBox.confirm(`您确定要将【${multipleDates.value.map((item: any) => dayjs(item).format('YYYY-MM-DD')).join(',')}】设为工作日吗？`, '提示', {
		type: 'warning',
		draggable: true,
	})
		.then(() => {
			setHolidayApi({
				list: multipleDates.value,
				isWorkDay: true,
			}).then(() => {
				ElMessage.success('设置成功');
				selectMonth(today.value);
			});
		})
		.catch(() => {});
};
/*// 设置工作时间
const setWorkTime = () => {
  dialogVisible.value = true;
};*/
// 清除选择
const clearSelect = () => {
	state.calendarData.forEach((item: any) => {
		item.checked = false;
	});
};
// 获取所选中的日期
const multipleDates = computed(() => {
	return state.calendarData.filter((item: any) => item.checked).map((item: any) => item.currantTime);
});
// 表单ref
const ruleFormRef = ref<RefType>();
// 表单提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
	});
};
// 获取休息日设置
const getSetting = async (dateYear: string, dateMoth: string) => {
	loading.value = true;
	try {
		const { result } = await getDaysSetting(dateYear, dateMoth);
		result.forEach((i: any) => {
			const item = state.calendarData.find((j: any) => dayjs(i.day).format('YYYY-MM-DD') === j.currantTime);
			if (item) {
				item.isWorkDay = i.isWorkDay;
			}
		});
	} catch {
		// handle error if needed
	} finally {
		loading.value = false;
	}
};
// 是否休息日
const isFestival = (slotData: any) => {
	let solarDayArr = slotData.day.split('-');
	let lunarDay: any = calendar.solar2lunar(solarDayArr[0], solarDayArr[1], solarDayArr[2]);
	return lunarDay.lunarFestival || lunarDay.festival;
};
// 公历转农历
const solarToLunar = (slotData: any) => {
	let solarDayArr = slotData.day.split('-');
	let lunarDay: any = calendar.solar2lunar(solarDayArr[0], solarDayArr[1], solarDayArr[2]);
	// 农历日期
	let lunarMD = lunarDay.IMonthCn + lunarDay.IDayCn;
	return lunarDay.lunarFestival ? lunarDay.lunarFestival : lunarDay.festival ? lunarDay.festival : lunarMD;
};
onMounted(async () => {
	const days: number = dayjs(today.value).daysInMonth();
	state.calendarData = Array.from({ length: days }, (_, i) => ({
		currantTime: dayjs(today.value).startOf('month').add(i, 'day').format('YYYY-MM-DD'),
		isWorkDay: ![0, 6].includes(dayjs(today.value).startOf('month').add(i, 'day').day()),
		checked: false,
	}));
	await getSetting(dayjs(today.value).format('YYYY'), dayjs(today.value).format('MM'));
});
</script>
<style scoped lang="scss">
/**日期div的样式-农历*/
.el-calendar-table .el-calendar-day > div .lunar {
	padding-top: 10px;
}
:deep(.el-checkbox) {
	align-items: center;
	justify-content: center;
}
:deep(.el-checkbox__input) {
	position: absolute;
	right: 0;
	top: 0;
}
</style>
