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

<script>
import axios from 'axios'
import * as signalR from "@microsoft/signalr";
import withUrl from "@/config/withUrl";
import {MessagePackHubProtocol} from "@microsoft/signalr-protocol-msgpack";

export default {
  data() {
    return {
      connection: null
    }
  },
  methods: {
    checkVersion () {
      axios.defaults.headers.get['Cache-Control'] = 'no-cache'
      axios.get('/version.json').then(res => {
        let version = String(res.data.version)
        console.log(version, localStorage.getItem('_version'))
        if (version !== localStorage.getItem('_version')) {
          console.log('版本更新')
          localStorage.setItem('_version', version)
          window.location.reload()
        }
      })
    },
    SRConnection() {
      let _this = this
      this.connection = new signalR.HubConnectionBuilder()
          .withUrl(`${withUrl}/plcHub?groupName=illegalPushGroup${sessionStorage.getItem('plcCode')}`)
          .withAutomaticReconnect()
          .withHubProtocol(new MessagePackHubProtocol())
          .build()
      // 监听扫码
      this.connection.on('illegalStockInOut', res => {
        console.log('异常出入库----------------')
        console.log(res)
        this.connection.invoke('ReturnSureMes', res.MesId)
        if (!['warning-list', 'check'].includes(this.$route.name)) {
          this.$router.push({
            name: 'check'
          })
        }
      })
      this.connection.start().then(() => {
        console.log('连接成功--global')
      }).catch(err => {
        console.log('err--')
        console.log(err)
        re_start()
      })
      // 监听网络断开
      this.connection.onclose(() => {
        this.connection = null
        console.log('网络已断开！global')
        // this.$Message.error('网络连接断开')
        // this.$router.go(0)
      })
      // 异常重启
      async function re_start() {
        try {
          await _this.connection.start()
        } catch (err) {
          setTimeout(() => re_start(), 5000)
        }
      }
    }
  },
  mounted() {
    this.SRConnection()
    this.checkVersion()
    /* 轮询监听是否发布新版本 */
    if (process.env.NODE_ENV !== 'development') {
      this.checkVersion()
      setInterval(() => {
        this.checkVersion()
      }, 10000)
    }
  }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>
