<template>
  <n-dropdown trigger="hover" :options="options" @select="selectKey">
    <div class="user_msg">
      <n-image
        class="user_avatar"
        :src="userInfo.avatar"
        preview-disabled
      />
      <span class="user_name">{{ userInfo.realname }}</span>
    </div>
  </n-dropdown>

  <!-- 修改密码 -->
  <update-modal v-if="modalShow" v-modal:visible="modalShow" />
</template>
<script>
import { reactive, toRefs, h } from 'vue'
import { NIcon } from 'naive-ui'
import {
  Pencil as EditIcon,
  LogOutOutline as LogoutIcon
} from '@vicons/ionicons5'
import { useDialog } from 'naive-ui'
import { loginOut } from '@/api/login/index.js'
import { mapActions, mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user.js'
import UpdateModal from './components/UpdateModal.vue'
export default {
  name: 'LogOut',
  components: { UpdateModal },
  setup() {
    const renderIcon = (icon) => {
      return () => {
        return h(NIcon, null, {
          default: () => h(icon)
        })
      }
    }
    const data = reactive({
      options: [
        {
          label: '修改密码',
          key: 'edit',
          icon: renderIcon(EditIcon)
        },
        {
          label: '退出登录',
          key: 'out',
          icon: renderIcon(LogoutIcon)
        }
      ],
      modalShow: false
    })

    // 选中选项触发的回调
    const dialog = useDialog()

    return {
      ...toRefs(data),
      dialog
    }
  },
  computed: {
    ...mapState(useUserStore, {
      userInfo: 'userInfo'
    })
  },
  methods: {
    ...mapActions(useUserStore, ['logout']),
    selectKey(key) {
      console.log(key)
      if (key === 'out') {
        this.dialog.warning({
          title: '提示',
          content: '确定要退出登录吗？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            loginOut().then((res) => {
              if (res.code === 0) {
                this.$router.replace('/login')
                this.logout()
                $message.success(res.msg)
              } else {
                $message.error(res.msg)
              }
            })
          }
        })
      } else if (key === 'edit') {
        this.modalShow = true
      }
    }
  }
}
</script>
<style scoped>
.user_msg {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.user_avatar {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}
</style>
