<template>
  <aside :class="['aui-sidebar', `aui-sidebar--${$store.state.sidebarLayoutSkin}`]">
    <div class="aui-sidebar__inner">
      <el-menu :default-active="$store.state.sidebarMenuActiveName"
               :collapse="$store.state.sidebarFold"
               :unique-opened="true"
               :collapseTransition="false"
               class="aui-sidebar__menu">
            <sub-menu v-for="menu in routeList"
            :key="menu.id"
            :menu="menu" />
      </el-menu>
    </div>
  </aside>
</template>

<script>
import SubMenu from './main-sidebar-sub-menu'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import Cookies from 'js-cookie'

export default {
  data () {
    return {
      pid: '',
      parentPid: '',
      socket: '',
      stompClient: '',
      routeList: []
    }
  },
  components: {
    SubMenu
  },
  created () {
    this.$store.state.sidebarMenuList = [...window.SITE_CONFIG['menuList']]
    this.routeList = JSON.parse(JSON.stringify(window.SITE_CONFIG['menuList']))
    this.initWebSocket()
  },
  methods: {
    filterRoute (routeList, selectRoute) {
      routeList.forEach((item, index) => {
        if (item.children && item.children.length >= 1) {
          this.filterRoute(item.children, selectRoute)
        } else {
          if (item.menuCode === selectRoute.menuCode) {
            if (selectRoute.num !== 0) {
              item.num = selectRoute.num
              this.pid = `true${item.pid}`
            } else {
              item.num = selectRoute.num
              this.pid = `false${item.pid}`
            }
          }
        }
      })
      routeList.forEach(item => {
        if (item.children && item.children.length >= 1) {
          if (this.pid.indexOf('true') > -1) {
            if (item.id === this.pid.substring(4)) {
              item.redPoint = true
              if (parseInt(item.pid) !== 0) {
                this.parentPid = `true${item.pid}`
              }
            }
          } else if (this.pid.indexOf('false') > -1) {
            if (item.id === this.pid.substring(5)) {
              item.redPoint = false
              if (parseInt(item.pid) !== 0) {
                this.parentPid = `false${item.pid}`
              }
            }
          }
        }
      })
      routeList.forEach(item => {
        if (this.parentPid.indexOf('true') > -1) {
          if (item.id === this.parentPid.substring(4)) {
            item.redPoint = true
          }
        } else if (this.parentPid.indexOf('false') > -1) {
          if (item.id === this.parentPid.substring(5)) {
            item.redPoint = false
          }
        }
      })
      return routeList
    },
    initWebSocket () {
      this.connection()
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          this.stompClient.send('alive')
        } catch (err) {
          console.log('断线了: ' + err)
          this.connection()
        }
      }, 5000)
    },
    connection () {
      // 建立连接对象
      let socketUrl = window.SITE_CONFIG['apiURL'] + '/ws/menuNoticeEndpoint'
      this.socket = new SockJS(socketUrl)// 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息，注意这里用的是http而不是原生WebSocket的ws

      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket)

      // 定义客户端的认证信息,按需求配置
      let token = Cookies.get('token') || ''
      console.log('token: ' + token)
      let headers = {
        'token': token
      }
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, this.onConnected, this.onFailed)
    },
    onConnected: function (frame) {
      console.log('Connected: ' + frame)
      let topic = '/userMenuNotice/menuNoticeQueue/menu/getResponse'
      this.stompClient.subscribe(topic, this.onSubscribe)
      if (window.sessionStorage.getItem('routeList')) {
        this.routeList = JSON.parse(window.sessionStorage.getItem('routeList'))
      }
      // 获取党群议事菜单消息
      this.$http.get('/events/epdcevents/initMenuNotice').then(({ data: res }) => {}).catch(() => {
      })
    },
    onSubscribe (value) {
      this.pid = ''
      this.parentPid = ''
      const selectRoute = JSON.parse(value.body)
      const list = JSON.parse(JSON.stringify(this.$store.state.sidebarMenuList))
      if (Object.prototype.toString.call(selectRoute) === '[object Array]') {
        selectRoute.forEach(item => {
          this.$store.state.sidebarMenuList = this.filterRoute(list, item)
        })
      } else if (Object.prototype.toString.call(selectRoute) === '[object Object]') {
        this.$store.state.sidebarMenuList = this.filterRoute(list, selectRoute)
      }
      this.routeList = JSON.parse(JSON.stringify(this.$store.state.sidebarMenuList))
      window.sessionStorage.setItem('routeList', JSON.stringify(this.$store.state.sidebarMenuList))
    },
    onFailed (frame) {
      console.log('Failed: ' + frame)
    },
    disconnect () {
      if (this.stompClient != null) {
        this.stompClient.disconnect()
        console.log('Disconnected')
      }
    }
  }
}
</script>
