<template>
    <div :class="{'has-logo':showLogo}" :style="{ backgroundColor: settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground }">
        <logo v-if="showLogo" :collapse="isCollapse" />
        <el-scrollbar :class="settings.sideTheme" wrap-class="scrollbar-wrapper">
            <el-menu
                :default-active="activeMenu"
                :collapse="isCollapse"
                :background-color="settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground"
                :text-color="settings.sideTheme === 'theme-dark' ? variables.menuColor : variables.menuLightColor"
                :unique-opened="true"
                :active-text-color="settings.theme"
                :collapse-transition="false"
                mode="vertical"
            >
                <sidebar-item
                    v-for="(route, index) in sidebarRouters"
                    :key="route.path  + index"
                    :item="route"
                    :base-path="route.path"
                />
            </el-menu>
        </el-scrollbar>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import Logo from "./Logo";
import SidebarItem from "./SidebarItem";
import variables from "@/assets/styles/variables.scss";
import {Message} from "element-ui";
import router from "@/router";

export default {
    components: { SidebarItem, Logo },
    computed: {
        ...mapState(["settings"]),
        ...mapGetters(["sidebarRouters", "sidebar"]),
        activeMenu() {
            const route = this.$route;
            const { meta, path } = route;
            // if set path, the sidebar will highlight the path you set
            if (meta.activeMenu) {
                return meta.activeMenu;
            }
            return path;
        },
        showLogo() {
            return this.$store.state.settings.sidebarLogo;
        },
        variables() {
            return variables;
        },
        isCollapse() {
            return !this.sidebar.opened;
        }
    },
  data() {
    // return {
    //   timer: null,
    //   intervalId:null
    // }

    return{
      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 1 * 1000, //20秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      sessionid:null,
      jumpsign:'1'
    }


  },
  created() {
    // //页面刚进入时开启长连接
    this.initWebSocket();

  },
  destroyed() {
    //页面销毁时关闭长连接
    clearTimeout(this.timeoutObj);
    // console.log('销毁页面')
    this.websocketclose();

  },
  methods:{
    initWebSocket() {
      //建立连接
      //初始化weosocket
      let tokenStr = localStorage.getItem("jy")
      let visitPort
      if (process.env.NODE_ENV=='development'){
        visitPort = '443'
      }
      else {
        visitPort = '443'
      }
      let wsuri = 'wss:'+location.host.split(':')[0]+ ':'+visitPort+'/websocket/testsocket?JY='+tokenStr.split("&")[0]+'&'+'JySign='+tokenStr.split("&")[1];
      //建立连接
      this.websock = new WebSocket(wsuri);
      //连接成功
      this.websock.onopen = this.websocketonopen;
      //连接错误
      this.websock.onerror = this.websocketonerror;
      //接收信息
      this.websock.onmessage = this.websocketonmessage;
      //连接关闭
      this.websock.onclose = this.websocketclose;
    },
    start() {
      //开启心跳
      var self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      // self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function() {
        self.websock.send("heartbeat");
      }, self.timeout);
    },
    websocketonopen() {
      //连接成功事件
      this.websocketsend(this.sessionid);
      //提示成功
      // console.log("连接成功", 3);
      //开启心跳
      this.start();
    },
    websocketonerror(e) {
      // Message({
      //   message: '后端超出探活数量，不允许再次连接',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      this.jumpsign='0'
      this.$alert('后端超出探活数量，不允许再次连接!', {
        confirmButtonText: '确定',
        callback: action => {
          location.replace('about:blank');
        }
      });

      // this.$router.push('/404')
      //连接失败事件
      //错误
      // console.log("WebSocket连接发生错误");
      //重连
      // this.reconnect();
    },
    websocketclose(e) {
      //连接关闭事件
      //提示关闭
      if (this.jumpsign=='1'){
        this.$router.go(0)
        // console.log("连接已关闭");
      }

      //重连
      // this.reconnect();
    },
    websocketonmessage(event) {
      //接收服务器推送的信息
      //打印收到服务器的内容
      // console.log("收到服务器信息",event.data);
      let data=event.data
      this.sessionid = data
      //收到服务器信息，心跳重置
      this.start()
    },
    websocketsend(msg) {
      //向服务器发送信息
      this.websock.send(msg);
    }

  }
};
</script>
