<template>
  <ai-dropdown size="small" class="d2-mr">
    <div class="btn-text user-info">
      <span v-if="info.user_info && info.user_info.avatar">
        <img :src="info.user_info.avatar" class="user-avatar"/>
      </span>
      <span v-else class="user-avatar user-avatar-default"></span>
      <span>
        你好 {{info.name}}
      </span>
      <i class="ai-icon-arrow-down ai-icon--right"></i>
    </div>

    <ai-dropdown-menu slot="dropdown">
      <!-- <ai-dropdown-item @click.native="updatePassword">
        <d2-icon name="pencil" class="d2-mr-5"/>
        修改密码
      </ai-dropdown-item> -->
      <ai-dropdown-item @click.native="logOff">
        <d2-icon name="power-off" class="d2-mr-5"/>
        注销
      </ai-dropdown-item>
    </ai-dropdown-menu>
  </ai-dropdown>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import store from '@/store/index'
export default {
  computed: {
    ...mapState('d2admin/user', [
      'info'
    ])
  },
  created () {
    // this.initWebSocket();
  },
  methods: {
    ...mapActions('d2admin/account', [
      'logout'
    ]),
    /**
     * @description 登出
     */
    logOff () {
      this.logout({
        vm: this,
        confirm: true
      })
    },
    // 修改密码
    updatePassword () {
      this.$router.push({
        name: 'updatePwd'
      })
    },
    initWebSocket () { // 初始化weosocket
      const user = store.state.d2admin.user.info.user_info.username
      const wsuri = 'ws://localhost:9090/websocket/' + user
      this.websock = new WebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    // 广播发送
    websocketonopen () { // 连接建立之后执行send方法发送数据
      this.websocketsend()
    },
    websocketonerror () { // 连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage (e) { // 数据接收
      if (e.data && e.data !== 'undefined') {
        this.$notify.success(e.data)
      }
    },
    websocketsend (Data) { // 数据发送
      this.websock.send(Data)
    },
    websocketclose (e) { // 关闭
      console.log('断开连接', e)
    }
  }
}
</script>
<style lang="less">
.user-avatar {
  cursor: pointer;
  width: 35px;
  height: 35px;
  margin-right: 6px;
  border-radius: 50%;
}
.user-avatar-default {
  background:#f5f5f5
}
.user-info{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
