<template>
	<div>
		<div class="head">
			<div class="head">
				<el-row>
					<el-form-item>
						<el-input v-model="searchInfo.name" placeholder="请输入模板名称" style="margin-left: 10px;" />
					</el-form-item>
					<el-button type="primary" @click="GetList()" style="margin-left: 10px;">查询</el-button>
					<el-button type="success" @click="Add()" style="margin-left: 10px;">添加</el-button>
				</el-row>
			</div>
		</div>
		<el-table :data="tableData" style="width: 100%;" row-key="id" v-loading="loading">
			<el-table-column prop="id" label="Id" width="100" v-if="false" />
			<el-table-column prop="name" label="名称" />
			<!-- <el-table-column prop="plan_type_name" label="号源类型" /> -->
			<el-table-column prop="" label="起止时间" width="140">
				<template #default="scope">
					{{scope.row.start_time}} - {{scope.row.end_time}}
				</template>
			</el-table-column>
			<el-table-column prop="interval_time" label="时间间隔">
				<template #default="scope">
					{{scope.row.interval_time}}分钟
				</template>
			</el-table-column>
			<el-table-column prop="count" label="号源总数" />
			<el-table-column prop="count" label="预留号源数">
				<template #default="scope">
					{{scope.row.y_number.length}}
				</template>
			</el-table-column>
			<el-table-column prop="" label="操作" width="220">
				<template #default="scope">
					<el-button type="primary" @click="Edit(scope.row)" size="small">修改</el-button>
					<el-button type="danger" @click="Del(scope.row.id)" size="small">删除</el-button>
					<el-button type="success" @click="CreatPlanClick(scope.row)" size="small">生成计划</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="page">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
				:page-sizes="[15, 50, 100, 200]" layout="total,sizes, prev, pager, next" :total="total"
				@size-change="PageSizeChange" @current-change="PageCurrentChange" />
		</div>
		<el-dialog v-model="dialogVisible" title="号源模板设置" style="margin-top: 10px;">
			<div class="chuansuokuang" v-loading="loading">
				<el-form :model="Info" label-width="150" style="max-width: 600px">
					<el-form-item label="医院">
						 <el-select :filterable="true" clearable v-model="Info.hospital_id" placeholder="选择医院">
						 	<el-option label="海南现代妇女儿童医院"
						 		:value="1" />
						 </el-select>
					</el-form-item>
					<el-form-item label="名称">
						<el-input v-model="Info.name" />
					</el-form-item>
					<el-form-item label="起止时间">
						<div style="display: flex;">
							<el-time-picker v-model="Info.TimeRange" value-format='HH:mm:00' is-range
								range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
								@change="TimeRangeChange()" />
						</div>
					</el-form-item>
					<el-form-item label="时间间隔">
						<el-input-number v-model="Info.interval_time" :min="1" :max="10000"
							@input.native="handle($event)" />
					</el-form-item>
					<!-- <el-form-item label="号源类型">
						<el-select :filterable="true" clearable v-model="Info.plan_type" placeholder="选择号源类型">
							<el-option v-for="(item,index) in PlabTypeList" :key="index" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item> -->
					<el-form-item label="状态">
						<el-switch v-model="Info.status" size="large" active-text="正常" inactive-text="停用"
							:active-value="1" :inactive-value="0" />
					</el-form-item>
				</el-form>
				<div  class="plan_type_list">
					<div v-for="(item,index) in PlabTypeList" :key="index" @click="SetPlanType(item)" class="plan_type" :style="'background-color:'+ item.color" >设为 {{item.name}}-<span class="TypeCount">{{item.count}}</span></div>
				</div>
				<div class="timelist_k" v-if="timeList">
					<div v-for="(item,index) in timeList" :key="index" :class="['timelist_button', item.class]" :style="'background-color:'+ item.type_color"
						@click="TimeClick(index)">{{item.time}}</div>

				</div>
				<div>未选中则为预留号源</div>
				
				
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="Save()">
						确定
					</el-button>
					<el-button type="warning" @click="Save2()">
						另存
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="CreatPlanDialogVisible" title="生成号源">
			<div class="chuansuokuang" v-loading="loading">
				<el-form :model="CPlan" label-width="150" >
					<el-form-item label="名称"> 
					<span style="font-size: 14px;font-weight: 700;">{{CPlan.name}}</span>
					</el-form-item>
					<el-form-item label="起止时间">
						<div style="display: flex;">
							<el-date-picker
							      v-model="CPlan.dateRange"
							      type="daterange"
								  value-format="YYYY-MM-DD"
							      range-separator="至"
							      start-placeholder="开始日期"
							      end-placeholder="结束日期">
							    </el-date-picker>
						</div>
					</el-form-item>
					<el-form-item label="星期">
						<el-checkbox  v-model="CPlan.checkedAll" @change="CPanCheckAll()">全选</el-checkbox>
						<el-checkbox-group v-model="CPlan.week">
							<el-checkbox label="1">星期一</el-checkbox>
							<el-checkbox label="2">星期二</el-checkbox>
							<el-checkbox label="3">星期三</el-checkbox>
							<el-checkbox label="4">星期四</el-checkbox>
							<el-checkbox label="5">星期五</el-checkbox>
							<el-checkbox label="6">星期六</el-checkbox>
							<el-checkbox label="7">星期日</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="工作日生成">
						<el-switch v-model="CPlan.workday_create" size="large" active-text="是" inactive-text="否"
							:active-value="1" :inactive-value="0" />
					</el-form-item>
					<el-form-item label="节假日生成">
						<el-switch v-model="CPlan.holiday_create" size="large" active-text="是" inactive-text="否"
							:active-value="1" :inactive-value="0" />
					</el-form-item>
				</el-form>
                 
			</div>
			<div v-if="success_daterange.length>0">
				<div>以下日期内的号源已成功生成</div>
				 <el-tag type="success" style="margin-left: 8px;margin-bottom: 8px;" v-for="(item,index) in success_daterange" :key="index">{{item[0]}}-{{item[1]}}</el-tag>
			</div>
			
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="CreatPlanDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="CreatePlans()">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="CreatTiShiDialogVisible" title="生成号源">
			<div style="margin-bottom: 10px;">当前选择的时间段和现有如下计划时间段有重叠,请先删除</div>
			<div style="display: flex; justify-content: space-between;flex-wrap: wrap;">
				 <el-tag style="margin: 4px;" size="large" v-for="(item,index) in ChongFuList" :key="index" type="">{{item.date +' '+item.time}}</el-tag>
			</div>
			
			<template #footer>
				<span class="dialog-footer">
					<!-- <el-button @click="CreatTiShiDialogVisible = false">取消</el-button> -->
					<el-button type="primary" @click="CreatTiShiDialogVisible = false">
						知道了
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		PlanTypeGetList,
		PlanModelTimeList,
		PlanModelSave,
		PlanModelGetList,
		PlanModelGetDetail,
		PlanModelDel,
		PlanCreate
	} from '@/api/api.js'
	let loading = ref(false)
	let searchInfo = ref({})
	let tableData = ref([])
	let currentPage = ref(1) //当前页码
	let pageSize = ref(15) //每页数量
	let total = 0 //总数量
	const PageSizeChange = (e) => { // 修改每页数量
		pageSize.value = e
		GetList()
	}
	const PageCurrentChange = (e) => { //切换页码
		currentPage.value = e
		GetList()
	}
	const GetList = () => {
		loading.value = true
		PlanModelGetList({
			searchInfo: searchInfo.value,
			page: currentPage.value,
			pageSize: pageSize.value
		}).then(res => {
			loading.value = false
			if (res.status) {
				tableData.value = res.data.list
				total = res.data.count
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	let Info = ref({});
	let dialogVisible = ref(false);
	const Add = async() => {
		Info.value = {}
		Info.value.id = 0
		Info.value.hospital_id=1
		Info.value.status = 1
		Info.value.TimeRange = ['08:00:00', '12:00:00']
		Info.value.interval_time = 5 //间隔，分钟
		dialogVisible.value = true
		await GetPlanTypeList()
		GetTimeList()
	}
	let PlabTypeList = ref([]); //所有可用的号源类型
	const GetPlanTypeList = async () => {
		loading.value = true
		try {
			const res = await PlanTypeGetList({
				searchInfo: {
					status: 1
				},
			})
			if (res.status) { 
				PlabTypeList.value = res.data.list.map(item => ({
					...item,
					count: 0
				}));
			} else {
				ElMessage.error(res.msg)
			}
		} catch (error) {
			ElMessage.error('请求失败')
		} finally {
			loading.value = false
		}
	}
	const handle = (e) => {
		Info.value.interval_time = e

		setTimeout(() => {
			GetTimeList()
		}, 500)

	}
	//改变时间段选择
	const TimeRangeChange = () => {
		GetTimeList()
	}
	//获取时间段列表
	let timeList = ref([])
	const GetTimeList = (type = '') => {
		timeList.value = []
		loading.value = true
		PlanModelTimeList({
			TimeRange: Info.value.TimeRange,
			interval_time: Info.value.interval_time
		}).then(res => {
			loading.value = false
			if (res.status) {
				let time_obj = {}
				res.data.list.forEach((v, i) => {
					if (type == 'detail') { //如果是 编辑模式,回显详情
						if (Info.value.y_number.includes(i)) {
							time_obj = {
								time: v
							}
						} else {
							time_obj = {
								time: v,
								class: "timelist_button_selected"
							}

						}

					} else {
						time_obj = {
							time: v
						}
					}
					timeList.value.push(time_obj)
				})
				console.log('---------',PlabTypeList.value)
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//点击时间
	const TimeClick = (index) => {
		if (timeList.value[index].class == "timelist_button_selected") {
			timeList.value[index].class = ""
			timeList.value[index].type_color = null
			timeList.value[index].plan_type_id = null
		} else {
			timeList.value[index].class = "timelist_button_selected"
		}
	}
	//另存
	const Save2=()=>{
		Info.value.id=0
		Save()
	}
	//保存
	const Save = () => {
		Info.value.y_number = [] //预留号源
		timeList.value.forEach((v, i) => {
			if (v.class != 'timelist_button_selected') {
				Info.value.y_number.push(i)
			}
		})
		Info.value.count = timeList.value.length
		loading.value = true
		PlanModelSave({
			Info: Info.value,
			Timelist:timeList.value
		}).then(res => {
			loading.value = false
			if (res.status) {
				dialogVisible.value = false
				GetList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	const Edit = async(row) => {
		dialogVisible.value = true
		await GetPlanTypeList()
		GetDetail(row.id)
	}
	const GetDetail = (id) => {
		loading.value = true
		PlanModelGetDetail({
			id: id
		}).then(res => {
			loading.value = false
			if (res.status) {
				Info.value = res.data
				//GetTimeList('detail')
				timeList.value=Info.value.list
				timeList.value.forEach((v,i)=>{
					PlabTypeList.value.forEach((t_v,t_i)=>{
						if(v.plan_type_id==t_v.id){
							t_v.count++
						}
					})
					if(v.type==1){
						timeList.value[i].class = "timelist_button_selected"
					}
				})
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	const Del = (id) => {
		loading.value = true
		PlanModelDel({
			id: id
		}).then(res => {
			loading.value = false
			if (res.status) {
				GetList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	let CPlan=ref({});
	let CreatPlanDialogVisible = ref(false)
	let CreatTiShiDialogVisible= ref(false)
	let ChongFuList=ref([]);
	const CreatPlanClick = (row) => {
		CreatPlanDialogVisible.value = true
		CPlan.value.name=row.name
		CPlan.value.model_id=row.id
		CPlan.value.workday_create=1
		CPlan.value.holiday_create=1
		success_daterange.value=[];
	}
	const CPanCheckAll=()=>{//生成计划时全选星期 
		if(CPlan.value.checkedAll){
			CPlan.value.week=['1','2','3','4','5','6','7']
		}else{
			CPlan.value.week=[]
		}
	}
	let success_daterange=ref([]);
	const CreatePlans= async ()=>{ 
		if(loading.value===true) return 
		success_daterange.value=[];
		let ranges=splitDateRange(CPlan.value.dateRange[0],CPlan.value.dateRange[1])
		for (const range of ranges) {
		 let status=  await CreatePlans_r(range)
		 if(status===true){
			 success_daterange.value.push(range)
		 }
		 if(status===false){
			 break;
		 }
		}
	}

	const CreatePlans_r= async (range)=>{
		loading.value = true
		let r_status=false;
		await PlanCreate({
			CPlan: CPlan.value,
			dateRange:range
		}).then(res => {
			loading.value = false
			if (res.status) {
				// CreatPlanDialogVisible.value = false
				 ElMessage({
				 	message: "成功创建"+res.data.success_count+"条计划",
				 	type: 'success',
				 })
				 r_status=true;
			} else {
				if(res.msg=='号源重复'){
					CreatTiShiDialogVisible.value=true
					ChongFuList.value=res.data.list
				}
				ElMessage.error(res.msg)
			}
		})
		return r_status;
	}
	const SetPlanType=(item)=>{
		timeList.value.forEach((v,i)=>{
			if(v.class == "timelist_button_selected" && v.type_color==null){
				timeList.value[i].type_color =item.color
				timeList.value[i].plan_type_id =item.id
				PlabTypeList.value.forEach((t_v,t_i)=>{
					if(item.id==t_v.id){
						t_v.count++
					}
				})
			}
		})
	}
	onMounted(() => {
		GetList()
	})
	
	
	function splitDateRange(startDateStr, endDateStr) {
	    const result = [];
	    const startDate = new Date(startDateStr);
	    const endDate = new Date(endDateStr);
	
	    let currentDate = new Date(startDate);
	    while (currentDate <= endDate) {
	        const year = currentDate.getFullYear();
	        const month = currentDate.getMonth();
	        const nextMonthDate = new Date(year, month + 1, 1);
	        const endOfCurrentMonth = new Date(nextMonthDate - 1);
	
	        // 如果当前月的结束日期超过了总结束日期，则调整为总结束日期
	        const actualEndDate = (endOfCurrentMonth <= endDate)? endOfCurrentMonth : endDate;
	
	        const startStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`;
	        const endStr = `${actualEndDate.getFullYear()}-${String(actualEndDate.getMonth() + 1).padStart(2, '0')}-${String(actualEndDate.getDate()).padStart(2, '0')}`;
	
	        result.push([startStr, endStr]);
	
	        currentDate = nextMonthDate;
	    }
	
	    return result;
	}
</script>

<style scoped>
	.timelist_k {
		display: flex;
		flex-wrap: wrap;
		height: 500px;
		overflow-y: scroll;
	}

	.timelist_button {
		width: 150px;
		border: 1px solid #e2e2e2;
		margin-top: 8px;
		margin-left: 8px;
		text-align: center;
		height: 28px;
		line-height: 28px;
		cursor: pointer;
		background-color: #f4f4f4;
		font-weight: 700;
		border-radius: 4px;
	}

	.timelist_button:hover {
		border: 2px solid #8fc2ff;
		line-height: 26px;
		color: #2b5885;
	}

	.timelist_button_selected {
		background-color: #8fc2ff;
		color: #fff
	}
	.plan_type_list{
		display: flex;
		color: #fff;
	}
	.plan_type{
		padding: 4px 8px;
		border-radius: 6px;
		margin-left: 8px;
		cursor: pointer;
	}
	.TypeCount{
		font-size: 14px;
		font-weight: 900;
		
	}
</style>