<template>
	<div v-loading="loading">
		<el-dialog title="预约列表" class="iframeDialog" v-model="iframe_show" @opened="dialogopened" @closed="closeIfram()">
			<iframe id="bdIframe" :src="selectedUrl" class="iframe" :key="iframeKey" scrolling="auto"></iframe>
		</el-dialog>
		<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 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 v-if="loginUserinfo && loginUserinfo.group!=2">
						<el-select :filterable="true" clearable v-model="searchInfo.services_group" 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-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.apply_department" placeholder="申请科室"
						style="width: 200px;margin-left: 8px;" />
				</el-form-item>
				<el-form-item>
					<el-input v-model="searchInfo.doctor" 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 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-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" />
			<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="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="department_resources_name" label="预约资源" width="120" />
			<el-table-column prop="user_phone" label="电话" width="120" />
			<!-- <el-table-column prop="implement_department" 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="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>
		<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>
		<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>
		<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.entrust}}<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>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick
	} from 'vue'

	import {
		GetMainList,
		CancelYuYue,
		GetEnableDeviceList,
		DepartmentResourceGetEnableList,
		GetServiceDateTime,
		GetLoglist,
		CheckEntrstItemGroup,getMainDetail,SignIn,CancelSign
	} from '@/api/api.js'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	let AutoGroup=ref(true);//自动分组是否开启
	let shenqingdan_show=ref(false);
	let do_type = ref(0) //按钮操作类型1预约2改约
	let loading = ref(false)
	let searchInfo = ref({
		dateRange: [],
		list_status: null,
		patient_type: null,
		resources: [],
		services_group: null,
		reg_num: null,
		user_name: null
	})
	//获取检查项目列表
	let tableData = ref([])
	let tableref = ref(null)
	let currentPage = ref(1) //当前页码
	let pageSize = ref(15) //每页数量
	let total = 0 //总数量
	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) => {
		//console.log('取消前：', tableSelected.value)
		let select_qian = tableSelected.value ? tableSelected.value.length : 0
		SelectClear();
	//	console.log(e)
		autoSeleted([e[e.length - 1]])
	//	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 = null
	}
	const autoSeleted = (rows) => {

		//	 tableref.value.toggleRowSelection(e[0], true)
		if (rows) {
			rows.forEach((row) => {
				tableref.value.toggleRowSelection(row, true)
			})
			tableSelected.value = rows
		} else {

			SelectClear()
		}
	}
	let ItemGroupShow = ref(false);
	let ItemGroup = ref(null);
	//查找同一个人同一个就诊号，当前页面 状态申请中的项目名称
	const FindMatchItem = () => {
		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 > 1) {
						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)
	let iframeKey = ref(0)

	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
		
		iframeKey.value++
		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为护士
		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 = () => {
		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(() => {

			})
	}
	//获取可用服务组
	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);
	
	if(sessionStorage.getItem("LoginUserInfo")){
		loginUserinfo.value=JSON.parse(sessionStorage.getItem("LoginUserInfo"))
	}
	//打印申请单
	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)
			}
		})
		
		
		
		
	}
	const closeIfram=()=>{
		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)
			} 
		})
	}
	onMounted(() => {
		if(loginUserinfo.value && loginUserinfo.value.group!=2){
			getEnableResource()
		}
		GetEnableDeviceListFunc()
		GetServiceDate()
		 

	})
</script>

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

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

	
</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>