<template>
  <div class="user-avatar-dropdown">
    <Dropdown
      :transfer="false"
      :visible="dropdownVisible"
      @on-click="handleClick"
      @on-clickoutside="handleClickOutside"
      trigger="custom"
    >
      <Avatar :src="userAvatar" @click="dropdownVisible = true" />
      <Badge :dot="!!messageUnreadCount">
        <div @click="dropdownVisible = true" class="username">{{userName}}</div>
      </Badge>
      <Icon :size="18" @click="dropdownVisible = true" type="md-arrow-dropdown"></Icon>
      <DropdownMenu slot="list">
        <DropdownItem name="message">
          消息中心
          <Badge :count="messageUnreadCount" style="margin-left: 10px"></Badge>
        </DropdownItem>
        <Poptip @on-cancel="dropdownVisible = false" @on-ok="logout" confirm title="确定退出系统？">
          <DropdownItem name="logout">退出登录</DropdownItem>
        </Poptip>
      </DropdownMenu>
    </Dropdown>
  </div>
</template>

<script>
import './user.less'
import { mapState, mapActions } from 'vuex'
import avatar from '@icon/avatar.png'
import { excuteInterval } from '@lib/tools'
export default {
  name: 'UserCenter',
  data () {
    return {
      dropdownVisible: false,
      logoutConfirm: false
    }
  },
  props: {
    userAvatar: {
      type: String,
      default: avatar
    }
  },
  computed: {
    ...mapState({
      userToken: state => state.user.token,
      userName: state => state.user.userName || '未设置姓名',
      messageUnreadCount: state => state.user.unreadCount
    })
  },
  mounted () {
    // 1: 定时获取未读消息数
    // 2: 拉取服务器时间（日期、时间控件使用服务器时间做限制，防止本地篡改）
    this.getUnreadMessageCount()
    excuteInterval(this.$config.FETCH_MSG_INTERVAL, () => {
      if (this.userToken) {
        this.getUnreadMessageCount()
      }
    })
    //1: 保持会话
    // excuteInterval(this.$config.KEEP_ALIVE_INTERVAL, () => {
    //   if (this.userToken) {
    //     this.keepAlive()
    //   }
    // })
  },
  methods: {
    ...mapActions(['handleLogout', 'getUnreadMessageCount', 'keepAlive']),
    logout () {
      this.$Message.loading({
        content: '正在退出...',
        duration: 0
      })
      this.handleLogout()
        .then(data => {
          this.$Message.destroy()
          this.$Message.success('已退出！')
          // 用户手动退出登录时关闭页面
          window.close()
        })
        .catch(err => {
          console.error('logout error: ', err)
        })
    },
    message () {
      this.dropdownVisible = false
      this.$router.push({
        name: 'msg'
      })
    },
    handleClick (name) {
      switch (name) {
        case 'logout':
          // this.logout()
          this.logoutConfirm = true
          break
        case 'message':
          this.message()
          break
      }
    },
    handleClickOutside () {
      this.dropdownVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.user-avatar-dropdown {
  /deep/ .ivu-poptip-body-message {
    color: #515a6e;
  }
}
</style>
