<template>
	<div v-loading="loading">
		<div class="head">
			<el-row>
				<el-form-item>
					<el-tag class="ml-2" type="success" style="margin-right: 20px;">医嘱类别</el-tag>
					<el-select clearable :filterable="true" v-model="searchInfo.bigClass" @change="GetItemClassList()"
						placeholder="所有医嘱大类">
						<el-option v-for="(item, index) in BigClassList" :key="index" :label="item.item_class_name"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select :filterable="true" clearable v-model="searchInfo.smallClass" placeholder="所有医嘱小类"
						style="margin-left: 10px;">
						<el-option v-for="(item, index) in SmallClassList" :key="index" :label="item.item_class_name"
							:value="item.id" />
					</el-select>
				</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="GetItemList()" style="margin-left: 10px;">查询</el-button>
				<el-button type="warning" @click="GetHisItemClass()" style="margin-left: 10px; margin-left: 40px;">同步分类</el-button>
				<el-button type="warning" @click="GetHisCheckItem()" style="margin-left: 10px;">同步检查项目</el-button>
			</el-row>
		</div>
		<el-table :data="tableData" style="width: 100%;" row-key="id">
			<el-table-column prop="id" label="Id" width="100" v-if="false" />
			<el-table-column prop="item_name" label="检查项目名称" />
			<el-table-column prop="reservation_method_name" label="预约方式" />
			<el-table-column prop="limosis" label="要求空腹" width="100">
				<template #default="scope">
					<el-tag v-if="scope.row.limosis==1" class="ml-2" type="danger">是</el-tag>
					<el-tag v-if="scope.row.limosis==0" class="ml-2" type="success">否</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="check_notice" label="检查须知" />
			<el-table-column prop="check_time" label="检查时间" width="100" />
			<el-table-column prop="check_begin_time" label="开始预约时间" width="120" />
			<el-table-column prop="devicesInfo" label="关联服务组">
				<template #default="scope">
					<span v-for="(item,index) in scope.row.devicesInfo " :key="index">
						<el-tag v-if="item.status==1 && item.is_del==0" class="ml-2"
							type="success">{{item.device_name}}</el-tag>
						<el-tag v-if="item.status==0 || item.is_del==1" class="ml-2"
							type="danger">{{item.device_name}}</el-tag>
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="" label="医嘱关联服务组" width="150">
				<template #default="scope">
					<el-button size="small" @click="LinkDeviceClick(scope.row)">关联服务组</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="" label="操作" width="150">
				<template #default="scope">
					<el-button type="primary" @click="EditItem(scope.row)" size="small">修改</el-button>
					<el-button type="warning" @click="HuChi(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="DevicedialogVisible" title="关联服务组" width="40%">
			<div class="chuansuokuang">
				<el-transfer v-model="selectedDevice" :titles="['可选服务组', '已关联服务组']"
					:props="{ key: 'id',label: 'device_name'}" :data="deviceList" />
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="DevicedialogVisible = false">取消</el-button>
					<el-button type="primary" @click="SaveLinkDevice()">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="ItemDialogVisible" title="编辑项目" width="40%">
			<div class="row"><span class="title">医嘱名称：</span>{{selectedItemInfo.item_name}}</div>
			<div class="row"><span class="title">预约方式：</span>
				<!-- 	<el-select style=" width: 200px;" clearable
					v-model="selectedItemInfo.reservation_method" placeholder="预约方式">
					<el-option v-for="(item, index) in yuyueType" :key="index" :label="item.name" :value="item.id" />
				</el-select> -->
				<el-checkbox-group v-if="yuyueType" v-model="selectedItemInfo.reservation_method">
					<el-checkbox v-for="(item, index) in yuyueType" :label="item.id" :value="item.id"
						:key="index">{{item.name}}</el-checkbox>
				</el-checkbox-group>
			</div>
			<div class="row"><span class="title">空腹：</span><el-select :filterable="true" clearable
					v-model="selectedItemInfo.limosis" placeholder="是否空腹" style=" width: 100px;">
					<el-option label="否" :value="0" />
					<el-option label="是" :value="1" />
				</el-select>
			</div>

			<div class="row"><span class="title">检查时间：</span><el-input v-model="selectedItemInfo.check_time"
					placeholder="请输入此项检查的时长" style="width: 200px;" /></div>
			<div class="row"><span class="title">等待时间：</span><el-input v-model="selectedItemInfo.check_begin_time"
					placeholder="开医嘱后,等待时间" style="width: 200px;" />
				<div style="margin-left: 4px;">医嘱开具后，预约时间需在设定的等待期之后,单位分钟</div>
			</div>


			<div class="row"><span class="title">检查须知：</span><el-input v-model="selectedItemInfo.check_notice"
					type="textarea" placeholder="请输入检查须知" style="	width: 500px;" /></div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="ItemDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="SaveItemInfoFunc()">
						确定
					</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="HuChiDialogVisible" :title="'为 '+SelectedHuChiItemInfo.name+' 设置互斥'" width="80%">
			请输入想要与 <span style="font-weight: 900;font-size: 16px;">{{SelectedHuChiItemInfo.name}}</span> 互斥的项目名称

			<!-- <div v-if="itemHuChiList.length>0">
				<div class="row" v-for="(item,index) in itemHuChiList" :key="index">
						<div class="col">{{item.code1_item_name}}</div>
						<div class="col">{{item.code2_item_name}}</div>
						<div class="col" style="width: 150px;"><span v-if="item.time>0">互斥时间：{{item.time}}小时</span><span v-if="item.time==0">永久互斥</span></div>
						<el-button type="danger" style="margin-left: 8px;" @click="HuChi_Del(item.id)">解除</el-button>
				</div>
				
			</div> -->

			<div style="display: flex;margin-top: 20px;">
				
				<div style="width: 30%;border-right: 1px solid #ccc;padding:4px 20px;">
					<div  v-loading="HuChiLoading"
						style="border-bottom: 1px solid #ccc;padding-bottom: 12px;margin-bottom: 20px;">
						<div style="display: flex;margin-bottom: 8px;">
							<el-select clearable :filterable="true" v-model="HuChi_bigClass"
								@change="GetItemClassList('Dialog')" placeholder="所有医嘱大类">
								<el-option v-for="(item, index) in DialogBigClassList" :key="index"
									:label="item.item_class_name" :value="item.id" />
							</el-select>
						
							<el-select :filterable="true" clearable v-model="HuChi_smallClass" placeholder="所有医嘱小类" @change="HuChi_SearchItem()"
								style="margin-left: 10px;">
								<el-option v-for="(item, index) in DialogSmallClassList" :key="index" 
									:label="item.item_class_name" :value="item.id" />
							</el-select>
						</div>
						<div>
							<el-input v-model="HuChi_InputItem" placeholder="项目搜索" style="width: 200px;" />
							<el-button type="success" style="margin-left: 8px;" @click="HuChi_SearchItem()">查询</el-button>
						</div>
						
						
					</div>

					<div style="padding-left: 40px;max-height: 400px;overflow-y:scroll;">
						<el-checkbox-group v-model="HuChiCheckedItems" style="display: flex;flex-direction: column;">
							<el-checkbox v-for="(item1,index1) in HuChiSelectItemList" :key="index1"
								:label="item1.item_code">{{item1.item_name}}</el-checkbox>
						</el-checkbox-group>
					</div>
				</div>
				<div
					style="width: 100px;border-right: 1px solid #ccc;text-align: center;height:400px;line-height: 400px;">
					<el-button type="primary" :icon="ArrowRight" circle @click="AddHuChiItem()" />
				</div>
				<div style="width: 60%;padding-left: 20px;max-height: 450px;overflow-y:scroll;">
					<div style="color: #999;margin-bottom: 4px;font-size: 12px;">已经存在互斥项（{{itemHuChiList.length}}）</div>
					<table id="huchi_table" v-if="itemHuChiList.length>0">
						<tr v-for="(item,index) in itemHuChiList" :key="index">
							<td>{{item.code2_item_name}}</td>
							<td><el-input v-model="itemHuChiList[index].time" placeholder="时间,0为永久互斥"
									style="width: 150px;" /><span style="font-size: 12px;color:#bbb;"> 小时</span></td>
							<td>
								<span v-if="item.id" style="display: flex;">
									<el-button type="danger" style="margin-left: 8px;"
										@click="HuChi_Del(item.id)">解除</el-button>
									<el-button type="primary" style="margin-left: 8px;"
										@click="HuChi_Save(SelectedHuChiItemInfo.code,item.code2,itemHuChiList[index].time,item.id)">更新</el-button>
								</span>
								<span v-else style="display: flex;">
									<el-button type="success" style="margin-left: 8px;"
										@click="HuChi_Save(SelectedHuChiItemInfo.code,item.code2,itemHuChiList[index].time)">保存</el-button>
									<el-button style="margin-left: 8px;" @click="HuChi_YiChu(item)">移除</el-button>
								</span>
							</td>
						</tr>
					</table>
					<div v-else style="text-align: center;margin-top: 20px;color:#bbb;">
						-- 暂未设置互斥项 --
					</div>
				</div>
			</div>

		</el-dialog>
		<el-dialog v-model="HuChiSelectDialogVisible" :title="'为 '+SelectedHuChiItemInfo.name+' 设置互斥'" width="50%">
			<div v-loading="HuChiLoading">
				<span style="font-weight: 900;">设置互斥时间，单位小时，0为永久互斥</span>
				<div class="row" v-for="(item,index) in HuChiSelectItemList" :key="index">
					<div style="margin-right: 12px;">{{SelectedHuChiItemInfo.name}} </div>
					<el-icon>
						<DArrowLeft />
					</el-icon><el-icon>
						<DArrowRight />
					</el-icon>
					<div style="margin-left: 12px; width: 250px;">{{item.item_name}} </div>
					<el-input v-model="HuChi_InputTimeList[index]" placeholder="时间,0为永久互斥" style="width: 150px;" />
					<el-button type="danger" style="margin-left: 8px;"
						@click="HuChi_Save(SelectedHuChiItemInfo.code,item.item_code,HuChi_InputTimeList[index])">添加</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		GetCheckItemClassList,
		GetCheckItemList,
		GetEnableDeviceList,
		ItemBindDevice,
		GetYuYueTypes,
		SaveItemInfo,
		SetHuChi,
		DelHuChi,
		GetHuChiList,
		UpdateHisItemClass,
		updateHisCheckItem
	} from '@/api/api.js'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		ArrowRight
	} from '@element-plus/icons-vue'

	let loading = ref(false);
	let searchInfo = ref({
		bigClass: '',
		smallClass: '',
		name: '',

	})
	//选中的项目信息
	let selectedItemInfo = ref({
		id: null,
		item_name: '',
		limosis: '',
		reservation_method: '',
		check_time: '',
		check_begin_time: '',
		check_notice: ''
	})
	//获取检查项目类别list
	let BigClassList = ref([]);
	let SmallClassList = ref([]);
	let DialogBigClassList = ref([]);
	let DialogSmallClassList = ref([]);
	const GetItemClassList = (type='') => {
		let searchData={}
		searchData=  { ...searchInfo.value }
		if(type=='Dialog'){
			 searchData.bigClass=HuChi_bigClass.value
		}
		loading.value = true
		GetCheckItemClassList({
			searchInfo: searchData
		}).then(res => {
			loading.value = false
			if (res.status) {
				if(type=='Dialog'){
					DialogBigClassList.value = res.data.bigClass
					DialogSmallClassList.value = res.data.smallClass
				}else{
					BigClassList.value = res.data.bigClass
					SmallClassList.value = res.data.smallClass
				}
				
				GetItemList()
			} else {
				ElMessage.error(res.msg)
			}

		})
	}

	//获取检查项目列表
	let tableData = ref([])
	let currentPage = ref(1) //当前页码
	let pageSize = ref(15) //每页数量
	let total = 0 //总数量
	const GetItemList = () => {
		loading.value = true
		GetCheckItemList({
			searchInfo: searchInfo.value,
			page: currentPage.value,
			pageSize: pageSize.value
		}).then(res => {
			loading.value = false
			if (res.status) {
				let list = res.data.list;
				// list.forEach(function(v,i){
				// 	if(v.reservation_method){
				// 		list[i].reservation_method=v.reservation_method.split(",")
				// 	}
				// })
				tableData.value = list
				total = res.data.count
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	const PageSizeChange = (e) => { // 修改每页数量
		pageSize.value = e
		GetItemList()
	}
	const PageCurrentChange = (e) => { //切换页码
		currentPage.value = e
		GetItemList()
	}

	let DevicedialogVisible = ref(false); //关联设备弹窗
	let ItemDialogVisible = ref(false); //编辑项目弹窗

	//点击打开设备穿梭框
	const LinkDeviceClick = (row) => {
		selectedDevice.value = []
		DevicedialogVisible.value = true
		selectedItemInfo.value.id = row.id
		row.devicesInfo.forEach(function(v, i) {
			deviceList.value.forEach(function(v2, i2) {
				if (v.id == v2.id) {
					selectedDevice.value.push(v.id)
				}

			})
		})
	}

	let selectedDevice = ref([]) //选中的设备
	const SaveLinkDevice = () => {
		ItemBindDevice({
			item_id: selectedItemInfo.value.id,
			device_ids: selectedDevice.value,
		}).then(res => {
			if (res.status) {
				DevicedialogVisible.value = false
				selectedDevice.value = []
				GetItemClassList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//获取可用设备列表
	let deviceList = ref([])
	const GetDeviceList = () => {
		GetEnableDeviceList({}).then(res => {
			if (res.status) {
				deviceList.value = res.data
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	//编辑项目
	const EditItem = (row) => {

		ItemDialogVisible.value = true
		selectedItemInfo.value.id = row.id
		selectedItemInfo.value.item_name = row.item_name
		selectedItemInfo.value.limosis = row.limosis
		selectedItemInfo.value.reservation_method = row.reservation_method
		selectedItemInfo.value.check_time = row.check_time
		if (row.check_begin_time == '' || row.check_begin_time == null) {
			row.check_begin_time = 0
		}
		selectedItemInfo.value.check_begin_time = row.check_begin_time
		selectedItemInfo.value.check_notice = row.check_notice
	}
	//获取预约方式类型
	let yuyueType = ref('')
	const GetyuYueTypeFunc = () => {
		GetYuYueTypes({}).then(res => {
			if (res.status) {
				yuyueType.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//保存项目信息
	const SaveItemInfoFunc = () => {
		SaveItemInfo({
			Info: selectedItemInfo.value
		}).then(res => {
			if (res.status) {
				ItemDialogVisible.value = false
				GetItemList()
			} else {
				ElMessage.error(res.msg)
			}
		})
	}
	let HuChiDialogVisible = ref(false);
	let HuChi_InputItem = ref('');
	let HuChi_smallClass=ref(null);
	let HuChi_bigClass=ref(null)
	let HuChiSelectItemList = ref(null)
	let HuChiSelectDialogVisible = ref(false);
	let HuChi_InputTimeList = ref([]); //设置互斥时间
	let HuChiLoading = ref(false);
	let HuChiCheckedItems = ref([]); //左侧勾选的检查项目
	let SelectedHuChiItemInfo = ref({
		code: '',
		name: ''
	})
	const HuChi = (row) => {
		HuChiDialogVisible.value = true
		SelectedHuChiItemInfo.value.name = row.item_name
		SelectedHuChiItemInfo.value.code = row.item_code
		HuChiSelectItemList.value = [];
		HuChi_InputItem.value = '';
		GetItemClassList('Dialog')
		HuChiList()
	}
	const HuChi_SearchItem = () => {
		 
		HuChiLoading.value = true
		HuChi_InputTimeList.value = [];
		GetCheckItemList({
			searchInfo: {
				name: HuChi_InputItem.value,
				bigClass: HuChi_bigClass.value,
				smallClass: HuChi_smallClass.value
			},
			page: 1,
			pageSize: 100
		}).then(res => {
			HuChiLoading.value = false
			if (res.status) {
				if (res.data.list.length > 0) {
					HuChiSelectItemList.value = res.data.list
				} else {
					ElMessage.error('未找到相关项目')
				}

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

		})
	}
	//向右侧添加项目
	const AddHuChiItem = () => {
		console.log(HuChiCheckedItems.value);
		//HuChiSelectItemList.value
		let newArr = [];
		let removedArr = [];
		//检测右侧是否有将要移入的项目
		let enable = true
		itemHuChiList.value.forEach(function(v, i) {
			HuChiCheckedItems.value.forEach(function(v2, i2) {
				if (v.code2 == v2) {
					ElMessage.error(v.code2_item_name + " 已经存在于右侧，不能重复添加")
					enable = false
				}
			})
		})
		if (!enable) return false;

		HuChiSelectItemList.value.forEach(item => {
			if (HuChiCheckedItems.value.includes(item.item_code)) {
				itemHuChiList.value.push({
					code2: item.item_code,
					code2_item_name: item.item_name
				}); // 如果id在要移除的id列表中，将该项添加到removedArr
			} else {
				newArr.push(item); // 否则，将该项添加到newArr
			}
		});
		HuChiSelectItemList.value = newArr;

		console.log(removedArr);
		console.log(itemHuChiList.value);
		HuChiCheckedItems.value = []
	}
	//移动回左侧
	const HuChi_YiChu = (y_item) => {
		itemHuChiList.value = itemHuChiList.value.filter(item => item.code2 != y_item.code2);
		if (!HuChiSelectItemList.value.find(item => item.item_code == y_item.code2)) {
			HuChiSelectItemList.value.push({
				item_code: y_item.code2,
				item_name: y_item.code2_item_name
			});
		}
	}
	//保存互斥设置
	const HuChi_Save = (code1, code2, time, id = 0) => {
		HuChiLoading.value = true
		SetHuChi({
			id: id,
			code1: code1,
			code2: code2,
			time: time
		}).then(res => {
			HuChiLoading.value = false
			if (res.status) {
				ElMessage({
					message: res.msg,
					type: 'success',
				})
				itemHuChiList.value.forEach(function(v, i) {
					if (v.code2 == res.data.code2) {
						console.log(333);
						itemHuChiList.value[i].id = res.data.id
					}
				})
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//获取项目已经设置的互相列表
	let itemHuChiList = ref([]);
	const HuChiList = () => {
		HuChiLoading.value = true
		GetHuChiList({
			code: SelectedHuChiItemInfo.value.code
		}).then(res => {
			HuChiLoading.value = false
			if (res.status) {
				itemHuChiList.value = res.data
			} else {
				ElMessage.error(res.msg)
			}

		})
	}
	//解除互斥
	const HuChi_Del = (id) => {
		ElMessageBox.confirm(
				'确定解除此项互斥关系吗？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				HuChiLoading.value = true
				DelHuChi({
					id: id
				}).then(res => {
					HuChiLoading.value = false
					if (res.status) {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						HuChiList();
					} else {
						ElMessage.error(res.msg)
					}

				})
			})

	}
	//同步his分类
	const GetHisItemClass=()=>{
		ElMessageBox.confirm(
				'确定从his同步分类吗？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				loading.value = true
				UpdateHisItemClass().then(res => {
					loading.value = false
					if (res.status) {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						GetItemClassList();
					} else {
						ElMessage.error(res.msg)
					}
		
				})
			})
	}
	//同步his检查项目
	const GetHisCheckItem=()=>{
		ElMessageBox.confirm(
				'确定从his同步检查项目吗？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				loading.value = true
				updateHisCheckItem({termClassId:155}).then(res => {
					loading.value = false
					if (res.status) {
						ElMessage({
							message: res.msg,
							type: 'success',
						})
						GetItemList();
					} else {
						ElMessage.error(res.msg)
					}
		
				})
			})
	}
	onMounted(() => {
		GetItemClassList()
		GetDeviceList()
		GetyuYueTypeFunc()
	})
</script>

<style scoped>
	.page {
		display: flex;
		justify-content: flex-end;
		margin-top: 10px;
	}

	.chuansuokuang {
		display: flex;
		justify-content: center;
	}

	.row {
		display: flex;
		align-items: center;
		margin-left: 20px;
		margin-top: 12px;
	}

	.title {
		font-weight: 700;
		white-space: nowrap;
		width: 100px;
		text-align: left;
	}

	.col {
		border: 1px solid #ddd;
		padding: 4px;
		width: 400px;
	}

	#huchi_table {
		width: 100%;
		border: 1px solid #ccc;
		border-collapse: collapse;
	}

	#huchi_table tr {
		border: 1px solid #ccc;

	}

	#huchi_table td {
		border: 1px solid #ccc;
		padding: 4px 8px;

	}
</style>