<template>
	<!--  :style="{ flex: layoutUserFlexNum }" -->
	<div class="layout-navbars-breadcrumb-user pr15">
<!--		 <el-dropdown :show-timeout="70" :hide-timeout="50" trigger="click" @command="onComponentSizeChange">
			<div class="layout-navbars-breadcrumb-user-icon mr10"  title="组件大小">
				<i class="iconfont icon-ziti"></i>
			</div>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item command="large" :disabled="state.disabledSize === 'large'">大型</el-dropdown-item>
					<el-dropdown-item command="default" :disabled="state.disabledSize === 'default'">默认</el-dropdown-item>
					<el-dropdown-item command="small" :disabled="state.disabledSize === 'small'">小型</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		<div class="layout-navbars-breadcrumb-user-icon mr10" @click="onSearchClick"  title="菜单搜索">
			<el-icon>
				<ele-Search />
			</el-icon>
		</div>
		<div class="layout-navbars-breadcrumb-user-icon mr10" @click="onLayoutSetingClick" title="布局配置">
			<i class="icon-skin iconfont"></i>
		</div>-->
		 <div class="layout-navbars-breadcrumb-user-icon mr10" title="消息">
			<el-popover placement="bottom" trigger="click" transition="el-zoom-in-top" :width="300" :persistent="false">
				<template #reference>
					<el-badge :value="messageCount" :max="99" :hidden="messageHidden">
            <SvgIcon name="ele-Bell" size="18px"/>
					</el-badge>
				</template>
				<template #default>
					<UserNews @onAllReadClick="onAllReadClick"/>
				</template>
			</el-popover>
		</div>
		 <div class="layout-navbars-breadcrumb-user-icon mr10" @click="onLockScreen" title="锁屏">
       <SvgIcon name="ele-Lock" size="18px"/>
		</div>
<!--		<div class="layout-navbars-breadcrumb-user-icon mr10" @click="onScreenfullClick" :title="isScreenfull ? '关全屏' : '开全屏'" >
			<i class="iconfont" :class="!isScreenfull ? 'icon-quanping1' : 'icon-tuichuquanping'"></i>
		</div>-->
		<el-dropdown :show-timeout="70" :hide-timeout="50" @command="onHandleCommandClick">
			<div class="layout-navbars-breadcrumb-user-link" :title="userInfos.name">
				<div class="layout-navbars-breadcrumb-user-link-photoBox">
					<el-avatar :src="userInfos.photo" :size="24" class="layout-navbars-breadcrumb-user-link-photo">
						<SvgIcon name="ele-UserFilled" color="var(--el-color-primary)" />
					</el-avatar>
          <span class="text-no-wrap layout-navbars-breadcrumb-user-link-photoBox-name">{{ userInfos.name ? userInfos.name : '' }}</span>
          <SvgIcon name="ele-ArrowDown" class="ml3"/>
				</div>

			</div>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item command="/home"> <SvgIcon name="ele-House" /> 首页 </el-dropdown-item>
					<el-dropdown-item divided command="setting" v-if="showSetting"> <SvgIcon name="ele-Setting" />系统设置 </el-dropdown-item>
					<el-dropdown-item divided command="search"> <SvgIcon name="ele-Search" /> 搜索菜单 </el-dropdown-item>
					<el-dropdown-item divided command="changePwd"> <SvgIcon name="ele-Lock" /> 修改密码 </el-dropdown-item>
					<el-dropdown-item divided command="logOut"> <SvgIcon name="ele-SwitchButton" />退出 </el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		<Search ref="searchRef" />

		<!-- 锁频 -->
		<el-dialog v-model="dialogVisible" width="400px" draggable title="锁屏">
			<el-form :model="state.ruleForm" ref="ruleFormRef" @submit.native.prevent>
				<el-form-item label="锁屏密码" prop="pwd" :rules="[{ required: true, message: '请输入锁屏密码', trigger: 'blur' }]">
					<el-input show-password placeholder="请输入密码" v-model="state.ruleForm.pwd" @keyup.enter="confirmLock(ruleFormRef)">
						<template #prefix>
							<el-icon class="el-input__icon">
								<ele-Unlock />
							</el-icon>
						</template>
					</el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="confirmLock(ruleFormRef)">确 定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 修改密码 -->
		<el-dialog v-model="showDutyDialog" draggable title="修改密码" width="500px">
			<el-form :model="state.dutyForm" label-width="80px" :rules="rules" ref="dutyFormRef">
				<el-form-item prop="currentPassword" label="旧密码" class="mb30">
					<el-input
						class="inputDeep"
						clearable
						show-password
						placeholder="请输旧就密码"
						v-model="state.dutyForm.currentPassword"
						autocomplete="off"
					>
						<template #prefix>
							<el-icon class="el-input__icon">
								<ele-Unlock />
							</el-icon>
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="新密码" prop="newPassword" class="mb30">
					<el-input
						class="inputDeep"
						clearable
						show-password
						placeholder="请输入新密码"
						v-model="state.dutyForm.newPassword"
						autocomplete="off"
					>
						<template #prefix>
							<el-icon class="el-input__icon">
								<ele-Unlock />
							</el-icon>
						</template>
					</el-input>
					<div class="intensity">
						<span class="psdText">密码强度：{{ modes === 1 ? '弱' : modes === 2 ? '中' : modes === 3 ? '强' : '' }}</span>
						<span class="line ruo" :class="modes === 1 ? 'low' : ''"></span>
						<span class="line zhong" :class="modes === 2 ? 'middle' : ''"></span>
						<span class="line qiang" :class="modes === 3 ? 'high' : ''"></span>
					</div>
				</el-form-item>
				<el-form-item prop="confirmPassword" label="确认密码">
					<el-input
						class="inputDeep"
						clearable
						type="password"
						show-password
						placeholder="请再次输入密码"
						v-model="state.dutyForm.confirmPassword"
						autocomplete="off"
					>
						<template #prefix>
							<el-icon class="el-input__icon">
								<ele-Unlock />
							</el-icon>
						</template>
					</el-input>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showDutyDialog = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="save(dutyFormRef)" :loading="loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="layoutBreadcrumbUser">
