<template>
	<div
		:style="{
			marginRight: '12px',
			lineHeight: `${config.layout.headerHeight}px`,
		}"
	>
		<a-space>
			<a-dropdown>
				<template #overlay>
					<a-menu>
						<a-menu-item>
							<template #icon>
								<icon-font type="icon-settings" />
							</template>
							<span>{{ $t('layout.user.profile') }}</span>
						</a-menu-item>
						<a-menu-item @click="logout">
							<template #icon>
								<icon-font type="icon-logout" />
							</template>
							<span>{{ $t('layout.user.logout') }}</span>
						</a-menu-item>
					</a-menu>
				</template>
				<a-avatar v-if="user?.avatar" :title="user?.fullName || user?.userName" :src="user?.avatar" />
				<a-avatar v-else :title="user?.fullName || user?.userName" class="right-acatar">
					{{ (user?.fullName || user?.userName || '').substring(0, 1) }}
				</a-avatar>
			</a-dropdown>
			<a-dropdown v-if="config.enableI8n">
				<template #overlay>
					<a-menu v-model:selected-keys="currentLanguage" @click="switchLanguage">
						<a-menu-item key="zh_CN">
							<template #icon>
								<icon-font type="icon-chinese" />
							</template>
							<span>中文-简体</span>
						</a-menu-item>
						<a-menu-item key="en_US">
							<template #icon>
								<icon-font type="icon-english" />
							</template>
							<span>English</span>
						</a-menu-item>
					</a-menu>
				</template>
				<a-avatar
					:style="{
						backgroundColor: token.colorPrimaryBg,
						color: token.colorPrimary,
					}"
				>
					<template #icon><icon-font type="icon-language" style="font-size: 32px" /></template>
				</a-avatar>
			</a-dropdown>
		</a-space>
	</div>
</template>

<script setup lang="ts">
	import { useAppStore } from '@/stores/app'
	import { useI18n } from 'vue-i18n'
	import { Modal, theme } from 'ant-design-vue'
	import { createVNode } from 'vue'
	import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
	import { config } from '@/settings/application'
	import { MenuInfo } from 'ant-design-vue/es/menu/src/interface'
	import { useUserStore } from '@/stores/user'
	import api from '@/api'
	const t = useI18n()
	const user = useUserStore()

	const currentLanguage = computed(() => {
		return [useAppStore().language]
	})
	const switchLanguage = ({ key }: MenuInfo) => {
		t.locale.value = String(key)
		const html = document.querySelector('html')
		html?.setAttribute('lang', String(key))
		useAppStore().changeLocale(key as 'zh_CN' | 'en_US')
	}
	const logout = () => {
		Modal.confirm({
			title: '退出登录',
			icon: createVNode(ExclamationCircleOutlined),
			content: createVNode('div', { style: 'color:red;' }, '确定退出系统吗？'),
			onOk() {
				api.authApi.auth.logout(() => {
					user.logout()
				})
			},
		})
	}

	const { useToken } = theme
	const { token } = useToken()
</script>
<style lang="css" scoped>
	.ant-avatar {
		cursor: pointer;
	}
</style>
