<template>
	<div class="my_nav_box">
		<div class="deviceSelect3">
			<div class="deviceSelect deviceSelectbody" v-if="routePath.includes('/device')">
				<el-select size="small" v-model="deviceInfo.code" filterable @change="command" :placeholder="t('message.layout.选择机号')">
					<el-option v-for="item in devices" :key="item.code" :label="item.deviceNo" :value="item.code"> </el-option>
				</el-select>
			</div>
			<div class="deviceSelect" v-show="routePath.includes('/PatientManage')">
				<div class="deviceSelectbody2">
					<div style="">
						<el-select v-model="patientIsAlive" @change="changePat" style="width: 75px" class="m-2" placeholder="Select" size="small">
							<el-option :value="-1" :label="t('message.layout.全部')" />
							<el-option :value="1" :label="t('message.layout.留治')" />
							<el-option :value="2" :label="t('message.layout.转出')" />
						</el-select>
					</div>
					<div>
						<el-select size="small" v-model="patientInfo.code" :loading="selloading" filterable @change="commandPat" :placeholder="t('message.layout.选择患者')">
							<el-option v-for="item in patients" :key="item.code" :label="item.patientName + '(' + item.patientNamePy + ')'" :value="item.code">
							</el-option>
						</el-select>
					</div>
				</div>
			</div>
		</div>
		<div class="my_menu">
			<el-menu
				router
				:default-active="defaultActive"
				background-color="transparent"
				:collapse="isCollapse"
				:default-openeds="openeds"
				:unique-opened="getThemeConfig.isUniqueOpened"
				:collapse-transition="true"
			>
				<template v-for="val in menuLists">
					<el-sub-menu :index="val.path" v-if="val.children && val.children.length > 0" :key="val.path">
						<template #title>
							<SvgIcon :name="val.meta.icon" />
							<span>{{ $t(val.meta.title) }}</span>
						</template>
						<SubItem :chil="val.children" />
					</el-sub-menu>
					<el-menu-item :index="val.path" :key="val.path" v-else>
						<SvgIcon :name="val.meta.icon" />
						<template #title v-if="!val.meta.isLink || (val.meta.isLink && val.meta.isIframe)">
							<span>{{ $t(val.meta.title) }}</span>
						</template>
						<template #title v-else>
							<a :href="val.meta.isLink" target="_blank" rel="opener">{{ $t(val.meta.title) }}</a>
						</template>
					</el-menu-item>
				</template>
			</el-menu>
		</div>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, computed, defineComponent, getCurrentInstance, onMounted, watch, ref } from 'vue';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import { useStore } from '/@/store/index';
