<template>
  <div id="app">
    <router-view v-if="isRouterAlive" />
    <!-- <el-container class="is-vertical fullheight">
  <template v-if="!$route.meta.single">
    <el-header
      class="theme_color no-print"
      v-if="$route.name && $route.name != 'templateFormSingle' && $route.name != 'onlineForm' && $route.name != 'doneReadOnly'"
      height="48px"
      style="padding: 0 10px;"
    >
      <navigator />
    </el-header>
    <el-main class="base-main hidden_scroll fullheight" name="app-base-main" > <router-view v-if="isRouterAlive" style="margin: 0 auto;height: 100%;" /> </el-main>
  </template>
  <router-view v-if="$route.meta.single" />
</el-container> -->
  </div>
</template>

<script>
// import Navigator from '@/views/index.vue'
import portal from '@/api/portal.js'

export default {
  name: 'app',
  provide() {
    //父组件中通过provide来提供变量，在子组件中通过inject来注入变量。
    return {
      reload: this.reload
    }
  },
  components: {
    // Navigator,
  },
  data() {
    return {
      isRouterAlive: true, //控制视图是否显示的变量
      lockReconnect: false,
      connectCount: 0,
      heartCheck: null
    }
  },
  mounted() {
    // 因为resize事件在整个项目中只能监听一次，所以这里通过全局广播发送这个事件
    window.onresize = () => {
      this.$root.$emit('resize')
    }
    // this.$bus.$on('login', () => {
    //     this.initWebSocket()
    // })
    this.$bus.$on('getWebsocketStatus', () => {
      this.websocketStatus()
    })
  },
  created() {
    const that = this
    // that.$store._vm.$root.$on('login-completed', function () {
    //     that.getSysDict()
    //     //获取静态资源目录
    //     that.$store.dispatch('menu/getStaticMenus')
    //     // 获取用户接口权限
    //     that.$store.dispatch('menu/getCurrentUserMethodAuth')
    //     // 获取动态资源目录
    //     // that.$store.dispatch('menu/getSyncMenus')
    // })
    this.heartCheckFun()
    this.initWebSocket()
  },
  methods: {
    reload() {
      this.isRouterAlive = false
      setTimeout(() => {
        this.isRouterAlive = true
      }, 10)
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var url =
        window.context.WebSocket.replace('https://', 'wss://').replace(
          'http://',
          'ws://'
        ) + '/websocket'
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketStatus() {
      let status = ''
      if (this.websock && this.websock.readyState) {
        status = this.websock.readyState
      }
      this.$bus.$emit('websocket-status', status)
    },
    websocketOnopen() {
      console.log('WebSocket连接成功')
      this.heartCheck.start()
      this.websocketStatus()
    },
    websocketOnerror(e) {
      console.log(e, 'WebSocket连接发生错误')
      this.reconnect()
      this.websocketStatus()
    },
    websocketOnmessage(e) {
      console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.cmd == 'dict') {
        // 重载字典
        this.getSysDict()
      }
      // 接收报警消息
      if (data.messageType === 'alarm') {
        this.$bus.$emit('alarm', data)
      }
      this.$bus.$emit('websocket-message', data)
      this.heartCheck.reset()
    },
    websocketOnclose(e) {
      console.log('connection closed (' + e.code + ')')
      this.reconnect()
      this.websocketStatus()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      if (this.lockReconnect || this.connectCount >= 3) return
      this.lockReconnect = true
      this.connectCount++
      //没连接上会一直重连，设置延迟避免请求过多

      setTimeout(() => {
        console.log('尝试重新连接WebSocket（第' + this.connectCount + '次）')
        this.initWebSocket()
        this.lockReconnect = false
      }, 5000)
    },
    heartCheckFun() {
      var that = this
      //心跳检测,每10s心跳一次
      this.heartCheck = {
        timeout: 10000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function() {
          clearTimeout(this.timeoutObj)
          this.start()
          return this
        },
        start: function() {
          var self = this
          this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            that.websocketSend("{'messageType':'heartcheck'}")
            // console.info('客户端发送心跳')
            //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
            //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            //}, self.timeout)
          }, this.timeout)
        }
      }
    },
    //---------websocket 接收字典被修改的信息，请求新字典数据。-------------

    getSysDict() {
      portal.getSysDict().then(data => {
        if (data) {
          sessionStorage.setItem('dict_data', JSON.stringify(data))
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.theme_color {
  background-color: $--theme-color;
}

#app {
  // background: #f5f5f5;
}

@media print {
  #app {
    height: auto !important;
  }
  .no-print {
    display: none;
  }
  .base-main {
    background: #ffffff !important;
    padding: 0 !important;
  }
}

.base-main {
  // background-color: $--bg-color-page;
  padding-top: 8px;
}

.hidden_scroll {
  &::-webkit-scrollbar {
    width: 0;
    background-color: transparent;
  }
}

.base-footer {
  border-top: 1.5px solid #ededed;
}

.el-dialog__header {
  padding: 10px !important;
  background: #f8f8f8;
  border-bottom: 1px solid #eee;
}

.el-dialog__header > .el-dialog__title {
  font-size: 15px;
}

.el-dialog__header > .el-dialog__headerbtn {
  top: 13px;
}

.el-dialog__header .el-dialog__close {
  font-weight: bold;
}

.el-dialog__footer {
  border-top: 1px solid #eee;
}

.rotating {
  animation: rotating 1.7s linear infinite;
}
</style>
