<template>
	<div>
		<div class="head">
			<el-row>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.department_id" placeholder="选择科室" @change="DepartmentChange()"
						style="margin-left: 8px;width: 150px;">
						<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>
					<el-select :filterable="true" clearable v-model="searchInfo.resources_id" placeholder="选择资源"
						style="margin-left: 8px;width: 150px;">
						<el-option v-for="(item,index) in enableResourceList" :key="index"
							:label="item.department_resources_name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.device_id" placeholder="选择服务组"
						style="margin-left: 8px;width: 150px;">
						<el-option v-for="(item,index) in EnableDeviceList" :key="index" :label="item.device_name"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.xingqi" placeholder="星期"
						style="margin-left: 8px;width: 150px;">
						<el-option v-for="(item,index) in xingqi" :key="index" :label="item.label"
							:value="item.label" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.status" placeholder="状态"
						style="margin-left: 8px;width: 150px;">
						<el-option label="正常" value="1" />
						<el-option label="关闭" value="0" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-date-picker style="margin-left: 8px; width: 300px" v-model="searchInfo.dateRange"
						type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
						value-format="YYYY-MM-DD" />
				</el-form-item>
				<el-button @click="GetList()" style="margin-left: 10px;">搜索</el-button>
				<!-- <el-button type="danger" @click="Del()" style="margin-left: 10px;">删除</el-button> -->
			</el-row>
		</div>
		<el-table :data="tableData" style="width: 100%;" row-key="id" v-loading="loading"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" />
			<el-table-column prop="id" label="Id" />
			<el-table-column prop="date" label="日期" width="100">
				<template #default="scope">
					<span>{{ scope.row.date.substring(0, 10) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="weekname" label="星期" />
			<el-table-column prop="resources_id" label="" v-if="false" />
			<el-table-column prop="department_name" label="科室" />
			<el-table-column prop="department_resources_name" label="资源" />
			<el-table-column prop="" label="服务组" show-overflow-tooltip>
				<template #default="scope">
					<div v-if="scope.row.devices.length>0">
						<div v-for="(item,index) in scope.row.devices" :key="index"
							:class="(item.status==1 && item.is_del==0) ? '':'hongzi'">{{ item.device_name }}
						</div>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="period_name" label="时段" />
			<el-table-column prop="begin_time" label="开始时间" />
			<el-table-column prop="end_time" label="结束时间" />
			<el-table-column prop="end_reservation_time" label="截止时间" />
			<el-table-column prop="" label="类型数量" show-overflow-tooltip width="250">
				<template #default="scope">
					<div v-if="scope.row.countsInfo.length>0">
						<div style="font-weight: 700;color:#999">最大数量:{{ scope.row.countsInfo[0].max_total }}</div>
						<div v-for="(item,index) in scope.row.countsInfo" :key="index" style="display: flex;">
							<div style="font-weight:700;width: 50px;text-align: right;margin-right: 8px">{{ item.name
                                }}
							</div>
							<div>共:{{ item.count }} 已用: <span @click="GetMingXi(scope.row,item.appointment_type_id)"
									class="yiyong">{{ item.used_count }}</span>
								余:{{ Number(item.count - item.used_count) }}
							</div>
						</div>
					</div>
				</template>
			</el-table-column>
			<!--            <el-table-column prop="time_unit" label="可用时长" width="80" />-->
			<el-table-column prop="roster_status" label="状态">
				<template #default="scope">
					<el-tag v-if="scope.row.status === 1" class="ml-2" type="success">正常</el-tag>
					<el-tag v-if="scope.row.status === 0" class="ml-2" type="danger">关闭</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="" label="操作">
				<template #default="scope">
					<el-button   @click="getDetail(scope.row.id)" size="small" style="margin-left: 10px;">
						详情
					</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="PlanDetailDialogVisible" title="详情" width="40%">
			<div v-loading="loading">
				<el-form v-if="PlanDetaiInfo" label-width="100px" style="padding-right: 40px;">
					<el-form-item label="日期:">
						{{ PlanDetaiInfo.date }}
					</el-form-item>
					<el-form-item label="星期:">
						{{ PlanDetaiInfo.weekname }}
					</el-form-item>
					<el-form-item label="科室:">
						{{ PlanDetaiInfo.department_name }}
					</el-form-item>
					<el-form-item label="资源:">
						{{ PlanDetaiInfo.resources_name }}
					</el-form-item>
					<el-form-item label="服务组:">
						<el-tag v-for="(item,index) in PlanDetaiInfo.devices" :key="index"
							:type="(item.status===1 && item.is_del===0)?'':'danger'" style="margin-left: 8px">
							{{ item.device_name }}
						</el-tag>
					</el-form-item>
					<el-form-item label="病人类型:">
						<el-checkbox-group disabled v-model="PlanDetaiInfo.patientType">
							<el-checkbox label="0">住院</el-checkbox>
							<el-checkbox label="1">门诊</el-checkbox>
							<el-checkbox label="2">急诊</el-checkbox>
							<el-checkbox label="3">体检</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="时间段:">
						开始时间：<span style="font-weight: 700;display: inline-block;margin-right: 8px">{{ PlanDetaiInfo.begin_time
                        }} </span> 结束时间：<span
							style="font-weight: 700;display: inline-block;margin-right: 8px">{{ PlanDetaiInfo.end_time }}
						</span>
						停止预约时间：<span style="font-weight: 700">{{ PlanDetaiInfo.end_reservation_time }}</span>
					</el-form-item>
					<el-form-item label="渠道名额:" v-if="PlanDetaiInfo.coutsInfo">
						<div style="margin-right: 16px">
							<div>当日总量</div>
							<div class="qudao_k_input">
								<el-input @input="MaxCountChange" disabled type="number" v-model="PlanDetaiInfo.max_total"
									:min="1" placeholder="0" oninput="value=value.replace(/^0|[^0-9]/g, '')" />
							</div>
							<div style="font-size: 12px;color: #999">设置渠道比例可自动分配</div>
						</div>
						<div>
							<div class="qudao_k" v-for="(item,index) in PlanDetaiInfo.coutsInfo" :key="index">
								<div style="width: 50px">{{ item.name }}</div>
								<div class="qudao_k_input">
									<el-input disabled type="number" v-model="PlanDetaiInfo.coutsInfo[index].count" :min="1"
										placeholder="0" oninput="value=value.replace(/^0|[^0-9]/g, '')" />
								</div>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="状态：">
						<el-switch disabled v-model="PlanDetaiInfo.status" size="large" active-text="正常" inactive-text="关闭"
							:active-value="1" :inactive-value="0" />
					</el-form-item>
					<el-form-item label="添加时间：">
						{{ PlanDetaiInfo.created_at }}
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="PlanDetailDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="SavePlanAction">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="MingXiDialogVisible" title="预约明细" width="60%">
			<div>
				<div style="text-align: center;font-size: 16px; margin-top: -30px;margin-bottom: 10px;">{{selectedPlanRow.department_resources_name}}
					<span v-for="(item,index) in selectedPlanRow.devices" :key="index"
						:class="(item.status==1 && item.is_del==0) ? '':'hongzi'">{{ item.device_name }}
					</span>
				</div>
				<el-form-item label="渠道">
					<el-select :filterable="true" clearable v-model="selectecQuDaoid" @change="GetMingXi(selectedPlanRow,selectecQuDaoid)" placeholder="选择渠道"
						style="margin-left: 8px;width: 150px;">
						<el-option  label="全部" :value="0" />
						<el-option v-for="(item1,index1) in selectedPlanRow.countsInfo" :key="index1"
							:label="item1.name" :value="item1.appointment_type_id" />
					</el-select>
				</el-form-item>
				<el-table :data="MingXiList" style="width: 100%;" row-key="id" v-loading="MingXiLoading">
					<el-table-column prop="list_status" label="状态" width="100">
						<template #default="scope">
							<el-tag v-if="scope.row.list_status===0" class="ml-2" type="info">申请中</el-tag>
							<el-tag v-if="scope.row.list_status===1" class="ml-2" type="success">已预约</el-tag>
							<el-tag v-if="scope.row.list_status===2" class="ml-2">登记</el-tag>
							<el-tag v-if="scope.row.list_status===3" class="ml-2" type="warning">完成</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="user_name" label="姓名" />
					<el-table-column prop="user_phone" label="电话" />
					<el-table-column prop="reg_num" label="登记号" />
					<el-table-column prop="reservation_department" label="申请科室" />
					<el-table-column prop="entrust" label="项目" />
					<el-table-column prop="qudao_name" label="渠道" />
				</el-table>
			</div>
		</el-dialog>
	</div>
</template>
<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		PlanListGetList,
		GetEnableDepartmentList,
		GetEnableDeviceList,
		TimePeriodGetEnableList,
		DepartmentResourceGetEnableList,
		PlanDetailChangeInfo,
		PlanListGetDetail,
		PlanDetailPlanListDel,
		GetPlanUsedList
	} from '@/api/api.js'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'


	let loading = ref(false)
	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()
	}
	let tableSelected = ref([])
	const handleSelectionChange = (e) => {
		tableSelected.value = e
	}
	let searchInfo = ref({
		department_id: null,
		resources_id: null,
		device_id: null,
		xingqi: null,
		status: null,
		dateRange: []
	})
	let PlanDetailDialogVisible = ref(false)
	const GetList = () => {
		PlanListGetList({
			page: currentPage.value,
			pageSize: pageSize.value,
			searchInfo: searchInfo.value
		}).then(res => {
			tableData.value = res.data.list
			total = res.data.count
		})
	}

	let xingqi = ref([{
		label: '星期一',
		value: 1
	}, {
		label: '星期二',
		value: 2
	}, {
		label: '星期三',
		value: 3
	}, {
		label: '星期四',
		value: 4
	}, {
		label: '星期五',
		value: 5
	}, {
		label: '星期六',
		value: 6
	}, {
		label: '星期日',
		value: 7
	}])
	//获取可用服务组
	let EnableDeviceList = ref([])
	const GetEnableDeviceListFunc = () => {
		loading.value = true
		GetEnableDeviceList().then(res => {
			loading.value = false
			if (res.status) {
				EnableDeviceList.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	let EnableDepartmentList = ref([])
	const GetDepartmentEnableList = () => {
		loading.value = true
		GetEnableDepartmentList({is_all: true}).then(res => {
			loading.value = false
			if (res.status) {
				EnableDepartmentList.value = res.data.list
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	// //获取可用的时间段
	// let TimePeriodList = ref([])
	// const GetEnableTimePeriod = () => {
	//     loading.value = true
	//     TimePeriodGetEnableList().then(res => {
	//         loading.value = false
	//         if (res.status) {
	//             TimePeriodList.value = res.data
	//         } else {
	//             ElMessage.error(res.msg)
	//         }
	//
	//     })
	// }
	//获取可用资源列表
	let enableResourceList = ref([])
	const getEnableResource = () => {
	 
		DepartmentResourceGetEnableList(
		{department_id: searchInfo.value.department_id}
		).then(res => {
		 
			if (res.status) {
				enableResourceList.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//获取详情
	let PlanDetaiInfo = ref('')
	const getDetail = (id) => {
		PlanDetailDialogVisible.value = true
		loading.value = true
		PlanListGetDetail({
			id: id
		}).then(res => {
			loading.value = false
			if (res.status) {
				PlanDetaiInfo.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//监听最大值输入
	const MaxCountChange = (e) => {
		console.log(e)
		if (e === '' || e == null || e === 0) {
			PlanDetaiInfo.value.max_total = 0
		}
		let temp = 0
		let qudao_count = PlanDetaiInfo.value.coutsInfo.length

		for (let i = 0; i < qudao_count; i++) {
			if (PlanDetaiInfo.value.coutsInfo[i].ratio === 0) continue
			PlanDetaiInfo.value.coutsInfo[i].count = Math.round(PlanDetaiInfo.value.max_total * (PlanDetaiInfo.value
				.coutsInfo[i].ratio / 100))
			temp = temp + PlanDetaiInfo.value.coutsInfo[i].count
			//如果各个渠道的总和与设置的总数不一致，最后1项适当加减，平衡总数
			if (i === qudao_count - 1 && temp !== PlanDetaiInfo.value.max_total) {
				PlanDetaiInfo.value.coutsInfo[i].count = PlanDetaiInfo.value.coutsInfo[i].count - (temp - PlanDetaiInfo
					.value.max_total)
			}
		}
	}
	//保存修改
	const SavePlanAction = () => {
		let tempCount = 0
		PlanDetaiInfo.value.coutsInfo.forEach((item) => {
			tempCount = tempCount + Number(item.count)
		})
		if (tempCount !== Number(PlanDetaiInfo.value.max_total)) {
			ElMessage.error('各个渠道数量之和与当日总量不符')
			return false
		}
		loading.value = true
		PlanDetailChangeInfo({
			PlanDetaiInfo: PlanDetaiInfo.value
		}).then(res => {
			loading.value = false
			if (res.status) {
				PlanDetailDialogVisible.value = false
				GetList()
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	const Del = () => {
		if (tableSelected.value.length == 0) {
			ElMessage.error("请至少勾选1条记录")
			return false
		}
		let ids = []
		tableSelected.value.map((item) => {
			ids.push(item.id)
		})
		ElMessageBox.confirm(
			'确定删除吗？',
			'提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			loading.value = true
			PlanDetailPlanListDel({
				ids: ids
			}).then(res => {
				loading.value = false
				if (res.status) {
					ElMessage({
						message: res.msg,
						type: 'success',
					})
					GetList()
				} else {
					ElMessage.error(res.msg)
				}
			})
		})
	}
	let MingXiDialogVisible = ref(false);
	let MingXiLoading = ref(false)
	let MingXiList = ref(null);
	let selectedPlanRow = ref(null);
	let selectecQuDaoid =ref(null);
	const GetMingXi = (row, typeid) => {
		selectecQuDaoid.value=typeid
		selectedPlanRow.value = row
		MingXiDialogVisible.value = true
		MingXiLoading.value = true
		GetPlanUsedList({
			planid: row.id,
			qudaoid: typeid
		}).then(res => {
			MingXiLoading.value = false
			if (res.status) {
				MingXiList.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
const DepartmentChange = () => {
		enableResourceList.value = []
		if (searchInfo.value.department_id > 0)
			getEnableResource()
	}
	onMounted(() => {
		GetList()
		GetDepartmentEnableList()
	 
		GetEnableDeviceListFunc()
	})
</script>
<style scoped>
	.type_count {
		display: flex;
	}

	.type_count div {
		white-space: nowrap;
		margin-right: 10px;
	}

	.qudao_k {
		display: flex;
	}

	.qudao_k_input {
		width: 150px;
	}

	.hongzi {
		color: #b25252;
	}

	.yiyong {
		font-weight: 700;
		color: #f5a96c;
		cursor: pointer;
	}

	.yiyong:hover {
		color: #666;
	}
</style>