import { list as getDevices } from '/@/api/device/index';
import { QueryList } from '/@/api/HemodiPatients/index';
import SubItem from '/@/layout/navMenu/subItem.vue';
import { Session, Local } from '/@/utils/storage';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
export default defineComponent({
	name: 'navMenuVertical',
	components: { SubItem },
	props: {
		menuList: {
			type: Array,
			default: () => [],
		},
	},
	setup(props) {
		const { t } = useI18n();
		const { proxy } = getCurrentInstance() as any;
		const store = useStore();
		const route = useRoute();

		const state = reactive({
			selloading: false,
			// 修复：https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
			defaultActive: route.meta.isDynamic ? route.meta.isDynamicPath : route.path,
			isCollapse: false,
			selectText: '选择设备',
			devices: [],
			patients: [],
			loadingel: false,
			openeds: ['/device/index'],
		});
		const patientIsAlive = computed(() => {
			return store.state.userInfos.patientIsAlive;
		});
		// 获取父级菜单数据
		const menuLists = computed(() => {
			return props.menuList;
		});
		// 获取布局配置信息
		const getThemeConfig = computed(() => {
			return store.state.themeConfig.themeConfig;
		});
		// 获取设备信息
		const deviceInfos = computed(() => {
			return store.state.deviceInfos.deviceInfos;
		});
		// 菜单高亮（详情时，父级高亮）
		const setParentHighlight = (currentRoute) => {
			const { path, meta } = currentRoute;
			const pathSplit = meta.isDynamic ? meta.isDynamicPath.split('/') : path.split('/');
			if (pathSplit.length >= 4 && meta.isHide) return pathSplit.splice(0, 3).join('/');
			else return path;
		};
		// 点击下拉刷新设备列表
		const visibleChange = (vis: any) => {
			console.log(vis);
		};

		const routePath = computed(() => {
			return route.path;
		});
		// 选定设备到vuex
		const command = (item: any) => {
			// state.devices.forEach(element => {
			// 	if(element.code===item){
			// 		var dev={
			// 			"clientCode": element.clientCode,
			// 			"code": element.code,
			// 			"deviceBrand": element.deviceBrand,
			// 			"deviceCurrentState": element.deviceCurrentState,
			// 			"deviceGroupCode": element.deviceGroupCode,
			// 			"deviceInitialRunCount": element.deviceInitialRunCount,
			// 			"deviceModel": element.deviceModel,
			// 			"deviceName": element.deviceName,
			// 			"deviceNo": element.deviceNo,
			// 			"devicePurchaseTime": element.devicePurchaseTime,//购买日期
			// 			"deviceSn": element.deviceSn,
			// 			"deviceType": element.deviceType,
			// 			"id": element.id,
			// 			"remark": element.remark,
			// 			"deviceVsSchemes":element.deviceVsSchemes,
			// 			"sortOrder":element.sortOrder
			// 		}
			// 		store.dispatch('deviceInfos/setdeviceInfos',dev);
			// 	}
			// });
			const device = state.devices.find((e) => e.code === item);
			console.log(item, device);
			if (device) {
				store.dispatch('deviceInfos/setdeviceInfos', Object.assign({}, device));
			} else {
				ElMessage.warning('匹配设置失败，请重新选择');
			}
		};
		const commandPat = (item: any) => {
			console.log(item);
			state.patients.forEach((e) => {
				if (e.code === item) {
					const pa = {
						id: e.id,
						code: item,
						patientName: e.patientName,
						userGender: e.patientGender,
						patientHemoCode: e.patientHemoCode,
						age: e.age,
						patientIdentityNo: e.patientIdentityNo,
						patientAddress: e.patientAddress,
						patientTelNo: e.patientTelNo,
						birthday:e.birthday,
						// 性别
						patientGenderText: e.patientGenderText,
						// 透析总次数
						historyCount: e.historyCount,
						// 是否阳性传染病
						patientIsPositive: e.patientIsPositive,
						patientNo:e.patientNo,
						hisCode:e.hisCode,
					};
					Session.set('patientInfo', pa);
					Local.set('patientInfo', pa);
					store.dispatch('patientInfos/setpatientInfos', pa);
				}
			});
		};
		const changePat = (val) => {
			// 更新右侧患者列表
			store.commit('userInfos/SET_patientIsAlive', val);
		};
		// 设置菜单的收起/展开
		watch(
			store.state.themeConfig.themeConfig,
			() => {
				document.body.clientWidth <= 1000 ? (state.isCollapse = false) : (state.isCollapse = getThemeConfig.value.isCollapse);
			},
			{
				immediate: true,
			}
		);
		const deviceInfo = computed(() => {
			return store.state.deviceInfos.deviceInfos;
		});

		const patientInfo = computed(() => {
			return store.state.patientInfos.patientInfos;
		});
		watch(deviceInfo,()=>{
			var ps = new Object({
				page: 0,
				size: 0,
				wherecondition: `client_code='${store.state.userInfos.userInfos.client.code}'`,
				ordercondition: 'sort_order asc',
			});
			state.loadingel = true;
			getDevices(ps).then((re) => {
				state.devices = re.data.list;
				state.loadingel = false;
			});
		})
		watch(patientInfo, () => {
			patientList();
		});
		watch(patientIsAlive, () => {
			// 清除选中的患者
			const patientInfo = {
				// 患者code
				code: '',
				// 患者id
				id: 0,
				// 患者姓名
				patientName: '',
			};

			// 将患者信息写入vuex
			Session.set('patientInfo', patientInfo);
			Local.set('patientInfo', patientInfo);
			store.dispatch('patientInfos/setpatientInfos', patientInfo);
			patientList();
		});

		watch(() => store.state.userInfos.patientIsAliveTrigger, () => {
			patientList();
		})
	
		const patientList = () => {
			var ps2 = new Object({
				page: 0,
				size: 0,
				wherecondition: `client_code='${store.state.userInfos.userInfos.client.code}'`,
				ordercondition: 'patient_is_alive asc, id asc',
			});
			if (patientIsAlive.value !== -1) {
				ps2.wherecondition += ` and patient_is_alive='${patientIsAlive.value}'`;
			}
			state.selloading = true;
			QueryList(ps2)
				.then((re) => {
					// setTimeout(()=>{
					// 	state.patients=re.data.list
					// },5000)
          state.patients = re.data.list;
          store.state.patientInfos.patientList = re.data.list
				})
				.finally(() => {
					state.selloading = false;
				});
		};
		// 页面加载时
		onMounted(() => {
			state.defaultActive = setParentHighlight(route);
			var ps = new Object({
				page: 0,
				size: 0,
				wherecondition: `client_code='${store.state.userInfos.userInfos.client.code}'`,
				ordercondition: 'sort_order asc',
			});
			state.loadingel = true;
			getDevices(ps).then((re) => {
				console.log('00000');
				console.log(re);
				state.devices = re.data.list;
				state.loadingel = false;
			});
			patientList();
		});
		// 路由更新时
		onBeforeRouteUpdate((to) => {
			if (to.path == '/PatientManage/PatientList') {
				patientList();
			}
			// 修复：https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
			state.defaultActive = setParentHighlight(to);
			proxy.mittBus.emit('onMenuClick');
			const clientWidth = document.body.clientWidth;
			if (clientWidth < 1000) getThemeConfig.value.isCollapse = false;
		});
		return {
			menuLists,
			patientIsAlive,
			patientInfo,
			deviceInfo,
			commandPat,
			changePat,
			visibleChange,
			deviceInfos,
			command,
			getThemeConfig,
			routePath,
			...toRefs(state),
			t
		};
	},
});
</script>
<style lang="less">
.deviceSelectbody {
	padding-top: 10px;
}
.deviceSelect {
	text-align: center;
	width: 200px;
	height: 52px;
	background: #66b1ff;
	.deviceSelectbody {
		padding-top: 12px;
		// text-align: center;
		display: flex;
		justify-content: space-between;
		margin-left: 5px;

		width: 95%;
		.el-select .el-input {
			// padding-top: 10px;
			// border: #9FC8FF solid 1px;
			.el-input__inner {
				// background-color: #60A7FF;
				border-radius: 15px;
				font-size: 12px;
				height: 28px;
				padding-top: 0px;
				padding-bottom: 0px;
				// line-height: 28px;
			}
		}
	}
	.deviceSelectbody2 {
		padding-top: 10px;
		// text-align: center;
		display: flex;
		justify-content: space-between;
		margin-left: 2px;
		margin-right: 2px;
	}
	.el-dropdown {
		.el-dropdown--large {
			el-button {
				width: 210px;
			}
		}
	}
}
.my_nav_box {
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;
	.deviceSelect3 {
		flex: 0 0 auto;
	}
	.my_menu {
		flex: 1 1 auto;
		overflow-y: auto;
	}
}
</style>
