<template>
  <div class="avue-contail" :class="{ 'avue--collapse': isCollapse }">
    <div class="avue-header">
      <!-- 顶部导航栏 -->
      <top ref="top" />
    </div>
    <div class="avue-layout">
      <div class="avue-left">
        <!-- 左侧导航栏 -->
        <sidebar :msgCount="msgCount" />
      </div>
      <div class="avue-main">
        <!-- 顶部标签卡 -->
        <tags />
        <transition name="fade-scale">
          <search class="avue-view" v-show="isSearch"></search>
        </transition>
        <!-- 主体视图层 -->
        <div
          style="
            height: calc(100% - 30px);
            overflow-y: auto;
            overflow-x: hidden;
          "
          id="avue-view"
          v-show="!isSearch"
        >
          <keep-alive>
            <router-view class="avue-view" v-if="$route.meta.keepAlive" :msgCount="msgCount" />
          </keep-alive>
          <router-view class="avue-view" v-if="!$route.meta.keepAlive" :msgCount="msgCount" />
        </div>
      </div>
    </div>
    <div class="avue-shade" @click="showCollapse"></div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import tags from "./tags";
import search from "./search";
import top from "./top/";
import sidebar from "./sidebar/";
import admin from "@/util/admin";
import { validatenull } from "@/util/validate";
import { calcDate } from "@/util/date.js";
import { getStore } from "@/util/store.js";
import website from '@/config/website';

let socket
//初始组合式

export default {

  components: {
    top,
    tags,
    search,
    sidebar,
  },
  name: "index",
  provide() {
    return {
      index: this,
    };
  },


 computed: mapGetters(["isMenu", "isLock", "isCollapse", "website", "menu", "userInfo"]),

  data() {
    return {
      //搜索控制
      isSearch: false,
      //刷新token锁
      refreshLock: false,
      //刷新token的时间
      refreshTime: "",
      msgCount:{
        myMessageCount:'0',
        userId:'1111111'

      },
      routeinfo:{}
    };
  },
 watch: {
        $route(val){
          //发送消息
          this.socketSend()
        },
        menu(){
           this.socketSend()
        },

    },
  created() {

    //实时检测刷新token
    this.refreshToken();

  },

  mounted() {
    this.init();

  },


  props: [],
  methods: {
    showCollapse() {
      this.$store.commit("SET_COLLAPSE");
    },
    // 初始化
    init() {
      this.$store.commit("SET_SCREEN", admin.getScreen());
      window.onresize = () => {
        setTimeout(() => {
          this.$store.commit("SET_SCREEN", admin.getScreen());
        }, 0);
      };
      this.$store.dispatch("FlowRoutes").then(() => {});
    },
    //打开菜单
    openMenu(item = {}) {
      this.$store.dispatch("GetMenu", item.id).then((data) => {
        if (data.length !== 0) {

          this.$router.$avueRouter.formatRoutes(data, true);
        }

        //当点击顶部菜单后默认打开第一个菜单
        /*if (!this.validatenull(item)) {
          let itemActive = {},
            childItemActive = 0;
          if (item.path) {
            itemActive = item;
          } else {
            if (this.menu[childItemActive].length === 0) {
              itemActive = this.menu[childItemActive];
            } else {
              itemActive = this.menu[childItemActive].children[childItemActive];
            }
          }
          this.$store.commit('SET_MENU_ID', item);
          this.$router.push({
            path: this.$router.$avueRouter.getPath({
              name: (itemActive.label || itemActive.name),
              src: itemActive.path
            }, itemActive.meta)
          });
        }*/
      });
         //发送消息

    },
    // 定时检测token
    refreshToken() {
       this.setInitSocket()
      this.refreshTime = setInterval(() => {
        const token =
          getStore({
            name: "token",
            debug: true,
          }) || {};
        const date = calcDate(token.datetime, new Date().getTime());
        if (validatenull(date)) return;
        if (date.seconds >= this.website.tokenTime && !this.refreshLock) {
          this.refreshLock = true;
          this.$store
            .dispatch("refreshToken")
            .then(() => {
              this.refreshLock = false;
            })
            .catch(() => {
              this.refreshLock = false;
            });
        }
      }, 10000);
    },
      //推送系统

    setInitSocket () {
      if (!website.socket) return
        const user_id = this.userInfo.user_id;
        socket = new WebSocket(website.socket + user_id);
        socket.onopen = function (evt) {
            console.log('websocket链接成功');
        };

        socket.onclose = function (evt) {
            console.log('websocket连接已断开')
        };
        let that=this
        socket.onmessage = function ({data}) {
            if (data) {
                if(JSON.parse(data)!==null){
                   that.msgCount = JSON.parse(data)
                }
            }
            console.log("myMsg：",data)
        };
        socket.onerror = function ({data}) {
            console.log('发生错误：', data)
        };
    },

    //发送消息
    socketSend (msg) {
      if (!website.socket) return
       const user_id = this.userInfo.user_id;
        console.log('发送消息：',)
        if (socket) {
            socket.send(user_id);
        } else {
            setTimeout(()=>{
                socket.send(user_id);
            }, 1000)
        }
    }

  },

};
</script>
