<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <el-avatar v-if="userStore.user.avatar" :src="userStore.user.avatar" />
      <el-avatar v-else icon="UserFilled" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <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>
  <PasswordDialog ref="passwordRef" />
</template>

<script setup lang="ts" name="Avatar">
import { LOGIN_URL } from '@/constants'
import router from '@/router'
import { useUserStore } from '@/stores'
import PasswordDialog from '@/views/system/user/components/PasswordDialog.vue'
const userStore = useUserStore()
// 退出登录
const logout = () => {
  ElMessageBox.confirm('您是否确认退出登录?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 1.执行退出登录接口
    await userStore.userLogout()

    // 2.重定向到登陆页
    router.replace(LOGIN_URL)
    ElMessage.success('退出登录成功！')
  })
}
const passwordRef = ref<InstanceType<typeof PasswordDialog>>()

const openDialog = (ref: string) => {
  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>
