<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <img src="@/assets/images/avatar.gif" alt="avatar" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openDialog('infoRef')">
          <el-icon><User /></el-icon>个人信息
        </el-dropdown-item>
        <el-dropdown-item @click="openDialog('passwordRef')">
          <el-icon><Edit /></el-icon>修改密码
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <!-- infoDialog -->
  <InfoDialog ref="infoRef" />
  <!-- passwordDialog -->
  <PasswordDialog ref="passwordRef" />
</template>

<script setup lang="ts">
import { logoutApi } from '@/api/system/auth'
import InfoDialog from './InfoDialog.vue'
import PasswordDialog from './PasswordDialog.vue'
import { Edit, SwitchButton, User } from '@element-plus/icons-vue'
import { removeToken } from '@/utils'
import { useTabsStore } from '@/stores/modules/tabs'
import { useKeepAliveStore } from '@/stores/modules/keepAlive'

const LOGIN_URL = import.meta.env.VITE_LOGIN_URL

const router = useRouter()
const tabsStore = useTabsStore()
const keepAliveStore = useKeepAliveStore()

// 退出登录
const logout = () => {
  ElMessageBox.confirm('您是否确认退出登录?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 执行退出登录接口
    await logoutApi()

    // 清除 Token
    removeToken()

    // 重定向到登陆页
    await router.replace(LOGIN_URL)

    // 清空 tabs、keepAlive 数据
    await tabsStore.setTabs([])
    await keepAliveStore.setKeepAliveName([])

    ElMessage.success('退出登录成功！')
  })
}

// 打开修改密码和个人信息弹窗
const infoRef = ref<InstanceType<typeof InfoDialog>>()
const passwordRef = ref<InstanceType<typeof PasswordDialog>>()
const openDialog = (ref: string) => {
  if (ref == 'infoRef') infoRef.value?.openDialog()
  if (ref == 'passwordRef') passwordRef.value?.openDialog()
}
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
