<template>
	<div v-loading="loading">
		<el-dialog title="预约列表" class="iframeDialog" v-model="iframe_show" @opened="dialogopened" @closed="closeYuYueDialog()">
			<iframe id="bdIframe" :src="selectedUrl" class="iframe" :key="YuYueKey" scrolling="auto"></iframe>
		</el-dialog>
		<el-dialog v-model="YuYueVueDialogVisible" fullscreen @close="closeYuYueDialog()">
			<YuYue202506 :reg_num="tableSelected[0].reg_num" :entrust_ids="entrust_ids" :key="YuYueKey" :episode_id="tableSelected[0].episodeid" appointment_type="4" :dotype="do_type" :do_user="loginUserinfo.id" :special_privileges="loginUserinfo.special_privileges" :scope="'department'"></YuYue202506>
		</el-dialog>
		<div class="head">
			<el-row>
				<el-form-item>
					<el-select v-model="searchInfo.dateType" placeholder="时间筛选类型"
						style="margin-left: 8px;width: 150px;">
						<el-option label="预约日期" value="reservation_date" />
						<el-option label="医嘱日期" value="entrust_date" />
						<el-option label="同时生效" value="both" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-date-picker style="margin-left: 8px; width: 150px" v-model="searchInfo.dateRange[0]"
						type="date" placeholder="开始时间" value-format="YYYY-MM-DD" />
					<span style="margin: 0 4px;">至</span>
					<el-date-picker style="width: 150px" v-model="searchInfo.dateRange[1]"
							type="date" placeholder="结束时间" value-format="YYYY-MM-DD" />
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.list_status" placeholder="状态"
						style="margin-left: 8px;width: 150px;">
						<el-option label="申请中" value="0" />
						<el-option label="已预约" value="1" />
						<el-option label="已报道" value="2" />
						<el-option label="已结束" value="3" />
					</el-select>
				</el-form-item>
		
					<el-form-item v-if="loginUserinfo && loginUserinfo.group!=2">
						<el-select :filterable="true" clearable v-model="searchInfo.patient_type" placeholder="患者类型"
							style="margin-left: 8px;width: 150px;">
							<el-option label="住院" value="0" />
							<el-option label="门诊" value="1" />
							<el-option label="急诊" value="2" />
							<el-option label="体检" value="3" />
						</el-select>
					</el-form-item>
					<el-form-item v-if="loginUserinfo && loginUserinfo.group!=2">
						<el-select multiple :filterable="true" clearable v-model="searchInfo.resources" placeholder="排班资源"
							style="margin-left: 8px;width: 250px;">
							<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-input v-model="searchInfo.reg_num" placeholder="登记号" style="width: 200px;margin-left: 8px;" />
				</el-form-item>
				<el-form-item>
					<el-input v-model="searchInfo.user_name" placeholder="患者姓名"
						style="width: 200px;margin-left: 8px;" />
				</el-form-item>
				<el-form-item>
					<el-select
						v-model="searchInfo.apply_department"
						filterable
						remote
						clearable
						reserve-keyword
						placeholder="申请科室"
						style="width: 200px;margin-left: 8px;"
						:remote-method="debouncedSearchDept"
					>
						<el-option
							v-for="item in deptOptions"
							:key="item.id"
							:label="item.department_name + ' (' + item.department_number + ')'"
							:value="item.department_name"
						/>
					</el-select>
				</el-form-item>
				<el-form-item v-if="loginUserinfo">
					<el-input v-model="searchInfo.doctor" :disabled="loginUserinfo.group==7" placeholder="医生"
						style="width: 200px;margin-left: 8px;" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="GetList()" style="margin-left: 10px;">查询</el-button>
				</el-form-item>

			</el-row>


			<el-row style="margin: 0px 0px 8px 8px; border-top: 1px solid #ccc;padding-top: 8px">
				<el-button type="success" @click.prevent="openIframe(1)">预 约</el-button>
				<el-button type="danger" @click="cancel()">取消预约</el-button>
				<el-button type="warning" @click="openIframe(2)">更改预约时间</el-button>
				<el-button type="primary" @click="SignInFunc()" style="margin-left: 40px;">报到</el-button>
				<el-button v-if="false" type="danger" @click="CancelSignFunc()">取消报到</el-button>
				<el-button @click="print_shenqingdan()">打印申请单</el-button>
				<el-button @click="batchPrint()">批量打印申请单</el-button>
				<el-button v-if="false" v-print="'#tablelist'" >打印表格</el-button>
				
			</el-row>
		</div>
		<el-table :data="tableData" id="tablelist" style="width: 100%;" row-key="id" v-loading="loading" ref="tableref"
			@select="handleSelect">
			<el-table-column type="selection" width="50">
				<template #header><span></span></template>
			</el-table-column>
			<el-table-column prop="list_status" label="状态" width="80">
				<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 label="门诊号" width="120">
				<template #default="scope">
					<span v-if="scope.row.patient_type != 0">{{ scope.row.reg_num }}</span>
				</template>
			</el-table-column>
			<el-table-column label="住院号" width="120">
				<template #default="scope">
					<span v-if="scope.row.patient_type == 0">{{ scope.row.episodeid?.slice(-10) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="user_name" label="姓名" />
			<el-table-column prop="user_sex" label="性别" width="60">
				<template #default="scope">
					<span v-if="scope.row.user_sex==1">男</span>
					<span v-if="scope.row.user_sex==2">女</span>
				</template>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="115" />
			<el-table-column prop="entrust" label="医嘱" width="200" />
			<el-table-column prop="is_pay" label="是否交费" width="80">
				<template #default="scope">
					<span v-if="scope.row.is_pay==1">是</span>
					<span v-if="scope.row.is_pay==0">否</span>
				</template>
			</el-table-column>
			<el-table-column prop="reservation_date" label="预约日期" width="120" />
			<el-table-column prop="check_begin_time" label="预约时间" width="120">
				<template #default="scope">
					<span
						v-if="scope.row.period_begin_time  && scope.row.period_end_time ">{{scope.row.period_begin_time.substring(0, 5)}}~{{scope.row.period_end_time.substring(0, 5)}}</span>
				</template>
			</el-table-column>
			<el-table-column prop="department_resources_name" label="排班" width="120" />
			<el-table-column prop="reservation_department" label="申请科室" width="120" />
			<el-table-column prop="" label="医嘱时间" width="160">
				<template #default="scope">
					{{scope.row.entrust_date}} {{scope.row.entrust_time}}
				</template>
			</el-table-column>
			<el-table-column prop="docotr" label="申请医生" width="80" />
			<el-table-column prop="patient_type" label="病人类型" width="80">
				<template #default="scope">
					<span v-if="scope.row.patient_type==0">住院</span>
					<span v-if="scope.row.patient_type==1">门诊</span>
					<span v-if="scope.row.patient_type==2">急诊</span>
					<span v-if="scope.row.patient_type==3">体检</span>
				</template>
			</el-table-column>
			<el-table-column prop="user_phone" label="电话" width="120" />
			<!-- <el-table-column prop="implement_department" label="执行科室" width="120" /> -->
			<el-table-column prop="department_resources_name" label="操作" width="120">
				<template #default="scope">
					<el-button @click="showLog(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="LogShow" title="变更记录" width="50%">
			<div>
				<el-table :data="LogList" style="width: 100%;" row-key="id">
					<el-table-column prop="list_status" label="状态" width="100">
						<template #default="scope">
							<el-tag v-if="scope.row.new_status==0" class="ml-2" type="info">申请中</el-tag>
							<el-tag v-if="scope.row.new_status==1" class="ml-2" type="success">已预约</el-tag>
							<el-tag v-if="scope.row.new_status==2" class="ml-2">登记</el-tag>
							<el-tag v-if="scope.row.new_status==3" class="ml-2" type="warning">完成</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="reg_num" label="登记号" />
					<el-table-column prop="note" label="说明" />
					<el-table-column prop="create_user" label="操作人/ID" />
					<el-table-column prop="created_at" label="记录时间" />
					<el-table-column prop="data" label="状态" width="100">
						<template #default="scope">
							<el-button @click="showLogJson(scope.row.data)" size="small">查看data</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
		<el-dialog v-model="LogDataShow" title="查看dataJson" width="40%">
			<div style="word-break: break-all">
				{{LogDataJson}}
			</div>
		</el-dialog>
		<el-dialog v-model="ItemGroupShow" title="选择可一起预约的项目" width="40%">
			<div v-if="ItemGroup.length>0">
				<div style="display: flex; border:1px solid #ccc;color: #999;">
					<div style="width: 50%; border-right: 1px solid #ccc;padding: 8px; text-align: center;">
						可一起预约项目
					</div>
					<div style="width: 50%;  padding: 8px;text-align: center;">
						关联的排班
					</div>
				</div>
				<div v-for="(group,index) in ItemGroup" :key="index" class="dialogitem" @click="ClickGroup(group)">
					<div style="width: 50%; display: flex;border-right: 1px solid #ccc;padding: 8px;">
						<div v-for="(item,i) in group">
							<span style="margin-left: 8px; width: 200px;">{{item.item_name}}</span>
						</div>
					</div>
					<div style="margin-left: 8px;padding: 8px;display: flex;">
						<div>{{group[0].device_name}}</div>
					</div>
				</div>
			</div>

		</el-dialog>
		<el-dialog v-model="TiShiShow" title="提示" width="40%" >
			<div v-for="(item,index) in successItem" :key="index" style="font-size:16px;">
				  
				 <table style="margin-top: -30px;">
					 <tr><td colspan="2" style="font-weight: 700; font-size: 18px;color:#4b6493">{{item.entrus	}}<el-tag type="success" size="large">预约成功</el-tag></td></tr>
					 <tr><td style="font-weight: 700;">体检号：</td><td>{{item.signInData[0].checkNo}}</td></tr>
					 <tr><td style="font-weight: 700;">排队号：</td><td>{{item.signInData[0].queueNo}}</td></tr>
					 <tr><td style="font-weight: 700;">等待人数：</td><td>{{item.signInData[0].currentNum}}</td></tr>
				 </table>
			</div>
			<div v-for="(item,index) in failItem" :key="index+200" style="color: crimson;">
				  {{item}}
			</div>
		</el-dialog>
		<el-dialog v-model="batchPrintDialogVisible" title="批量打印申请单" width="95%">
			<el-table :data="tableData.filter(v => v.list_status === 1)" ref="batchPrintTableRef"
				@selection-change="handleBatchSelectionChange" row-key="id" class="batch-print-table">
				<el-table-column type="selection" width="50" />
				<el-table-column prop="list_status" label="状态" width="80">
					<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 label="门诊号" width="120">
					<template #default="scope">
						<span v-if="scope.row.patient_type != 0">{{ scope.row.reg_num }}</span>
					</template>
				</el-table-column>
				<el-table-column label="住院号" width="120">
					<template #default="scope">
						<span v-if="scope.row.patient_type == 0">{{ scope.row.episodeid?.slice(-10) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="user_name" label="姓名" />
				<el-table-column prop="user_sex" label="性别" width="60">
					<template #default="scope">
						<span v-if="scope.row.user_sex==1">男</span>
						<span v-if="scope.row.user_sex==2">女</span>
					</template>
				</el-table-column>
				<el-table-column prop="age" label="年龄" width="115" />
				<el-table-column prop="entrust" label="医嘱" width="200" />
				<el-table-column prop="is_pay" label="是否交费" width="80">
					<template #default="scope">
						<span v-if="scope.row.is_pay==1">是</span>
						<span v-if="scope.row.is_pay==0">否</span>
					</template>
				</el-table-column>
				<el-table-column prop="reservation_date" label="预约日期" width="120" />
				<el-table-column prop="check_begin_time" label="预约时间" width="120">
					<template #default="scope">
						<span v-if="scope.row.period_begin_time && scope.row.period_end_time">{{scope.row.period_begin_time.substring(0, 5)}}~{{scope.row.period_end_time.substring(0, 5)}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="department_resources_name" label="排班" width="120" />
				<el-table-column prop="reservation_department" label="申请科室" width="120" />
				<el-table-column prop="" label="医嘱时间" width="160">
					<template #default="scope">
						{{scope.row.entrust_date}} {{scope.row.entrust_time}}
					</template>
				</el-table-column>
				<el-table-column prop="docotr" label="申请医生" width="80" />
				<el-table-column prop="patient_type" label="病人类型" width="80">
					<template #default="scope">
						<span v-if="scope.row.patient_type==0">住院</span>
						<span v-if="scope.row.patient_type==1">门诊</span>
						<span v-if="scope.row.patient_type==2">急诊</span>
						<span v-if="scope.row.patient_type==3">体检</span>
					</template>
				</el-table-column>
				<el-table-column prop="user_phone" label="电话" width="120" />
			</el-table>
			<template #footer>
				<el-button @click="batchPrintDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="confirmBatchPrint">确认打印</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import { useRoute } from 'vue-router'
	import {
		ref,
		onMounted,
		nextTick,watch
	} from 'vue'

	import {
		GetMainList,
		CancelYuYue,
		GetEnableDeviceList,
		DepartmentResourceGetEnableList,
		GetServiceDateTime,
		GetLoglist,
		CheckEntrstItemGroup,getMainDetail,SignIn,CancelSign,
		SearchDepartment
	} from '@/api/api.js'
	import {
		usePinia
	} from '@/stores/index.js'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import YuYue202506 from '@/components/Yewu/YuYue202506.vue'
	
	let pinia = usePinia()
	
	const route = useRoute()
	
	let YuYueVueDialogVisible=ref(false);
	let YuYueKey=ref(0);
	let AutoGroup=ref(true);//自动分组是否开启
	let do_type = ref(0) //按钮操作类型1预约2改约
	let loading = ref(false)
	let entrust_ids=ref('')
	let searchInfo = ref({
		dateType: 'reservation_date',
		dateRange: [],
		list_status: null,
		patient_type: null,
		resources: [],
		services_group: null,
		reg_num: null,
		user_name: null,
		apply_department: null
	})
	let loginType=ref('');
	//获取检查项目列表
	let tableData = ref([])
	let tableref = ref(null)
	let currentPage = ref(1) //当前页码
	let pageSize = ref(15) //每页数量
	let total = 0 //总数量
	let deptOptions = ref([])

	//简单防抖函数
	const debounce = (fn, delay) => {
		let timer = null
		return function(...args) {
			clearTimeout(timer)
			timer = setTimeout(() => fn.apply(this, args), delay)
		}
	}

	//远程搜索科室
	const searchDept = (keyword) => {
		if (!keyword) {
			deptOptions.value = []
			return
		}
		SearchDepartment({ keyword }).then(res => {
			if (res.status) {
				deptOptions.value = res.data.list
			} else {
				deptOptions.value = []
			}
		})
	}
	const debouncedSearchDept = debounce(searchDept, 300)
	const GetList = () => {
		loading.value = true
		GetMainList({
			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)
			}

		})
	}
	const PageSizeChange = (e) => { // 修改每页数量
		pageSize.value = e
		GetList()
	}
	const PageCurrentChange = (e) => { //切换页码
		currentPage.value = e
		GetList()
	}
	let tableSelected = ref([])
	const handleSelect = (e) => {
		if (e.length > 1) {
			const firstStatus = e[0].list_status;
			// 检查所有元素的状态是否一致,如果勾选的有不同状态，则只选中最后1个
			const allEqual = e.every(item => item.list_status === firstStatus);
			if (!allEqual) {
				SelectClear()
				e = [e[e.length - 1]]
			}
		}
		
		if (e[e.length - 1].list_status != 0) { //非申请状态，只能勾选1个 
			SelectClear()
			e = [e[e.length - 1]]
		}
		let select_qian = tableSelected.value ? tableSelected.value.length : 0
		//SelectClear();
		autoSeleted(e)
	//	console.log('后：', tableSelected.value)
		if (select_qian > tableSelected.value.length) {
		} else {
			FindMatchItem()
		}
	}
	const handleSelectionChange = (e) => {
		// tableSelected.value = e
		//console.log(e)
	}
	const SelectClear = () => {
		//console.log("清空选中数据前==", tableref.value.getSelectionRows())
		//清空数据，通过Element-Plus表格的clearSelection的方法，清空所有已选中的数据
		tableref.value.clearSelection()
	//	console.log("清空选中数据后==", tableref.value.getSelectionRows())
		tableSelected.value = []
	}
	const autoSeleted = (rows) => {
		if (rows) {
			rows.forEach((row) => {
				if(row!=undefined){
					tableref.value.toggleRowSelection(row, true)
				}
			})
			tableSelected.value = rows
		} else {

			SelectClear()
		}
	}
	let ItemGroupShow = ref(false);
	let ItemGroup = ref(null);
	//查找同一个人同一个就诊号，当前页面 状态申请中的项目名称
	const FindMatchItem = () => {
		console.log(tableSelected.value)
		tableSelected.value.reverse();
		let temp_reg_num=''
		let chongzhi=false;
		tableSelected.value.forEach((v, i) => {
			if(temp_reg_num==''){
				temp_reg_num=v.reg_num
			}
			if(temp_reg_num!='' && temp_reg_num!=v.reg_num){
				 chongzhi=true
			}
			
		})
		if(chongzhi===true){
			let a=tableSelected.value[0]
			SelectClear();
			 
			autoSeleted([a])
		}
		console.log(tableSelected.value)
		let list = []
		if(tableSelected.value[0].list_status!=0)return false //如果勾选的不是申请中的医嘱则不进行匹配
		
		tableData.value.forEach((v, i) => {
			if (v.list_status == 0 && v.reg_num == tableSelected.value[0].reg_num && v.episodeid ==
				tableSelected.value[0].episodeid) {
				if (v.id == tableSelected.value[0].id) {
					list.push({
						name: v.entrust,
						rowid: i,
						first: 1
					})
				} else {
					list.push({
						name: v.entrust,
						rowid: i,
						first: 0
					})
				}
			}
		})
		if (list.length >= 2) {
			loading.value = true
			CheckEntrstItemGroup({
				items: list
			}).then(res => {
				loading.value = false
				if (res.status) {
					let group = res.data.group
					if (group.length > 1000000000) {
						ItemGroupShow.value = true;
						ItemGroup.value = group
					} else {
						SelectClear();
						let d = []
						group[0].forEach((vv, ii) => {
							d.push(tableData.value[vv.rowid])
						})
						autoSeleted(d)
					}
				} else {
					ElMessage.error(res.msg)
				}
			})
		}
	}
	const ClickGroup = (group) => { //点击弹出框选择可一起预约的分组
		SelectClear();
		let d = []
		group.forEach((v, i) => {
			d.push(tableData.value[v.rowid])
		})
		autoSeleted(d)
		ItemGroupShow.value = false
	}
	
	let selectedUrl = ref('')
	let fileUrl = import.meta.env.VITE_APP_FILE
	let iframe_show = ref(false)

	const openIframe = (type) => {
		console.log(tableSelected.value)
		let entrustids=[]//勾选的检查项目entrustid
		do_type.value = type
		console.log(tableSelected.value);
		if (tableSelected.value.length === 0) {
			ElMessage.error('请勾选1条记录')
			return false
		}
		//tableSelected.value[0].entrust_id
		let next=true
		tableSelected.value.forEach((v,i)=>{
			if(type==1 && v.list_status!=0){
				ElMessage.error(v.entrust+" 不可进行预约操作")
				next=false
			}
			if(type==2 && v.list_status!=1){
				ElMessage.error(v.entrust+" 不可进行改约操作")
				next=false
			}
			entrustids.push(v.entrust_id)
		})
		if(next==false) return false
		
		YuYueKey.value++
		//打开jquery版
		//iframe_show.value = true
		//selectedUrl.value = fileUrl + '/jq_page/appointment.html?' + encodeURIComponent('regnum=' + tableSelected
		//	.value[0].reg_num + '&entrustid=' + entrustids + '&episodeid=' + tableSelected
		//	.value[0].episodeid + '&dotype=' + do_type.value + '&appointment_type=4') //appointment_type=4为护士
		
		//打开 vue版
		entrust_ids.value=entrustids.join(',')
		YuYueVueDialogVisible.value=true
		selectedUrl.value = fileUrl + '/jq_page/appointment.html?' + 'regnum=' + encodeURIComponent(tableSelected
			.value[0].reg_num) + '&entrustid=' + encodeURIComponent(entrustids) + '&episodeid=' + encodeURIComponent(tableSelected
			.value[0].episodeid) + '&dotype=' + do_type.value + '&appointment_type=4' //appointment_type=4为护士
		console.log(selectedUrl.value)


	}
	const dialogopened = () => {
		nextTick(() => {
			const oIframe = document.getElementById('bdIframe')
			// const deviceWidth = document.documentElement.clientWidth
			const deviceHeight = document.getElementsByClassName('el-dialog')[0].clientHeight
			// oIframe.style.width = (Number(deviceWidth) - 50) + 'px' //数字是页面布局宽度差值
			oIframe.style.height = (deviceHeight - 105) + 'px' //数字是页面布局高度差
		})

	}
	
	const cancel = () => {
	    // 1. 基础校验：必须勾选记录
	    if (tableSelected.value.length === 0) {
	        ElMessage.error('请勾选1条记录')
	        return false
	    }
	
	    // 2. 状态校验：检查所有选中项的状态
	    let next = true
	    tableSelected.value.forEach((v) => {
	        if (v.list_status != 1) {
	            ElMessage.error(`${v.entrus	} 无需取消`)
	            next = false
	        }
	    })
	    if (!next) return false
	
	    // 【新增】控制变量：1=密码框，2=确认框
	    // 实际使用时，这个值可能来自 props、路由参数或业务逻辑判断
	
	
	    loading.value = true; // 可选：如果在弹窗前就需要加载状态，否则移到 then 内部
	
	    // 定义一个处理成功后的统一函数，避免代码重复
	    const handleSuccessAction = (password) => {
	        CancelYuYue({
	            MainListId: tableSelected.value[0].id,
	            reg_num: tableSelected.value[0].reg_num,
	            do_user: loginUserinfo.value.id,
	            password: password, // 如果是确认框，这里传空字符串或特定标识
	        }).then(res => {
	            loading.value = false
	            if (res.status) {
	                ElMessage({
	                    message: res.msg,
	                    type: 'success',
	                })
	                GetList()
	            } else {
	                ElMessage.error(res.msg)
	            }
	        }).catch(err => {
	             loading.value = false
	             console.error(err)
	        })
	    }
	
	    // 3. 根据变量决定弹窗类型
	    if (loginType.value === 'SysLogin') {
	        // 模式 1: 密码输入框
	        ElMessageBox.prompt('请输入登录密码后再操作', '提示', {
	            confirmButtonText: '确定',
	            cancelButtonText: '取消',
	            inputType: 'password',
	            inputPattern: /.+/, // 简单校验不能为空
	            inputErrorMessage: '密码不能为空'
	        })
	        .then(({ value }) => {
	            handleSuccessAction(value)
	        })
	        .catch(() => {
	            loading.value = false
	        })
	
	    } else if (loginType.value === 'HisLogin' || loginType.value === 'CasLogin') {
	        // 模式 2: 确认框
	        ElMessageBox.confirm('确定要执行取消操作吗？', '提示', {
	            confirmButtonText: '确定',
	            cancelButtonText: '取消',
	            type: 'warning'
	        })
	        .then(() => {
	            handleSuccessAction('noPassword') 
	        })
	        .catch(() => {
	            loading.value = false
	        })
	    } else {
	        loading.value = false
	        ElMessage.error('未知的操作类型配置')
	    }
	}
	//获取可用服务组
	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 enableResourceList = ref([])
	const getEnableResource = () => {
		loading.value = true
		DepartmentResourceGetEnableList().then(res => {
			loading.value = false
			if (res.status) {
				enableResourceList.value = res.data
			} else {
				//ElMessage.error(res.msg)
			}

		})
	}
	//获取服务器时间
	const GetServiceDate = () => {
		GetServiceDateTime().then(res => {
			if (res.status) {
				let datetime = res.data.datetime.substr(0, 10)
				searchInfo.value.dateRange = [datetime, datetime]
				GetList()
			}
		})
	}
	//查看日志
	let LogShow = ref(false);
	let LogList = ref(null);
	let LogDataShow = ref(false);
	const showLog = (row) => {
		LogShow.value = true
		GetLoglist({
			id: row.id
		}).then(res => {
			if (res.status) {
				LogList.value = res.data
			}
		})
	}
	let LogDataJson = ref('');
	const showLogJson = (data) => {
		LogDataShow.value = true
		LogDataJson.value = data
	}
	let loginUserinfo=ref(null);
	
	
	//打印申请单
	const print_shenqingdan=()=>{
		if(tableSelected.value.length !==1){
			ElMessage.error('请选择1项进行打印')
			return
		}
		const row = tableSelected.value[0]
		if (row.list_status != 1) {
			ElMessage.error(row.entrust + ' 不可打印，请重新选择')
			return
		}
		const params = 'OrderNoList[]=' + row.entrust_id
		const url = import.meta.env.VITE_APP_API + 'GetCheckPdf?Dev=1&Type=single&' + params
		fetch(url)
			.then(res => res.blob())
			.then(blob => {
				const blobUrl = URL.createObjectURL(blob)
				const iframe = document.createElement('iframe')
				iframe.style.display = 'none'
				iframe.src = blobUrl
				iframe.onload = () => {
					iframe.contentWindow.print()
					URL.revokeObjectURL(blobUrl)
				}
				document.body.appendChild(iframe)
			})
	}
	// 批量打印申请单
	let batchPrintDialogVisible = ref(false)
	let batchPrintSelected = ref([])
	let batchPrintTableRef = ref(null)
	
	const batchPrint = () => {
		const printable = tableData.value.filter(v => v.list_status === 1)
		if (printable.length === 0) {
			ElMessage.info('当前列表中没有可打印的已预约项目')
			return
		}
		batchPrintDialogVisible.value = true
	}
	
	const handleBatchSelectionChange = (selection) => {
		batchPrintSelected.value = selection
	}
	
	const confirmBatchPrint = () => {
		if (batchPrintSelected.value.length === 0) {
			ElMessage.error('请选择至少1项进行打印')
			return
		}
		const params = batchPrintSelected.value
			.map(v => 'OrderNoList[]=' + v.entrust_id)
			.join('&')
		const url = import.meta.env.VITE_APP_API + 'GetCheckPdf?Dev=1&Type=group&' + params
		fetch(url)
			.then(res => res.blob())
			.then(blob => {
				const blobUrl = URL.createObjectURL(blob)
				const iframe = document.createElement('iframe')
				iframe.style.display = 'none'
				iframe.src = blobUrl
				iframe.onload = () => {
					iframe.contentWindow.print()
					URL.revokeObjectURL(blobUrl)
				}
				document.body.appendChild(iframe)
				batchPrintDialogVisible.value = false
			})
	}
	const closeYuYueDialog=()=>{
		GetList()
	}
	//签到
	let TiShiShow=ref(false);
	let successItem=ref([]);
	let failItem=ref([]);
	const SignInFunc=()=>{
		if (tableSelected.value.length === 0) {
			ElMessage.error('请勾选1条记录')
			return false
		}
		let ids=[];
		tableSelected.value.forEach((v,i)=>{
			ids.push(v.id)
		})
		loading.value=true;
		SignIn({
			MainListIds:ids
		}).then(res => {
			loading.value=false
			if (res.status) {
				 if(res.data.success.length==ids.length){
					 ElMessage({
					 	message: "签到成功",
					 	type: 'success',
					 })
					 TiShiShow.value=true
					 successItem.value=res.data.success
					 failItem.value=res.data.fail
				 }else{
					 TiShiShow.value=true
					 successItem.value=res.data.success
					 failItem.value=res.data.fail
				 }
				 GetList()
			}else{
				ElMessage.error(res.msg)
			} 
		})
	}
	//取消报到
	const CancelSignFunc=()=>{
		if (tableSelected.value.length === 0) {
			ElMessage.error('请勾选1条记录')
			return false
		}
		let ids=[];
		tableSelected.value.forEach((v,i)=>{
			ids.push(v.id)
		})
		loading.value=true;
		CancelSign({
			MainListIds:ids
		}).then(res => {
			loading.value=false
			if (res.status) {
				 if(res.data.success.length==ids.length){
					 ElMessage({
					 	message: "取消成功",
					 	type: 'success',
					 })
				 }else{
					 TiShiShow.value=true
					 successItem.value=res.data.success
					 failItem.value=res.data.fail
				 }
				 GetList()
			}else{
				ElMessage.error(res.msg)
			} 
		})
	}
	const getStorageData=()=>{
		if(sessionStorage.getItem("LoginUserInfo")){
			loginUserinfo.value=JSON.parse(sessionStorage.getItem("LoginUserInfo"))
		}
		if(loginUserinfo.value && loginUserinfo.value.group!=2){
			getEnableResource()
		}
		//如果是医生，默认填入搜索医生
		if((loginUserinfo.value && loginUserinfo.value.group==7) || loginType.value==='HisLogin'){
			searchInfo.value.doctor=loginUserinfo.value.cn_name
			//填入默认查询体检人
			let default_reg_num=sessionStorage.getItem("default_reg_num")
			if(default_reg_num && default_reg_num!='null' && default_reg_num!=''){
				searchInfo.value.reg_num=default_reg_num
			}
		}
		// 如果 type=doctor，默认日期筛选为同时生效
		if (route.query.type === 'doctor') {
			searchInfo.value.dateType = 'both';
		}
	}
	onMounted(() => {
		loginType.value=sessionStorage.getItem('LoginType')
		GetEnableDeviceListFunc()
		if(pinia.baseInfoStatus){
			getStorageData()
			GetServiceDate()
		}else{
			const unwatch = watch(
			  () => pinia.baseInfoStatus,
			  (newVal) => {
			    if (newVal) {
					console.log(newVal)
					console.log('66666',loginUserinfo.value)
		 
				  getStorageData() 
				  GetServiceDate()
			      unwatch(); // 停止监听
			    }
			  }
			);
		}
		
		 

	})
</script>

<style >
	.iframe {
		border: 0px;
		width: 100%;
		height: 100%;
		margin-top: -20px;
	}

	.iframeDialog {
		margin-top: 40px;
		height: 90%;
		/* 设置iframe高度 */
		width: 90%;
		/* 设置iframe宽度 */
		overflow: auto;
	}

	#tablelist .el-checkbox[aria-label="选择所有行"] {
		display: none;
	}

	.batch-print-table .el-checkbox[aria-label="选择所有行"] {
		display: inline-flex;
	}

	.el-dialog.is-fullscreen {
		display: flex;
		flex-direction: column;
	}

	.el-dialog.is-fullscreen .el-dialog__body {
		flex: 1;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	
</style>
<style scoped>
	.dialogitem {
		cursor: pointer;
		;
		display: flex;
		border-left: 1px solid #ccc;
		border-right: 1px solid #ccc;
		border-bottom: 1px solid #ccc;
	}
	
	.dialogitem:hover {
		background-color: darkcyan;
		color: #fff;
	}
</style>