<template>
	<div>
		<div class="main" v-if="MainInfo!=null">
			<div class="main_left">
				<div class="k_title">医嘱列表 </div>
				<div v-for="(MainInfo_item,index1) in MainInfo" :key="index1">
					<div v-for="(item,index) in MainInfo_item.itemInfo" :key="index">
						<div :class="(item.selected==true)?'entrust_selected k_entrust':' k_entrust' ">
							<div style="display: flex;">
								<div class="l_title">医嘱项： </div>
								<div class="l_value">{{item.entrust.entrust}}</div>
							</div>
							<div style="display: flex;">
								<div class="l_title">状态：</div>
								<div class="l_value">
									<el-tag v-if="item.entrust.list_status===0" class="ml-2" type="info">申请中</el-tag>
									<el-tag v-if="item.entrust.list_status===1" class="ml-2" type="success">已预约</el-tag>
									<el-tag v-if="item.entrust.list_status===2" class="ml-2">登记</el-tag>
									<el-tag v-if="item.entrust.list_status===3" class="ml-2" type="warning">完成</el-tag>
								</div>
							</div>
							<div style="display: flex;">
								<div><span class="l_title">医生</span>：<span
										class="l_value">{{item.entrust.docotr}}</span>
								</div>
								<div style="margin-left: 12px;"><span class="l_title">是否空腹</span>：<span
										class="l_value"><span v-if=" item.item.limosis==1">是</span><span
											v-else>否</span></span>
								</div>
							</div>
							<div style="display: flex;" v-if="item.entrust.list_status>0">
								<div class="l_title">预约时间：</div>
								<div class="l_value">{{item.entrust.reservation_date}}
									{{item.entrust.period_begin_time.substring(0,5)}}-{{item.entrust.period_end_time.substring(0,5)}}
								</div>
							</div>
							<div style="display: flex;" v-if="item.msg">
								<div class="l_title">提示：</div>
								<div class="l_value">{{item.msg}}</div>
							</div>
						</div>
					</div>

				</div>

			</div>
			<div class="main_right">
				<div style="margin-bottom: 12px;">
					<div class="k_title">用户信息</div>
					<div class="userinfo" v-for="(item,index) in MainInfo" :key="index">
						<span class="l_title">姓名：</span>
						<span class="l_value2">{{item.mainInfo.user_name}} </span>
						<span class="l_title"> 登记号：</span>
						<span class="l_value2">{{item.mainInfo.reg_num}} </span>
						<span class="l_title"> 性别：</span>
						<span class="l_value2"><span v-if="item.mainInfo.user_sex==1">男</span><span
								v-if="item.mainInfo.user_sex==2">女</span> </span>
						<span class="l_title"> 年龄：</span>
						<span class="l_value2">12</span>
						<span class="l_title"> 电话：</span>
						<span class="l_value2">{{item.mainInfo.user_phone}}</span>
					</div>
				</div>
				<div style="">
					<el-form disabled :inline="true" label-width="100px" v-loading="loading"
						style="padding-right: 40px;">
						<el-form-item style="width: 30%;" label="预约日期:">
							<el-input v-model="startYuYueInfo.planInfo.date" />
						</el-form-item>
						<el-form-item style="width: 30%;" label="预约时段:">
							<el-input v-model="startYuYueInfo.planInfo.timeRange" />
						</el-form-item>
						<el-form-item style="width: 30%;" label="资源:">
							<el-input v-model="startYuYueInfo.planInfo.department_resources_name" />
						</el-form-item>
						<el-form-item style="width: 90%;" label="检查项目:">
							<el-input type="textarea" v-model="startYuYueInfo.entrustItems" />
						</el-form-item>
					</el-form>
				</div>
				<div style="margin-bottom: 12px;display: flex;">
					<el-button v-if="YuYueInfo.dotype==1" type="success" @click.prevent="StartYuYue(1)">预 约</el-button>
					<el-button v-if="YuYueInfo.appointment_type==1" type="danger"
						@click="DoctorCancelYuYueFunc()">取消预约</el-button>
					<el-button v-if="YuYueInfo.dotype==2" type="warning" @click="StartYuYue(2)">更改预约时间</el-button>
					<el-button type="primary"  @click="GetEntrustDetail()">刷 新</el-button>
					<el-button @click="ButtonDateChange(1)">上一页</el-button>
					<el-button @click="ButtonDateChange(2)">下一页</el-button>
					<el-button style="display: none;" ref="print_shenqingdan_button"
						v-print="'#shenqingdan'">打印申请单隐藏按钮</el-button>
					<el-button @click="print_shenqingdan()">打印申请单</el-button>
					<el-checkbox-group v-model="auto_print" style="margin-left: 12px;">
						<el-checkbox label="1">预约完成后打印申请单</el-checkbox>
					</el-checkbox-group>
				</div>
				<div style="display: flex; justify-content: space-around;">
					<div>
						<div class="date">
							<div>
								<el-date-picker v-model="table_date1" type="date" placeholder="请选择日期" size="large"
									@change="table_date_change" value-format="YYYY-MM-DD" />
							</div>
							<div style="margin-left: 8px;" v-if="tableData1.weekname">{{tableData1.weekname}}</div>
						</div>
						<div class="plan_table" style="margin-right: 8px;">
							<el-table ref="planTable1" highlight-current-row @row-click="PlanClick1"
								:data="tableData1.plan_list" border style="width: 100%">
								<el-table-column prop="date" label="日期" width="100" />
								<el-table-column prop="weekname" label="星期" width="80" />
								<el-table-column prop="department_resources_name" label="资源" width="120" />
								<el-table-column prop="devices" label="服务组" width="120" />
								<el-table-column prop="" label="时段" width="120">
									<template #default="scope">
										{{scope.row.begin_time.substring(0,5)}}-{{scope.row.end_time.substring(0,5)}}
									</template>
								</el-table-column>
								<el-table-column prop="address" width="90" label="已用/总数">
									<template #default="scope">
										<span @click="UsedCountClick(scope.row)"  style="font-weight: 700;color:cornflowerblue;cursor: pointer;">{{scope.row.used_count}}/{{scope.row.count}}</span>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
					<div>
						<div class="date">
							<div>
								<el-date-picker v-model="table_date2" type="date" placeholder="请选择日期" size="large"
									@change="table_date_change" value-format="YYYY-MM-DD" />
							</div>
							<div style="margin-left: 8px;" v-if="tableData2.weekname">{{tableData2.weekname}}</div>
						</div>
						<div class="plan_table">
							<el-table ref="planTable2" highlight-current-row @row-click="PlanClick2"
								:data="tableData2.plan_list" border style="width: 100%">
								<el-table-column prop="date" label="日期" width="100" />
								<el-table-column prop="weekname" label="星期" width="80" />
								<el-table-column prop="department_resources_name" label="资源" width="120" />
								<el-table-column prop="devices" label="服务组" width="120" />
								<el-table-column prop="" label="时段" width="120">
									<template #default="scope">
										{{scope.row.begin_time.substring(0,5)}}-{{scope.row.end_time.substring(0,5)}}
									</template>
								</el-table-column>
								<el-table-column prop="address" width="90" label="已用/总数">
									<template #default="scope">
										{{scope.row.used_count}}/{{scope.row.count}}
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
				</div>

			</div>
		</div>
		<el-dialog v-model="UsedListShow" title="号源占用详情" width="50%">
			<div>
				<el-table :data="UsedList" style="width: 100%;" row-key="id">
					<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 id="shenqingdan" v-if="shenqingdan_show">
			<div v-for="(item1,index1) in shenqingdan_list" :key="index1">
				<div v-for="(item,index) in item1.itemInfo" :key="index">
					<div v-if="item.entrust.list_status==1" style="height:100vh;">
						<div style="width: 100%;text-align: center;font-size: 14px;">演示医院</div>
						<div style="width: 100%;text-align: center;font-size: 18px;font-weight: bold;">检查申请单</div>
						<div style="width: 100%; border: 1px solid #ccc;padding: 20px;">
							<div>检查项目：{{item.entrust.entrust}}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onActivated,
		onMounted,
		nextTick
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		getMainDetail_duoren,
		NearestEnablePlanDate,
		GetEnablePlan,
		CheckIsDaiJian,
		PlanYuYue,
		DoctorCancelYuYue,
		GetPlanUsedList
	} from '@/api/api.js'
	const props = defineProps({
		YuYueInfo: {
			type: Object
		},
	})
	let loading = ref(false)
	let MainInfo = ref(null);
	let tableData1 = ref([])
	let tableData2 = ref([])
	let table_date1 = ref('');
	let table_date2 = ref('');
	let TodayDate = ref('');
	let MainInfoKey = ref(0); //多人时，选中人的key
	let shenqingdan_show = ref(false);
	let UsedListShow=ref(false);
	let UsedList=ref([]); //号源占用记录
	let auto_print = ref(['1']);
	let EnableGroupItem = ref([]); //可以同时预约的项目,左侧选中的项目
	let planTable1 = ref(null)
	let planTable2 = ref(null)

	let startYuYueInfo = ref({
		planInfo: {
			id: 0,
			date: '',
			timeRange: '',
			department_resources_name: ''
		},
		entrustItems: {},
		entrustids: [],
		mainListids: [],
	});
	const GetEntrustDetail = () => {
		EnableGroupItem.value = [];
		loading.value = true
		getMainDetail_duoren({
			entrustInfo: props.YuYueInfo.entrustInfo,
			appointment_type: props.YuYueInfo.appointment_type,
		}).then(res => {
			loading.value = false
			if (res.status) {
				MainInfo.value = res.data.info
				TodayDate.value = res.data.today_date
				//先让所有项目都同时选中，以后可能会调用接口查询 然后再更新此变量
				MainInfo.value.forEach((v, i) => {
					v.itemInfo.forEach((v2, i2) => {
						EnableGroupItem.value.push(v2.item)
					})
				})
				SelectedEntrustFunc()

			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//获取最近可用日期
	const NearestEnablePlanDateFunc = () => {
		loading.value = true
		NearestEnablePlanDate({
			regnum: MainInfo.value[MainInfoKey.value].mainInfo.reg_num,
			entrustid: startYuYueInfo.value.entrustids,
			episodeid: MainInfo.value[MainInfoKey.value].mainInfo.episodeid,
			appointment_type: props.YuYueInfo.appointment_type,
		}).then(res => {
			loading.value = false
			if (res.status) {
				if (res.data.list.length == 1) {
					table_date1.value = res.data.list[0]
					table_date2.value = getNextDay(table_date1.value,"jia")
				}
				if (res.data.list.length == 2) {
					table_date1.value = res.data.list[0]
					table_date2.value = res.data.list[1]
				}
				GetEnablePlanFunc(table_date1.value, startYuYueInfo.value.entrustids)
				GetEnablePlanFunc(table_date2.value, startYuYueInfo.value.entrustids)
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//获取某日可用号源
	const GetEnablePlanFunc = (date, entrustids) => {
		loading.value = true
		GetEnablePlan({
			regnum: MainInfo.value[MainInfoKey.value].mainInfo.reg_num,
			entrustid: entrustids,
			episodeid: MainInfo.value[MainInfoKey.value].mainInfo.episodeid,
			appointment_type: props.YuYueInfo.appointment_type,
			date: date
		}).then(res => {
			loading.value = false
			if (res.status) {
				if (res.data.appointment_date == table_date1.value) {
					tableData1.value = res.data
					tableData1.value.plan_list.forEach((v, i) => {
						if (v.id == MainInfo.value[MainInfoKey.value].mainInfo.roster_id) {
							planTable1.value.setCurrentRow(v)
						}
					})
				}
				if (res.data.appointment_date == table_date2.value) {
					tableData2.value = res.data
					tableData2.value.plan_list.forEach((v, i) => {
						if (v.id == MainInfo.value[MainInfoKey.value].mainInfo.roster_id) {
							planTable2.value.setCurrentRow(v)
						}
					})
				}
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//选中左侧医嘱
	const SelectedEntrustFunc = () => {
		startYuYueInfo.value.entrustItems = ''
		startYuYueInfo.value.entrustids = []
		startYuYueInfo.value.mainListids = []
		MainInfo.value.forEach((v, i) => {
			v.itemInfo.forEach((v2, i2) => {
				let isok = false;
				EnableGroupItem.value.forEach((j, k) => {
					if (v2.item.id == j.id) {
						isok = true;
					}
				})
				if (isok) {
					MainInfo.value[i].itemInfo[i2].selected = true
					startYuYueInfo.value.entrustItems += v2.item.item_name + ' , '
					startYuYueInfo.value.entrustids.push(v2.entrust.entrust_id)
					startYuYueInfo.value.mainListids.push(v2.entrust.id)
				}
			})

		})
		NearestEnablePlanDateFunc()

	}
	//切换日期
	const table_date_change = (val) => {
		GetEnablePlanFunc(val, startYuYueInfo.value.entrustids)
	}
	//点击 号源
	const PlanClick1 = (val) => {
		console.log(val)
		planTable2.value.setCurrentRow()
		PlanClick(val)
	}
	const PlanClick2 = (val) => {
		console.log(val)
		planTable1.value.setCurrentRow()
		PlanClick(val)
	}
	const PlanClick = (val) => {
		startYuYueInfo.value.planInfo = val
		startYuYueInfo.value.planInfo.timeRange = val.begin_time.substring(0, 5) + '-' + val.end_time.substring(0, 5)
		if (val.id != MainInfo.value[MainInfoKey.value].mainInfo.roster_id) {
			checkDaiJian()
		}


	}
	//检查待检
	const checkDaiJian = () => {
		loading.value = true
		let status = false;
		CheckIsDaiJian({
			reg_num: MainInfo.value[MainInfoKey.value].mainInfo.reg_num,
			planid: startYuYueInfo.value.planInfo.id,
		}).then(res => {
			loading.value = false
			if (res.status) {
				status = true
			} else {
				ElMessage.error(res.msg)
			}
		})
		return status;
	}
	//开始预约
	const StartYuYue = (type) => {
		if (startYuYueInfo.value.planInfo.id == 0 || startYuYueInfo.value.planInfo.id == '') {
			ElMessage.error('请勾选号源')
			return false;
		}
		loading.value = true
		PlanYuYue({
			mainlistid: startYuYueInfo.value.mainListids,
			planid: startYuYueInfo.value.planInfo.id,
			appointment_type: props.YuYueInfo.appointment_type,
			dotype: type
		}).then(res => {
			loading.value = false
			if (res.status) {
				ElMessage({
					message: '预约成功',
					type: 'success',
				})
				GetEntrustDetail()
				if (auto_print.value.length > 0) {
					print_shenqingdan()
				}
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//取消预约（此界面取消预约，不验证密码）
	const DoctorCancelYuYueFunc = () => {
		if (startYuYueInfo.value.mainListids.length !== 1) {
			ElMessage.error('请勾选1条记录')
			return false
		}
		ElMessageBox.confirm(
				'确定取消预约吗？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				loading.value = true
				DoctorCancelYuYue({
					MainListId: startYuYueInfo.value.mainListids[0],
					reg_num: MainInfo.value[MainInfoKey.value].mainInfo.reg_num,
				}).then(res => {
					loading.value = false
					if (res.status) {
						ElMessage({
							message: '取消成功',
							type: 'success',
						})
						GetEntrustDetail()
					} else {
						ElMessage.error(res.msg)
					}
				})
			})

	}
	const ButtonDateChange=(type)=>{
		if(type==1){
		 table_date2.value=getNextDay(table_date1.value,'jian')
		 table_date1.value=getNextDay(table_date2.value,'jian')
		}
		if(type==2){
		 table_date1.value=getNextDay(table_date2.value,'jia')
		 table_date2.value=getNextDay(table_date1.value,'jia')
		}
		table_date_change(table_date1.value)
		table_date_change(table_date2.value)
	}
	const UsedCountClick=(row)=>{
		UsedListShow.value=true
		loading.value = true
		GetPlanUsedList({
			planid: row.id 
		}).then(res => {
			loading.value = false
			if (res.status) {
				 UsedList.value=res.data
			} else {
				ElMessage.error(res.msg)
			}
		})
	}

	//获取第二天日期
	const getNextDay = ((dateString,type) => {
		const date = new Date(dateString);
		if (isNaN(date.getTime())) {
			console.error('日期无效');
			return null;
		}
		
		 
		     
		   if(type=='jia'){
		   	date.setDate(date.getDate() + 1);
		   }
		   if(type=='jian'){
		   	date.setDate(date.getDate() - 1);
		   }
		 
		    return date.toISOString().split('T')[0]; // 或者根据需要格式化日期
	})
	//打印申请单
	let print_shenqingdan_button = ref(null);
	let shenqingdan_list = ref([])
	const print_shenqingdan = () => {

		console.log('开始打印');
		getMainDetail_duoren({
			entrustInfo: props.YuYueInfo.entrustInfo,
			appointment_type: props.YuYueInfo.appointment_type,
		}).then(res => {
			if (res.status) {
				let enable = true
				shenqingdan_list.value = res.data.info
				shenqingdan_list.value.forEach((v, i) => {
					if (v.mainInfo.list_status != 1) {
						ElMessage.error(v.maininfo.entrust + " 不可打印，请重新选择")
						enable = false
					}
				})
				if (enable) {
					shenqingdan_show.value = true
					setTimeout(function() {
						print_shenqingdan_button.value.$el.click();
						shenqingdan_show.value = false
					}, 500)
				}
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	onMounted(() => {
		GetEntrustDetail()
	})
	console.log(props.YuYueInfo);
</script>

<style scoped>
	.main {
		display: flex
	}

	.main_left {
		margin-right: 20px;
		width: 250px;
	}

	.main_right {}

	.k_title {
		font-size: 16px;
		margin-bottom: 8px;
	}

	.date {
		display: flex;
		align-items: center;
	}

	.userinfo {
		border: 1px solid #ddd;
		padding: 8px;
		border-radius: 6px;
	}

	.plan_table {
		margin-top: 8px;
	}

	.l_title {
		font-size: 14px;
	}

	.l_value {
		font-size: 14px;
		font-weight: 700;

	}

	.l_value2 {
		font-size: 16px;
		font-weight: 700;
		color: #31b0d5;
	}

	.k_entrust {
		border: 1px solid #ddd;
		border-radius: 6px;
		margin-bottom: 8px;
		padding: 8px;
		cursor: pointer;
	}

	.entrust_selected {
		background-color: #b1f0fe;
		color: #5f8b9e;
		border: 0px;
	}
</style>
<style>
	.el-table__body tr.current-row>td.el-table__cell {
		background-color: #8cdbf3 !important;
		color: #3b5e67;
	}
</style>