<template>
  <div id="app" @contextmenu.prevent>
    <template v-if="webSocketToken">
      <!-- 页眉 -->
      <header-page></header-page>
      <!-- aside && main -->
      <el-container class="el-container">
        <!-- aside -->
        <aside-page></aside-page>
        <!-- main -->
        <router-view name="main"></router-view>
      </el-container>
    </template>

    <template v-else-if="httpToken">
      <router-view name="admin"></router-view>
    </template>

    <!-- 登陆页面 -->
    <template v-else>
      <router-view name="login"></router-view>
    </template>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { createWebSocket, closeWebsocket } from './websocket/websocket.js'
import { heartBeatReq } from './api/webSocketApi'

import HeaderPage from '@/components/HeaderPage.vue'
import AsidePage from '@/components/AsidePage.vue'
// import FooterPage from '@/components/FooterPage.vue'

export default {
  name: 'App',
  data() {
    return {
      heartTimer: null // 心跳检测
    }
  },
  components: {
    HeaderPage,
    AsidePage
  },
  computed: {
    ...mapState({
      currentMode: 'currentMode',
      webSocketState: 'webSocketState',
      webSocketToken: 'webSocketToken',
      httpToken: 'httpToken'
    })
  },
  watch: {
    // 监听websocket的状态
    webSocketState(val) {
      switch (val) {
        case 0:
          console.log('正在建立连接，还没有完成 默认值')
          break
        case 1:
          console.log('websocket连接成功')
          break
        case 2:
          console.log('连接正在进行关闭握手，即将关闭')
          break
        case 3:
          console.log('连接已经关闭或者根本没有建立')
          if (this.webSocketToken) {
            this.$alert('连接已经关闭, 请重新登录！', '提示', {
              showClose: false,
              closeOnClickModal: false,
              confirmButtonText: '确定',
              type: 'warning'
            })
              .then(() => {
                // 清空websocketToken
                this.$store.commit('SET_WEBSOCKET_TOKEN', '')
              })
              .catch(() => {})
          }
          break
        default:
          break
      }
    },
    // 监听token
    webSocketToken(newToken) {
      if (newToken === '') {
        clearInterval(this.heartTimer)
        this.heartTimer = null
      }
      if (newToken) {
        // 发送心跳
        this.heartTimer = setInterval(() => {
          heartBeatReq(newToken)
        }, 30000)
      } else {
        // 转到登录页面
        this.$router.replace({ name: 'login' })
        // 如果是electron 调整窗口大小
        if (this.currentMode === 'electron') {
          // 退出登录的loading
          const loading = this.$loading({
            lock: true,
            text: '正在退出',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let ct = setTimeout(() => {
            loading.close()
            clearTimeout(ct)
            ct = null
          }, 2000)
          // 调整窗口大小
          // this.$ipcRenderer.send('operations', 'logout')
          closeWebsocket()
          let cws = setTimeout(() => {
            createWebSocket(process.env.VUE_APP_WEBSOCKET_URL)
            clearTimeout(cws)
            cws = null
          }, 1000)
        } else {
          // 重新加载页面
          window.location.reload()
        }
      }
    },
    // 监听管理端token
    httpToken(newToken) {
      if (newToken) {
        console.log('httpToken', newToken)
      } else {
        // 转到登录页面
        this.$router.replace({ name: 'login' })
        // 如果是electron 调整窗口大小
        if (this.currentMode === 'electron') {
          // 退出登录的loading
          const loading = this.$loading({
            lock: true,
            text: '正在退出',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let lct = setTimeout(() => {
            loading.close()
            clearTimeout(lct)
            lct = null
          }, 2000)
          // 调整窗口大小
          // this.$ipcRenderer.send('operations', 'logout')
        } else {
          // 重新加载页面
          window.location.reload()
        }
      }
    }
  },
  mounted() {
    // 如过浏览器支持websocket 创建连接
    if ('WebSocket' in window) {
      createWebSocket(process.env.VUE_APP_WEBSOCKET_URL)
    } else {
      //  如果浏览器不支持WebSocket
      this.$message({
        message: '您的浏览器不支持 WebSocket!，请更换浏览器！',
        type: 'error'
      })
    }
  },
  destroyed() {
    // 离开页面摧毁定时器
    clearInterval(this.heartTimer)
    this.heartTimer = null
  }
}
</script>

<style lang="scss">
@import './styles/reset.scss';
@import './styles/normalize.scss';
@import './styles/common.scss';
@import './styles/my-element-ui.scss';
@import './styles/qqface.scss';
@import '~@/assets/iconfont/iconfont.css';
@import '~@/assets/font-awesome/css/font-awesome.css';

#app {
  font-size: $font-size-base;
  color: $color-common;
  font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'SF UI Text', 'Helvetica Neue', STHeiti,
    'Microsoft Yahei', Tahoma, Simsun, sans-serif;
  height: 100%;
  overflow: hidden;

  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .el-container {
    flex: 1 1 auto;
    overflow: hidden;
    background-color: white;
  }
}
</style>