import { defineAsyncComponent, ref, computed, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage, ElNotification, FormInstance } from 'element-plus';
import screenfull from 'screenfull';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { useTelStatus } from '/@/stores/telStatus';
import { useThemeConfig } from '/@/stores/themeConfig';
import {Session, Local, Cookie} from '/@/utils/storage';
import mittBus from '/@/utils/mitt';
import { VoiceInterfaceObject } from '/@/utils/PhoneScript';
import { changePwd } from '/@/api/login/user';

// 引入组件
const UserNews = defineAsyncComponent(() => import('/@/layout/navBars/breadcrumb/userNews.vue'));
const Search = defineAsyncComponent(() => import('/@/layout/navBars/breadcrumb/search.vue'));

const router = useRouter();
const stores = useUserInfo();
const storesThemeConfig = useThemeConfig();
const { userInfos } = storeToRefs(stores);
const { themeConfig } = storeToRefs(storesThemeConfig);
const usetelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(usetelStatusStore);
const searchRef = ref<RefType>();
const state = reactive({
	isScreenfull: false,
	disabledI18n: 'zh-cn',
	disabledSize: 'large',
	dutyForm: {
		currentPassword: '',
		newPassword: '',
		confirmPassword: '',
	},
	ruleForm: {
		pwd: '', // 锁频密码
	},
});
const messageCount = ref<number>(2);//消息数量
const messageHidden = computed(() => { //消息是否隐藏
  return messageCount.value === 0;
});
// 全部已读点击
const onAllReadClick = () => {
  messageCount.value = 0;
};
//  检查密码强度
let modes = ref<number>(0);
const checkPassword = (rule: any, value: string, callback: any) => {
	if (!value) {
		modes.value = 0;
		return callback('新密码不能为空');
	}
	if (value.length < 8) {
		modes.value = 0;
		return callback('新密码不少于8位');
	}
	/*
	  最短8位， {6,}
	  可以包含小写大母 [a-z] 和大写字母 [A-Z]
	  可以包含数字 [0-9]
	  可以包含下划线 [ _ ] 和减号 [ - ]
	*/
	if (/^[\w_-]{6,}$/.test(state.dutyForm.newPassword)) {
		modes.value = 1;
	}
	/*
	  最短8位， {8,}
	  必须包含1个数字
	  必须包含1个小写字母
	  必须包含1个大写字母
	  必须包含1个特殊字符
	*/
	if (/^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.?])\S*$/.test(state.dutyForm.newPassword)) modes.value = 2; //中等
	/*
	  最短8位， {8,}
	  必须包含1个数字
	  必须包含1个小写字母
	  必须包含1个大写字母
	  必须包含2个特殊字符
	*/
	if (/^\S*(?=\S{8,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*.?]{2,})\S*$/.test(state.dutyForm.newPassword)) modes.value = 3; //强密码
	if (modes.value == 0 || modes.value == 1) {
		return callback('提示：密码不得少于8位数，且必须包含字母大小写和特殊字符'); //弱密码
	}
	if (value === state.dutyForm.currentPassword) {
		return callback('新密码不能与旧密码一致，请重新输入');
	}
	return callback();
};
// 检查输入密码是否一致
const checkConfirmPassword = (rule: any, value: any, callback: any) => {
	if (!value) {
		return callback('请再次输入密码');
	}
	if (value != state.dutyForm.newPassword) {
		return callback('两次密码输入不一致，请重新输入');
	}
	return callback();
};
const rules = reactive({
	currentPassword: [{ required: true, message: '请输入旧密码', trigger: ['change', 'blur'] }],
	newPassword: [{ required: true, validator: checkPassword, trigger: ['change', 'blur'] }],
	confirmPassword: [{ required: true, validator: checkConfirmPassword, trigger: 'blur' }],
});
const dialogVisible = ref(false);
// 设置分割样式
const layoutUserFlexNum = computed(() => {
	let num: string | number;
	const { layout, isClassicSplitMenu } = themeConfig.value;
	const layoutArr: string[] = ['defaults', 'columns'];
	if (layoutArr.includes(layout) || (layout === 'classic' && !isClassicSplitMenu)) num = '1';
	else num = '';
	return num;
});
// 全屏点击时
const onScreenfullClick = () => {
	if (!screenfull.isEnabled) {
		ElMessage.warning('暂不不支持全屏');
		return false;
	}
	screenfull.toggle();
	screenfull.on('change', () => {
		state.isScreenfull = screenfull.isFullscreen;
	});
};
// 布局配置 icon 点击时
const onLayoutSetingClick = () => {
	mittBus.emit('openSetingsDrawer');
};
const dutyFormRef = ref<RefType>();
// 下拉菜单点击时
const onHandleCommandClick = (path: string) => {
	switch (path) {
		case 'changePwd': // 修改密码
			//  重置表单
			if (dutyFormRef.value) {
				dutyFormRef.value.resetFields();
			}
			showDutyDialog.value = true;
			break;
		case 'setting': // 设置
			onLayoutSetingClick();
			break;
		case 'search': // 搜索
			onSearchClick();
			break;
		case 'logOut': //退出登录
			if (telStatusInfo.value.isDutyOn) {
				ElMessageBox({
					closeOnClickModal: false,
					closeOnPressEscape: false,
					title: '提示',
					message: '检测到您未签出,本次退出系统将自动签出, 是否继续?',
					showCancelButton: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					buttonSize: 'default',
					draggable: true,
					type: 'warning',
					autofocus: false,
					cancelButtonClass: 'default-button',
					beforeClose: (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = '退出中';
							setTimeout(() => {
								done();
								setTimeout(() => {
									instance.confirmButtonLoading = false;
								}, 300);
							}, 700);
						} else {
							done();
						}
					},
				})
					.then(async () => {
						VoiceInterfaceObject.LogOut();
						// offDuty().then(() => {
						// 断开链接
						// signalR.stop();
						// 重置所有状态
						usetelStatusStore.resetState();
						// 清除缓存/token等
						Local.clear();
						Session.clear();
            Cookie.clear();
						// 使用 reload 时，不需要调用 resetRoute() 重置路由
						window.location.reload();
						// });
					})
					.catch(() => {});
				return;
			}
			ElMessageBox({
				closeOnClickModal: false,
				closeOnPressEscape: false,
				title: '提示',
				message: '此操作将退出登录, 是否继续?',
				showCancelButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				buttonSize: 'default',
				draggable: true,
				type: 'warning',
				autofocus: false,
				cancelButtonClass: 'default-button',
				beforeClose: (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						instance.confirmButtonText = '退出中';
						setTimeout(() => {
							done();
							setTimeout(() => {
								instance.confirmButtonLoading = false;
							}, 300);
						}, 700);
					} else {
						done();
					}
				},
			})
				.then(async () => {
					// 清除缓存/token等
					Local.clear();
					Session.clear();
          Cookie.clear();
					// 使用 reload 时，不需要调用 resetRoute() 重置路由
					window.location.reload();
				})
				.catch(() => {});
			break;
		default: //返回首页
			router.push('/');
			break;
	}
};
// 菜单搜索点击
const onSearchClick = () => {
	searchRef.value.openSearch();
};
// 组件大小改变
const onComponentSizeChange = (size: string) => {
	Local.remove('themeConfig');
	themeConfig.value.globalComponentSize = size;
	Local.set('themeConfig', themeConfig.value);
	initComponentSize();
	window.location.reload();
};
// 初始化全局组件大小
const initComponentSize = () => {
	switch (Local.get('themeConfig').globalComponentSize) {
		case 'large':
			state.disabledSize = 'large';
			break;
		case 'default':
			state.disabledSize = 'default';
			break;
		case 'small':
			state.disabledSize = 'small';
			break;
	}
};
const ruleFormRef = ref<RefType>();
//  锁频
const onLockScreen = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	dialogVisible.value = true;
};
// 确定锁频
const confirmLock = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		themeConfig.value.isLockScreen = true;
		Local.set('themeConfig', themeConfig.value);
		Session.set('lockPwd', state.ruleForm.pwd);
		dialogVisible.value = false;
	});
};
const showDutyDialog = ref(false);
const loading = ref(false);
// 修改密码保存
const save = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
		changePwd(state.dutyForm)
			.then(async () => {
				ElNotification({
					title: '成功',
					type: 'success',
					message: '密码修改成功，请重新登录',
				});
				setTimeout(() => {
					loading.value = false;
					// 使用 reload 时，不需要调用 resetRoute() 重置路由
					window.location.reload();
					// 清楚缓存
					Session.clear();
          Cookie.clear();
					Local.clear();
				}, 1000);
			})
			.catch(() => {
				showDutyDialog.value = false;
				loading.value = false;
			});
	});
};
// 开发环境不显示设置
const showSetting = computed(() => {
	return import.meta.env.VITE_MODE_NAME === 'development';
});
// 页面加载时
onMounted(() => {
	if (Local.get('themeConfig')) {
		initComponentSize();
	}
});
</script>

