<template>
	<div class="layout-navbars-breadcrumb-user">
		<!-- <el-dropdown :show-timeout="70" :hide-timeout="50" trigger="click" @command="onComponentSizeChange">
			<div class="layout-navbars-breadcrumb-user-icon">
				<i class="iconfont icon-ziti" :title="$t('message.user.title0')"></i>
			</div>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item command="" :disabled="disabledSize === ''">{{ $t('message.user.dropdownDefault') }}</el-dropdown-item>
					<el-dropdown-item command="medium" :disabled="disabledSize === 'medium'">{{ $t('message.user.dropdownMedium') }}</el-dropdown-item>
					<el-dropdown-item command="small" :disabled="disabledSize === 'small'">{{ $t('message.user.dropdownSmall') }}</el-dropdown-item>
					<el-dropdown-item command="mini" :disabled="disabledSize === 'mini'">{{ $t('message.user.dropdownMini') }}</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown> -->
		<div v-if="testDev" class="layout-navbars-breadcrumb-user-icon mr10" style="color: red;font-weight: 800; font-size: 20px; margin-right: 30px;" @click="onScreenfullClick">
			{{ $t('message.user.测试环境哦') }}
		</div>
		<div class="layout-navbars-breadcrumb-user-icon" @click="getUserTicketList">{{ $t('message.user.工单') }}</div>
		<el-dropdown :show-timeout="70" :hide-timeout="50" trigger="click" @command="onLanguageChange">
			<div class="layout-navbars-breadcrumb-user-icon">
				<!-- <i class="iconfont" :class="disabledI18n === 'en' ? 'icon-fuhao-yingwen' : 'icon-fuhao-zhongwen'" :title="$t('message.user.title1')"></i> -->
				<img :src="i18nImgUrl" style="width: 24px;" alt="" srcset="">
			</div>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item command="zh-cn" :disabled="disabledI18n === 'zh-cn'">
						<img src="../../../assets/imgs/nationalFlag/zh.png" style="width: 24px;margin-right: 8px;" alt="" srcset="">
						简体中文</el-dropdown-item>
					<el-dropdown-item command="ja" :disabled="disabledI18n === 'ja'">
						<img src="../../../assets/imgs/nationalFlag/jp.png" style="width: 24px;margin-right: 8px;" alt="" srcset="">
						日本語</el-dropdown-item>
					<el-dropdown-item command="en" :disabled="disabledI18n === 'en'">
						<img src="../../../assets/imgs/nationalFlag/us.png" style="width: 24px;margin-right: 8px;" alt="" srcset="">
						English</el-dropdown-item>
					<el-dropdown-item command="zh-tw" :disabled="disabledI18n === 'zh-tw'">
						<img src="../../../assets/imgs/nationalFlag/zh.png" style="width: 24px;margin-right: 8px;" alt="" srcset="">
						繁體中文</el-dropdown-item>
					<el-dropdown-item command="ms" :disabled="disabledI18n === 'ms'">
						<img src="../../../assets/imgs/nationalFlag/ms.png" style="width: 24px;margin-right: 8px;" alt="" srcset="">
						Malay</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		<!-- <div class="layout-navbars-breadcrumb-user-icon" @click="onSearchClick">
			<el-icon :title="$t('message.user.title2')">
				<elementSearch />
			</el-icon>
		</div> -->
		<!-- <div class="layout-navbars-breadcrumb-user-icon" @click="onLayoutSetingClick">
			<i class="icon-skin iconfont" :title="$t('message.user.title3')"></i>
		</div> -->
		
		<!-- <div class="layout-navbars-breadcrumb-user-icon mr10" @click="onScreenfullClick">
			<i
				class="iconfont"
				:title="isScreenfull ? $t('message.user.title6') : $t('message.user.title5')"
				:class="!isScreenfull ? 'icon-fullscreen' : 'icon-tuichuquanping'"
			></i>
		</div> -->
		<div class="layout-navbars-breadcrumb-user-icon">
			<el-popover placement="bottom" trigger="click" v-model:visible="isShowUserNewsPopover" :width="300" popper-class="el-popover-pupop-user-news">
				<template #reference>
					<el-badge  :type="badgeType"  :value="mesLength" @click="isShowUserNewsPopover = !isShowUserNewsPopover">
						<el-icon :title="$t('message.user.title4')">
							<elementBell />
						</el-icon>
					</el-badge>
				</template>
				<transition name="el-zoom-in-top">
					<UserNews @confirmCols="confirmCols" @setmagLength="setmagLength" v-show="isShowUserNewsPopover" />
				</transition>
			</el-popover>
		</div>
		<el-dropdown :show-timeout="70" :hide-timeout="50" :hide-on-click="false" trigger="click">
			<div class="layout-navbars-breadcrumb-user-icon">
				<span style="font-weight: 800;">{{getUserInfos.client.clientName}}</span>	<el-icon><Location /></el-icon>
			</div>
			<template #dropdown>
				
				<el-dropdown-menu :style="{ maxHeight: '600px', overflow: 'auto' }">
					<el-input
						v-model="filterText"
						:placeholder="$t('message.user.请输入关键字')"
						@input="handleInput"
						clearable
					></el-input>
					<el-dropdown-item v-for="(client,key) in view_cliens" :key="key" @click="clientSet(client)" >
						<span :style="{color:getUserInfos.client.clientName===client.clientName?'#409EFF':''}">
							{{client.clientName}}
						</span>
						
					</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		
		<el-dropdown :show-timeout="70" :hide-timeout="50" @command="onHandleCommandClick">
			<span class="layout-navbars-breadcrumb-user-link">
				<img :src="getUserInfos.photo" class="layout-navbars-breadcrumb-user-link-photo mr5" />
				{{ getUserInfos.userName === '' ? 'test' : getUserInfos.userName }}
				<el-icon class="el-icon--right">
					<elementArrowDown />
				</el-icon>
			</span>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item command="/home">{{ $t('message.user.dropdown1') }}</el-dropdown-item>
					<!-- <el-dropdown-item command="wareHouse">{{ $t('message.user.dropdown6') }}</el-dropdown-item> -->
					<el-dropdown-item command="/system/personalInfo">{{ $t('message.user.dropdown2') }}</el-dropdown-item>
					<el-dropdown-item command="about">{{ $t('message.user.关于') }}</el-dropdown-item>
					<el-dropdown-item command="help">{{ $t('message.user.帮助') }}</el-dropdown-item>
					<el-dropdown-item  command="logOut">{{ $t('message.user.dropdown5') }}</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		<!-- 工单详情 -->
		<Search ref="searchRef" />
		<el-dialog v-model="isWorkOrderShow" :title="$t('message.user.工单')" center :destroy-on-close="true">
			<Ticket ref="ticketRef" :type="ticketStatus" :code="ticketCode" />
			<template #footer>
			<div v-if="!ticketStatus" class="dialog-footer">
				<el-button :disabled="ticketLoading" @click="isWorkOrderShow = false">{{ $t('message.user.取消') }}</el-button>
				<el-button type="primary" :loading="ticketLoading" @click="sendWorkOrder">
					{{ $t('message.user.确认') }}
				</el-button>
			</div>
			</template>
		</el-dialog>
		<!-- 工单列表 -->
		<el-dialog v-model="isTicketListShow" :title="$t('message.user.我的工单')" center :destroy-on-close="true">
			<div style="margin-bottom:15px;" class="btn_top_box">
				<el-button type="success" size="small" @click="addTicket">{{ $t('message.user.我的工单') }}</el-button>
			</div>
			<el-table v-loading="ticketListLoading" :data="ticketList" size="small" :height="600">
				<el-table-column prop="ticketSubmitTime" :label="$t('message.user.提交日期')"  />
				<el-table-column prop="date" :label="$t('message.user.工单内容')" :show-overflow-tooltip="true">
					<template #default="scope">
						<div v-html="scope.row.ticketBody"></div>
					</template>
				</el-table-column>
				<el-table-column prop="status" :label="$t('message.user.工单内容')"  >
					<template #default="scope">
					<el-tag :type="scope.row.ticketStatus ? 'success' : ''" size="mini">{{ scope.row.ticketStatus ? $t('message.user.已办结') : $t('message.user.已提交') }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="ticketReplyTime" :label="$t('message.user.回复时间')"  />
				<el-table-column prop="date" :label="$t('message.user.回复内容')" :show-overflow-tooltip="true">
					<template #default="scope">
						<div v-html="scope.row.ticketReply"></div>
					</template>
				</el-table-column>
				<el-table-column prop="date" :label="$t('message.user.操作')" :show-overflow-tooltip="true">
					<template #default="scope">
						<el-button type="primary" link size="small" @click="lookSicketInfo(scope.row)">{{ $t('message.user.查看') }}</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, getCurrentInstance, computed, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import screenfull from 'screenfull';
import { useI18n } from 'vue-i18n';
import { resetRoute } from '/@/router/index';
import { useStore } from '/@/store/index';
import other from '/@/utils/other';
import { Session, Local } from '/@/utils/storage';
import UserNews from '/@/layout/navBars/breadcrumb/userNews.vue';
import Search from '/@/layout/navBars/breadcrumb/search.vue';
import { ticketListApi } from '/@/api/user_ticket/index';
import Ticket from './ticket.vue';
import zhCnImgUrl from '/@/assets/imgs/nationalFlag/zh.png';
import enImgUrl from '/@/assets/imgs/nationalFlag/us.png';
import jpImgUrl from '/@/assets/imgs/nationalFlag/jp.png';
import msImgUrl from '/@/assets/imgs/nationalFlag/ms.png';
import { confirmClient } from '/@/api/user';

export default {
	name: 'layoutBreadcrumbUser',
	components: { UserNews, Search, Ticket },
	setup() {
		const { t } = useI18n();
		const { proxy } = getCurrentInstance() as any;
		const router = useRouter();
		const store = useStore();
		const searchRef = ref();
		const state = reactive({
			filterText:'', //客户赛选
			badgeType:'primary',
			mesLength:0,
			testDev:false,
			isScreenfull: false,
			isShowUserNewsPopover: false,
			disabledI18n: store.state.zdyConfig.locale,
			disabledSize: '',
			isWorkOrderShow: false, // 工单详情是否显示
			ticketLoading: false, // 工单详情loading
			ticketList: [], // 工单列表,
			isTicketListShow: false, // 工单列表是否显示
			ticketListLoading: false, // 工单列表的请求loading
			ticketStatus: 0, // 0新增工单1查看工单
			ticketCode: '', // 查看工单的code,
			view_cliens:[],
		});

		const ticketRef = ref();
		// 获取用户信息 vuex
		const getUserInfos = computed(() => {
			return store.state.userInfos.userInfos;
		});
		// 获取布局配置信息
		const getThemeConfig = computed(() => {
			return store.state.themeConfig.themeConfig;
		});
		// 设置分割样式
		const layoutUserFlexNum = computed(() => {
			let { layout, isClassicSplitMenu } = getThemeConfig.value;
			let num = '';
			if (layout === 'defaults' || (layout === 'classic' && !isClassicSplitMenu) || layout === 'columns') num = 1;
			else num = null;
			return num;
		});

		// 发布版本
		const releaseVersion = computed(() => {
			return import.meta.env.VITE_RELEASE_VERSION;
		});

		// 完整版本
		const fullVersion = computed(() => {
			return import.meta.env.VITE_FULL_VERSION;
		});

		// 国际化语言图标
		const i18nImgUrl = computed(() => {
			let url = ''
			switch(state.disabledI18n) {
				case 'zh-cn':
					url = zhCnImgUrl;
					break;
				case 'en':
					url = enImgUrl;
					break;
				case 'ja':
					url = jpImgUrl;
					break;
				case 'zh-tw':
					url = zhCnImgUrl;
					break;
				case 'ms':
					url = msImgUrl;
					break;
			}
			console.log(state.disabledI18n)
			return url
		});
		// 全屏点击时
		const onScreenfullClick = () => {
			if (!screenfull.isEnabled) {
				ElMessage.warning(t('message.user.暂不不支持全屏'));
				return false;
			}
			screenfull.toggle();
			screenfull.on('change', () => {
				if (screenfull.isFullscreen) state.isScreenfull = true;
				else state.isScreenfull = false;
			});
		};
		// 布局配置 icon 点击时
		const onLayoutSetingClick = () => {
			proxy.mittBus.emit('openSetingsDrawer');
		};
		// 下拉菜单点击时
		const onHandleCommandClick = (path: string) => {
			if (path === 'logOut') {
				ElMessageBox({
					closeOnClickModal: false,
					closeOnPressEscape: false,
					title: t('message.user.logOutTitle'),
					message: t('message.user.logOutMessage'),
					showCancelButton: true,
					confirmButtonText: t('message.user.logOutConfirm'),
					cancelButtonText: t('message.user.logOutCancel'),
					beforeClose: (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = t('message.user.logOutExit');
							setTimeout(() => {
								done();
								setTimeout(() => {
									instance.confirmButtonLoading = false;
								}, 300);
							}, 700);
						} else {
							done();
						}
					},
				})
					.then(() => {
						console.log('登出----')
						Session.clear(); // 清除缓存/token等
						Local.clear()
						console.log(Local.get('patientInfo'))
						Local.remove('patientInfo')
						// 清除userInfo
						Local.remove('userInfo')
						Local.remove('uId')
						Local.remove('uCode')
						resetRoute(); // 删除/重置路由
						router.push('/login');
						setTimeout(() => {
							ElMessage.success(t('message.user.logOutSuccess'));
						}, 300);
					})
					.catch(() => {});
			} else if (path === 'wareHouse') {
				window.open('https://gitee.com/lyt-top/vue-next-admin');
			} else if (path === 'about') {
				ElMessageBox.alert(`${t('message.user.完整版本')}：${fullVersion.value}；${t('message.user.发布版本')}：${releaseVersion.value}`, t('message.user.关于'), {
					confirmButtonText: 'OK',
					callback: (action: any) => {
					},
				})
			} else if (path === 'help') {
				window.open('http://datacdn.data-it.tech/temp/%E8%A1%80%E6%B6%B2%E9%80%8F%E6%9E%90%E4%BF%A1%E6%81%AF%E7%AE%A1%E7%90%86%E8%BD%AF%E4%BB%B6%E4%BA%A7%E5%93%81%E8%AF%B4%E6%98%8E%E4%B9%A620240124.pdf');
			} else {
				router.push(path);
			}
		};
		// 菜单搜索点击
		const onSearchClick = () => {
			searchRef.value.openSearch();
		};
		// 组件大小改变
		const onComponentSizeChange = (size: string) => {
			Local.remove('themeConfig');
			getThemeConfig.value.globalComponentSize = size;
			Local.set('themeConfig', getThemeConfig.value);
			proxy.$ELEMENT.size = size;
			initComponentSize();
			window.location.reload();
		};
		// 语言切换
		const onLanguageChange = (lang: string) => {
			Local.remove('themeConfig');
			getThemeConfig.value.globalI18n = lang;
			Local.set('themeConfig', getThemeConfig.value);
			proxy.$i18n.locale = lang;
			initI18n();
			other.useTitle();
			store.commit("zdyConfig/SET_SYSTEM_LOCALE", lang);
			window.location.reload();
		};
		// 设置 element plus 组件的国际化
		const setI18nConfig = (locale: string) => {
			proxy.mittBus.emit('getI18nConfig', proxy.$i18n.messages[locale]);
		};
		// 初始化言语国际化
		const initI18n = () => {
			switch (Local.get('themeConfig').globalI18n) {
				case 'zh-cn':
					state.disabledI18n = 'zh-cn';
					setI18nConfig('zh-cn');
					break;
				case 'en':
					state.disabledI18n = 'en';
					setI18nConfig('en');
					break;
				case 'zh-tw':
					state.disabledI18n = 'zh-tw';
					setI18nConfig('zh-tw');
					break;
				case 'ja':
					state.disabledI18n = 'ja';
					setI18nConfig('ja');
					break;
				case 'ms':
					state.disabledI18n = 'ms';
					setI18nConfig('ms');
					break;
			}
		};
		// 初始化全局组件大小
		const initComponentSize = () => {
			switch (Local.get('themeConfig').globalComponentSize) {
				case '':
					state.disabledSize = '';
					break;
				case 'medium':
					state.disabledSize = 'medium';
					break;
				case 'small':
					state.disabledSize = 'small';
					break;
				case 'mini':
					state.disabledSize = 'mini';
					break;
			}
		};
		const confirmCols=()=>{
			state.isShowUserNewsPopover=false
		}
		const setmagLength=(num:number)=>{
			state.mesLength=num
		}
		watch(()=>state.mesLength,()=>{
			if(state.mesLength>0){
				setInterval(()=>{
					if(state.badgeType==='primary'){
						state.badgeType='info'
					}else{
						state.badgeType='primary'
					}
					
				},500)
			}
		})

		/** 发送工单 */
		const sendWorkOrder = async () => {
			state.ticketLoading = true;
			const isOk = await ticketRef.value.add();
			state.ticketLoading = false;
			getUserTicketList();
			if (isOk) {
				state.isWorkOrderShow = false;
			}
		}

		/** 获取工单列表 */
		const getUserTicketList = async () => {
			state.isTicketListShow = true;
			state.ticketListLoading = true;
			try {
				const params = {
					page: 0,
					size: 0,
					// @ts-ignore
					wherecondition: `client_code='${getUserInfos.value.client.code}' and user_code='${getUserInfos.value.userCode}'`,
					ordercondition: 'create_time desc'
				}
				const { data } = await ticketListApi(params);
				state.ticketList = data.list;
			} finally {
				state.ticketListLoading = false;
			}
		}

		/** 查看工单详情 */
		const lookSicketInfo = (row: any) => {
			state.ticketStatus = 1;
			state.ticketCode = row.code;
			state.isWorkOrderShow = true;
		}
		
		/** 添加工单 */
		const addTicket = () => {
			state.ticketStatus = 0;
			state.isWorkOrderShow = true;
		};
		const clientSet=(client:any)=>{
			//缓存客户选择
			Local.set('client_'+client.code,client.code)
			confirmClient('clientCode='+client.code).then((res)=>{
				// 更新token
				Session.set('token', res.data);
				Session.remove('userInfo')
				window.location.reload();
			})
		}
		const handleInput=()=>{
			console.log(state.filterText)
			if(state.filterText){
				state.view_cliens=[]
				getUserInfos.value.clients.forEach(e=>{
					if(e.clientName.indexOf(state.filterText)>=0){
						state.view_cliens.push(e)
					}
				})
			}else{
				getViewCilents()
			}
		}
		// 加载客户列表
		const getViewCilents=()=>{
			state.view_cliens=[]
			if(getUserInfos.value.clients?.length>0){
				getUserInfos.value.clients.forEach(e=>{
					state.view_cliens.push(e)
				})
			}
		}
		// 页面加载时
		onMounted(() => {
			state.view_cliens=getUserInfos.value.clients
			if (process.env.NODE_ENV === "development") {
				state.testDev=true
				}else {
				state.testDev=false
			}
			if (Local.get('themeConfig')) {
				initI18n();
				initComponentSize();
			}
			console.log('------------------------------')
			getViewCilents()
		});
		return {
			confirmCols,
			clientSet,
			setmagLength,
			handleInput,
			getUserInfos,
			onLayoutSetingClick,
			onHandleCommandClick,
			onScreenfullClick,
			onSearchClick,
			onComponentSizeChange,
			onLanguageChange,
			searchRef,
			layoutUserFlexNum,
			sendWorkOrder,
			getUserTicketList,
			ticketRef,
			lookSicketInfo,
			addTicket,
			i18nImgUrl,
			...toRefs(state),
		};
	},
};
</script>

<style scoped lang="scss">
.layout-navbars-breadcrumb-user {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	&-link {
		height: 100%;
		display: flex;
		align-items: center;
		white-space: nowrap;
		&-photo {
			width: 25px;
			height: 25px;
			border-radius: 100%;
		}
	}
	&-icon {
		padding: 0 10px;
		cursor: pointer;
		color: var(--bg-topBarColor);
		height: 50px;
		line-height: 50px;
		display: flex;
		align-items: center;
		&:hover {
			background: rgba(0, 0, 0, 0.04);
			i {
				display: inline-block;
				animation: logoAnimation 0.3s ease-in-out;
			}
		}
	}
	::v-deep(.el-dropdown) {
		color: var(--bg-topBarColor);
	}
	::v-deep(.el-badge) {
		height: 40px;
		line-height: 40px;
		display: flex;
		align-items: center;
	}
	::v-deep(.el-badge__content.is-fixed) {
		top: 12px;
	}
	::v-deep .el-table .cell.el-tooltip {
		max-height: 30px;
	}
	.btn_top_box {
		display: flex;
		justify-content: flex-end;
	}
}
</style>
