<template>
	<div>
		<el-dialog v-model="dialogVisible" title="资源信息" width="30%"  @close="close()">
			<el-form :model="ResourcesInfo" label-width="100px" v-loading="loading" style="padding-right: 40px;">
				<el-form-item label="所属科室:">
					<el-select  :filterable="true" clearable v-model="ResourcesInfo.department_id" placeholder="选择科室">
						<el-option v-for="(item,index) in EnableDepartmentList" :key="index" :label="item.department_name" :value="item.id" /> 
					</el-select> 
				</el-form-item>
				<el-form-item label="资源名称:">
					<el-input v-model="ResourcesInfo.department_resources_name" />
				</el-form-item>
				<el-form-item label="资源位置:">
					<el-input v-model="ResourcesInfo.department_resources_addr" />
				</el-form-item>
				<el-form-item label="资源状态:">
					<el-switch v-model="ResourcesInfo.department_resources_status"  active-text="可用" inactive-text="关闭"
						:active-value="1" :inactive-value="0" />
				</el-form-item>
				<el-form-item label="时令：">
					<div>
						<el-switch v-model="ResourcesInfo.time_mode" size="large" active-text="开启" inactive-text="关闭" :active-value="1" :inactive-value="0" @change="timeModeChange"/>
					</div>

					<div v-if="ResourcesInfo.time_mode==1" style="margin-top: 16px;">
						<!-- 显示夏令时和冬令时的配置 -->
						<div v-for="season in timeRangeList" :key="season.type" style="margin-bottom: 16px;">
							<div style="font-weight: bold; margin-bottom: 8px;">{{ season.type_name }}</div>
							<div v-for="(period, periodIndex) in season.periods" :key="periodIndex" style="display: flex; align-items: center; margin-bottom: 8px;">
								<el-date-picker
									v-model="season.periods[periodIndex]"
									type="daterange"
									format="MM-DD"
									value-format="MM-DD"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									style="width: 400px;"
								/>

								<el-button
									type="danger"
									:icon="Delete"
									@click="deleteRange(season.type, periodIndex)"
									:disabled="season.periods.length <= 1"
									size="small"
									plain
									circle
									style="margin-left: 8px;"
								/>
							</div>
							<el-button type="primary" @click="addRange(season.type)" size="small">
								新增{{ season.type_name }}周期
							</el-button>
						</div>
					</div>
					<div style="margin-left: 18px;color: #ff8b7c;">
						注意：调整时令，会影响该资源下全部模板
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="close()">取消</el-button>
					<el-button type="primary" @click="Save">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		 GetEnableDepartmentList,
		 SaveDepartmentResource
	} from '@/api/api.js'
	import {
		ElMessage
	} from 'element-plus'
	import { Delete } from '@element-plus/icons-vue'
	let loading=ref(false);
	let dialogVisible=ref(true);
	let ResourcesInfo=ref({
		id:null,
		department_id:null,
		department_resources_name:'',
		department_resources_status:1,
		department_resources_addr:'',
		time_mode: 0, // 0关闭 1开启
		time_range: [] // 时令数据
	})

	// 时令数据
	const timeRangeList = ref([
		{
			type: '1',
			type_name: '夏季排班',
			periods: [['', '']]
		},
		{
			type: '2',
			type_name: '冬季排班',
			periods: [['', '']]
		}
	])

	// 新增一组时间范围
	const addRange = (seasonType) => {
		const season = timeRangeList.value.find(s => s.type === seasonType)
		if (season) {
			season.periods.push(['', ''])
		}
	}

	// 删除指定组
	const deleteRange = (seasonType, periodIndex) => {
		const season = timeRangeList.value.find(s => s.type === seasonType)
		if (season && season.periods.length > 1) {
			season.periods.splice(periodIndex, 1)
		}
	}

	// 将数组格式转换为对象格式（用于保存）
	const convertPeriodsToObjects = (periods) => {
		return periods.map(period => ({
			start: period[0],
			end: period[1]
		}))
	}

	// 将对象格式转换为数组格式（用于显示）
	const convertPeriodsToArrays = (periods) => {
		return periods.map(period => [period.start, period.end])
	}

	// 时令开关变化
	const timeModeChange = (e) => {
		// 开关切换不重置 timeRangeList，只控制显示隐藏
		if (e == 1 && timeRangeList.value.length === 0) {
			// 如果开启时令且 timeRangeList 为空，才初始化默认值
			timeRangeList.value = [
				{
					type: '1',
					type_name: '夏季排班',
					periods: [['', '']]
				},
				{
					type: '2',
					type_name: '冬季排班',
					periods: [['', '']]
				}
			]
		}
	}

	// defineProps: 接收父组件传递的数据
		const props = defineProps({
			 departmentId: {
			      
			    },
			resourceInfo:{
				type:Object
			},
		})
 
	
	let EnableDepartmentList =ref([]);
	const GetDepartmentEnableList=()=>{
		loading.value = true
		GetEnableDepartmentList({}).then(res => {
			loading.value = false
			if (res.status) {
				EnableDepartmentList.value = res.data.list
			} else {
				ElMessage.error(res.msg)
			}
		
		})
	}
	const Save=()=>{
		if(!(isNotNullOrEmpty(ResourcesInfo.value.department_id) && isNotNullOrEmpty(ResourcesInfo.value.department_resources_name))){
			ElMessage.error("请填写完整内容")
			return false;
		}

		// 无论是否开启时令，都保存时令数据
		ResourcesInfo.value.time_range = timeRangeList.value.map(season => ({
			type: season.type,
			type_name: season.type_name,
			periods: convertPeriodsToObjects(season.periods)
		}))

		loading.value = true
		SaveDepartmentResource({info:ResourcesInfo.value}).then(res => {
			loading.value = false
			if (res.status) {
				ElMessage({
					message: '保存成功',
					type: 'success',
				})
				close()

			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//传值给父
	const emit = defineEmits(['closeAddResources'])
	const close = () => {
	  emit('closeAddResources')
	}
	const isNotNullOrEmpty=(str)=> {
		return str !== null && str !== '';
	}
	onMounted(() => {
		 console.log(props.departmentId);
		  console.log(props.resourceInfo);
		let	r_departmentId=props.departmentId

		if(props.resourceInfo!=undefined &&props.resourceInfo.id!=undefined ){

			r_departmentId=props.resourceInfo.department_id
			ResourcesInfo.value.id=props.resourceInfo.id
			ResourcesInfo.value.department_resources_name=props.resourceInfo.department_resources_name
			ResourcesInfo.value.department_resources_addr=props.resourceInfo.department_resources_addr
			ResourcesInfo.value.department_resources_status=props.resourceInfo.department_resources_status

			// 加载时令数据
			ResourcesInfo.value.time_mode = props.resourceInfo.time_mode || 0
			// 无论 time_mode 是什么值，都加载 time_range 数据
			if (props.resourceInfo.time_range && props.resourceInfo.time_range.length > 0) {
				timeRangeList.value = props.resourceInfo.time_range.map(season => ({
					type: season.type,
					type_name: season.type_name,
					periods: convertPeriodsToArrays(season.periods)
				}))
			}
		}
		ResourcesInfo.value.department_id=r_departmentId

		GetDepartmentEnableList();
	})
</script>

<style>
</style>