<style scoped lang="scss">
.layout-navbars-breadcrumb-user {

  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;

	&-link {
		height: 100%;
		white-space: nowrap;
		text-align: center;
    flex:1;
		&-photo {
			background-color: var(--hotline-bg-main-color);
			border: 2px solid var(--el-color-primary);
      margin-right: 5px;
		}
		&-photoBox {
			display: flex;
			justify-content: center;
      align-items: center;
      &-name{
        max-width: 150px;
        overflow: hidden;
      }
		}
	}

	&-icon {
		padding: 0 10px;
		cursor: pointer;
		color: var(--hotline-color-text-main);
		&:hover {
			i {
				display: inline-block;
				animation: logoAnimation 0.3s ease-in-out;
			}
		}
	}

	:deep(.el-dropdown) {
		color: var(--hotline-color-text-main);
		flex:1;
	}
	.intensity {
		.psdText {
			font-size: 14px;
			margin-right: 10px;
			color: #5a5a5a;
		}

		.line {
			display: inline-block;
			width: 48px;
			height: 10px;
			background: #d8d8d8;
			margin-right: 2px;

			&.ruo {
				border-radius: 6px 0 0 6px;
			}

			&.low {
				background: #bfcdff;
			}

			&.middle {
				background: #93a6fa;
			}

			&.high {
				background: #3c50e0;
			}

			&.qiang {
				border-radius: 0 6px 6px 0;
			}
		}

		.level {
			margin: 0 16px 0 8px;
		}
	}
}
</style>
