<template>
  <ul class="nav navbar-nav navbar-right">
    <li class="dropdown">
      <a
        
        class="dropdown-toggle"
        data-toggle="dropdown"
        role="button"
        aria-haspopup="true"
        aria-expanded="false"
        @click="getMessage()"
      >
        <i class="fa fa-envelope-o" />
        <span class="badge bg-green" style="margin-top: -15px; margin-left: 5px;">{{ messageCount }}</span>
      </a>
      <ul class="dropdown-menu">
        <template v-if="messages && messages.length > 0">
          <li
            v-for="item in messages" :key="item.id"
          >
            <a
              
              @click="showSingleMessage(item)"
            >
              <span class="badge" style="float:right;">{{ item.timeInterval }}</span>
              {{ item.title }} : {{ item.message }}
            </a>
          </li>
        </template>
        <li v-else>
          <a>
            <strong>没有新消息</strong>
          </a>
        </li>
        <li
          role="separator"
          class="divider"
        />
        <li>
          <a @click="viewMore">
            <strong>查看全部消息</strong>
          </a>
        </li>
        <li>
          <a @click="receiveAllMessage">
            <strong>设置所有消息已读</strong>
          </a>
        </li>
      </ul>
    </li>
  </ul>
</template>

<script>

import Common from '../common/Common.js';
import { Notify, Uuid } from 'pc-component-v3';

export default {

  components: {
  },

  props: {
    loginInfo: {
      type: Object,
      default: function(){
        return null;
      },
    },
  },

  data: function () {
    return {
      webSocket: null,
      messages: [],
      messageCount: '',
    };
  },


  watch: {
    'loginInfo': function (newValue, oldValue) {
      if (newValue != null) {
        this.getMessage();
        this.getMessageCount();
        // this.openWebSocket();
      }
    },
  },

  mounted: function(){      
    
  },

  methods: {
    /**
     * 获取消息数量
     */
    getMessageCount: function () {
      var _self = this;
      // var userId = _self.loginInfo.userId;
      $.ajax({
        url: Common.getApiURL('messageQueueResource/countByUserId'),
        type: 'get',
        dataType: 'json',
        data: {
          // userId: userId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          console.log(data);
          if(data.errorCode != 0){
            Notify.error(_self.$t('lang.Notify.prompt'), data.errorMessage, false);
            return;
          }
          _self.messageCount = data.data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 根据用户Id获取消息
     */
    getMessage: function () {
      var _self = this;
      // var userId = _self.loginInfo.userId;
      $.ajax({
        url: Common.getApiURL('messageQueueResource/listByUserId'),
        type: 'get',
        dataType: 'json',
        data: {
          // userId: userId,
          count: 10,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          // if (data == undefined || data.length == 0) {
          //   return;
          // }
          if(data.errorCode != 0){
            Notify.error(_self.$t('lang.Notify.prompt'), data.errorMessage, false);
            return;
          }
          // 清空数据
          _self.messages = data.datas;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
             * 阅读某条消息
             * @param  {Object} item
             * @return {void}
             */
    showSingleMessage: function (item) {
      var _self = this;
      _self.messageCount--;
      _self.$router.push('/desktop/single-notification/' + item.id);
    },

    /**
             * 读取更多的消息
             */
    viewMore: function () {
      var _self = this;
      _self.$router.push('/desktop/notification');
    },

    /**
     * 阅读所有消息
     * @return {void}
     */
    receiveAllMessage: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('messageQueueResource/reveiveAll'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode != 0){
            Notify.error(_self.$t('lang.Notify.prompt'), data.errorMessage, false);
            return;
          }
          _self.getMessageCount();
          _self.getMessage();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    openWebSocket: function () {
      var _self = this;
      var url = 'WebSocket/MessageQueue/' + _self.loginInfo.userId;
      console.log('HostPageBaseURL:' + Common.getHostPageBaseURL());
      console.log('url:' + url);
      var websocketUrl = Common.getHostPageBaseURL() + '/' + url;
      console.log('websocketUrl:' + websocketUrl);
      if (websocketUrl.indexOf('https') == 0) {
        websocketUrl = websocketUrl.replace('https', 'wss').replace('/api', '');
      } else if (websocketUrl.indexOf('http') == 0) {
        websocketUrl = websocketUrl.replace('http', 'ws').replace('/api', '');
      }
      _self.webSocket = new WebSocket(websocketUrl);
      _self.webSocket.onopen = function () {
        console.log('websocket打开');
      };

      _self.webSocket.onmessage = function (message, userId) {
        console.log(
          'websocket 收到信息 : ' + message.data + ',userId:' + userId,
        );
        _self.getMessageCount();
        _self.getMessage();
      };
      _self.webSocket.onclose = function () {
        console.log('websocket关闭');
        _self.webSocket = null;
      };
      _self.webSocket.onerror = function (event) {
        console.log('websocket异常');
        console.log(event);
        _self.webSocket.close();
      };
    },
  },
};

</script>
