<template>
	<div>
		<el-dialog v-model="YuYueDialogVisible" width="100%" @close="YuYueDialogClose()">
			<YuYue style="margin-top: -30px;" :key="YuYueKey" :YuYueInfo="YuYueInfo"></YuYue>
		</el-dialog>
		<div class="head">
			<div class="head">
				<el-row>
					<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-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>
						<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-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-row style="margin: 0px 0px 8px 8px; border-top: 1px solid #ccc;padding-top: 8px">
			<el-button type="success" @click.prevent="openYuYue(1)">预 约</el-button>
			<el-button type="danger" @click="cancel()">取消预约</el-button>
			<el-button type="warning" @click="openYuYue(2)">更改预约时间</el-button>
			<!-- 	<el-button type="primary" @click="SignInFunc()" style="margin-left: 40px;">报到</el-button>
			<el-button type="danger" @click="CancelSignFunc()">取消报到</el-button> -->
			<el-button style="display: none;" ref="print_shenqingdan_button"
				v-print="'#shenqingdan'">打印申请单隐藏按钮</el-button>
			<el-button @click="print_shenqingdan()">打印申请单</el-button>
			<el-button v-print="'#tablelist'">打印表格</el-button>

			<el-checkbox-group v-model="Is_AutoDuoRen" style="margin-left: 12px;">
				<el-checkbox label="1">自动选择多人</el-checkbox>
			</el-checkbox-group>


		</el-row>
		<el-table :data="tableData" @select="TableSelectChange" id="tablelist" ref="tableref" style="width: 100%;" row-key="id"
			v-loading="loading">
			<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 prop="reg_num" label="登记号" width="100" />
			<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="devices" label="服务组">
				<template #default="scope">
					<div style="white-space: nowrap;">
						<span v-for="(item,index) in scope.row.devices" :key="index">
							{{ item.device_name+ ' ' }}
						</span>
					</div>
				</template>
			</el-table-column>
			<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="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>
		<div id="shenqingdan" v-if="shenqingdan_show">
			<div v-for="(item,index) in shenqingdan_list" :key="index">
				<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.maininfo.entrust}}</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import YuYue from '@/components/Yewu/YuYue.vue'
	import {
		GetMainList,
		CancelYuYue,
		GetServiceDateTime,
		CheckEntrstItemGroup,
		getMainDetail,GetLoglist 
	} 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 //总数量
	let YuYueKey = ref(0); //用于每次打开更新组件key,强制重新加载
	let tableref = ref(null)
	let tableSelected = ref([]);
	let Is_AutoDuoRen = ref([]); //是否自动勾选多人
	let shenqingdan_show = ref(false);
	const PageSizeChange = (e) => { // 修改每页数量
		pageSize.value = e
		GetList()
	}
	const PageCurrentChange = (e) => { //切换页码
		currentPage.value = e
		GetList()
	}

	const GetList = () => {
		tableSelected.value = []
		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)
			}
		})
	}

	let YuYueDialogVisible = ref(false); //打开预约对话框
	let YuYueInfo = ref({});
	const openYuYue = (type) => {
		if(tableSelected.value.length==0){
			ElMessage.error('请勾选项目')
			return false
		}
		if (type == 1) {
			if (!tableSelected.value.every(item => item.list_status === 0)) {
				ElMessage.error('当前勾选项目，不能预约')
				return false
			}
		}
		if (type == 2) {
			if (!tableSelected.value.every(item => item.list_status === 1)) {
				ElMessage.error('当前勾选项目，不能改约预约')
				return false
			}
		}
		YuYueInfo.value.entrustInfo = mergeByRegNum(tableSelected.value)
		YuYueKey.value++;
		YuYueInfo.value.dotype = type //预约类型1预约2改约
		YuYueInfo.value.appointment_type = 4 //预约渠道id 4护士站
		YuYueDialogVisible.value = true;
	}
	//取消预约
	const cancel = () => {
		if (tableSelected.value.length === 0) {
			ElMessage.error('请勾选1条记录')
			return false
		}
		let next = true
		tableSelected.value.forEach((v, i) => {
			if (v.list_status != 1) {
				ElMessage.error(v.entrust + " 无需取消")
				next = false
			}
		})
		if (next == false) return false
		ElMessageBox.prompt('请输入登录密码后再操作', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputType: 'password'
			})
			.then(({
				value
			}) => {
				loading.value = true
				CancelYuYue({
					MainListId: tableSelected.value[0].id,
					reg_num: tableSelected.value[0].reg_num,
					password: value
				}).then(res => {
					loading.value = false
					if (res.status) {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						GetList()
					} else {
						ElMessage.error(res.msg)
					}

				})
			})
			.catch(() => {

			})
	}
	//勾选表格记录
	const TableSelectChange = (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)
		if (select_qian > tableSelected.value.length) {

		} else {
			if (Is_AutoDuoRen.value.length == 0) { //单人多项目
				FindPersonMatchItem()
			}
			if (Is_AutoDuoRen.value.length == 1) { //多人单项目
				FindAllMatchItem()
			}
		}
	}
	//清空所有
	const SelectClear = () => {
		tableref.value.clearSelection()
		tableSelected.value = []
	}
	const autoSeleted = (rows) => {
		if (rows) {
			rows.forEach((row) => {
				if (row != undefined) {
					tableref.value.toggleRowSelection(row, true)
				}
			})
			tableSelected.value = rows
		} else {
			SelectClear()
		}
	}

	//查找多个人可同时预约的项目
	const FindAllMatchItem = () => {
		console.log(tableSelected.value)
		tableSelected.value.reverse();
		let temp_reg_num = ''
		let chongzhi = false;
		let list = []
		if (tableSelected.value[0].list_status != 0) return false //如果勾选的不是申请中的医嘱则不进行匹配

		tableData.value.forEach((v, i) => {
			if (v.list_status == 0) {
				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 > 1) {
						ItemGroupShow.value = true;
						ItemGroup.value = group
					} else {
						SelectClear();
						let d = []
						group[0].forEach((vv, ii) => {
							vv.rowid.forEach((v3, i3) => {
								d.push(tableData.value[v3])
							})
						})
						autoSeleted(d)
					}
				} else {
					ElMessage.error(res.msg)
				}
			})
		}
	}

	let ItemGroupShow = ref(false);
	let ItemGroup = ref(null);
	//查找同一个人同一个就诊号，当前页面 状态申请中的项目名称
	const FindPersonMatchItem = () => {

		console.log('开始匹配个人项目')
		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 > 10000000) {
						ItemGroupShow.value = true;
						ItemGroup.value = group
					} else {
						SelectClear();
						let d = []
						group[0].forEach((vv, ii) => {
							vv.rowid.forEach((v3, i3) => {
								d.push(tableData.value[v3])
							})

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


	function mergeByRegNum(items) {
		return items.reduce((acc, item) => {
			const existingItem = acc.find(i => i.reg_num === item.reg_num);

			if (existingItem) {
				// 如果找到了相同的reg_num，则添加当前id到ids数组中
				existingItem.entrustid.push(item.entrust_id);
			} else {
				// 如果没有找到相同的reg_num，则创建一个新的条目
				acc.push({
					entrustid: [item.entrust_id],
					reg_num: item.reg_num,
					episodeid: item.episodeid
				});
			}

			return acc;
		}, []);
	}
	const YuYueDialogClose = () => {
		GetList()
	}
	//获取服务器时间
	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 print_shenqingdan_button = ref(null);
	let shenqingdan_list = ref([])
	const print_shenqingdan = () => {
		if (tableSelected.value.length !== 1) {
			ElMessage.error('请选择1项进行打印')
			return false
		}

		getMainDetail({
			regnum: tableSelected.value[0].reg_num,
			entrustid: tableSelected.value[0].entrust_id,
			episodeid: tableSelected.value[0].episodeid,
			appointment_type: 4
		}).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(() => {
		GetServiceDate()
	})
</script>

<style scoped>
	.head {
		margin: 10px auto;
	}
</style>