<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import portal from '@/api/portal.js'
import {Toast} from 'vant'
export default {
  name: 'app',
  provide() {
    //父组件中通过provide来提供变量，在子组件中通过inject来注入变量。
    return {
      reload: this.reload,
      heartCheck: null,
      lockReconnect: false,
      token: '',
    }
  },
  components: {},
  data() {
    return {
      isRouterAlive: true, //控制视图是否显示的变量
    }
  },
  mounted() {
    // 因为resize事件在整个项目中只能监听一次，所以这里通过全局广播发送这个事件
    window.onresize = () => {
      this.$root.$emit('resize')
    }
    this.$bus.$on('login', () => {
      // this.$refs.fileUpload.getToken()
      this.initWebSocket()
    })
    window.scrollTo(0, 0)

    // 禁止ios端输入框聚焦放大
    window.onload = function () {
      document.addEventListener('gesturestart', function (e) {
        e.preventDefault()
      })
      document.addEventListener('dblclick', function (e) {
        e.preventDefault()
      })
      document.addEventListener('touchstart', function (event) {
        if (event.touches.length > 1) {
          event.preventDefault()
        }
      })
      let lastTouchEnd = 0
      document.addEventListener(
        'touchend',
        function (event) {
          var now = new Date().getTime()
          if (now - lastTouchEnd <= 300) {
            event.preventDefault()
          }
          lastTouchEnd = now
        },
        false
      )
    }
  },
  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
    },
    websocketOnopen() {
      console.log('WebSocket连接成功')
      this.heartCheck.start()
    },
    websocketOnerror(e) {
      console.log(e, 'WebSocket连接发生错误')
      this.reconnect()
    },
    websocketOnmessage(e) {
      // console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.cmd == 'dict') {
        // 重载字典
        this.getSysDict()
      }
      this.heartCheck.reset()
    },
    websocketOnclose(e) {
      console.log('connection closed (' + e.code + ')')
      this.reconnect()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      if (this.lockReconnect) return
      this.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(() => {
        console.info('尝试重连...')
        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';

/deep/ .van-nav-bar__text {
  font-size: 16px;
}

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

#app {
  width: 100vw;
  // height: calc(100% - 110PX);
  overflow: auto;
  // padding-top: 50PX;
}

#app::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

@media print {
  #app {
    height: auto !important;
  }

  .no-print {
    display: none;
  }

  .base-main {
    background: #ffffff !important;
    padding: 0px !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;
}
.tabbaritem {
  font-family: Helvetica;
}
.tabbaritem img {
  width: 25px;
  height: 25px;
  margin-top: 3px;
}

.svg g polyline {
  stroke: red;
}
</style>
