<template>
  <el-container class="fullheight">
    <template v-if="navMode == 'sideMenu'">
      <el-container class="overhidden">
        <!-- <side-menu
          :menuShow.sync="menuShow"
          :navMode="navMode"
          :bizMenuAlias="bizMenuAlias"
        /> -->
        <el-main :class="['main-container', {'menu-hidden': !menuShow}]">
          <Navigator
            :menuShow.sync="menuShow"
            :navMode="navMode"
            :bizMenuAlias="bizMenuAlias"
          />
          <div class="side-menu-Main">
            <side-menu
              class="main-menu"
              :menuShow.sync="menuShow"
              :navMode="navMode"
              :bizMenuAlias="bizMenuAlias"
            />
            <Main class="page-main-wrapper short"></Main>
          </div>
        </el-main>
      </el-container>
    </template>
    <template v-else-if="navMode == 'topSideMenu-LR'">
      <el-container class="overhidden">
        <side-menu
          :menuShow.sync="menuShow"
          :navMode="navMode"
          :bizMenuIndex="bizMenuIndex"
          :bizMenuAlias="bizMenuAlias"
        />
        <el-main :class="['main-container', {'menu-hidden': !menuShow}]">
          <Navigator
            :menuShow.sync="menuShow"
            :navMode="navMode"
            :aliasPath="aliasPath"
            :bizMenuIndex="bizMenuIndex"
            :bizMenuAlias="bizMenuAlias"
          />
          <Main class="page-main-wrapper short"></Main>
        </el-main>
      </el-container>
    </template>
    <template v-else-if="navMode == 'topSideMenu-UD'">
      <div class="UD-container">
        <Navigator
          :menuShow.sync="menuShow"
          :navMode="navMode"
          :aliasPath="aliasPath"
          :bizMenuIndex="bizMenuIndex"
          :bizMenuAlias="bizMenuAlias"
        />
        <div class="UD-main">
          <side-menu
            :menuShow.sync="menuShow"
            :navMode="navMode"
            :bizMenuIndex="bizMenuIndex"
            :bizMenuAlias="bizMenuAlias"
            :showLogo="false"
          />
          <el-main :class="['main-container', {'menu-hidden': !menuShow}]">
            <Main class="page-main-wrapper"></Main>
          </el-main>
        </div>
      </div>
    </template>
    <template v-else-if="navMode == 'topMenu'">
      <el-container style="overflow-x: hidden; overflow-y: hidden">
        <el-main
          class="main-container"
          :class="$route.meta.isHome ? 'home-page' : ''"
        >
          <Navigator
            :menuShow.sync="menuShow"
            :navMode="navMode"
            :bizMenuAlias="bizMenuAlias"
          />
          <Main class="page-main-wrapper short"></Main>
        </el-main>
      </el-container>
    </template>
  </el-container>
</template>

<script>
import Navigator from './Navigator.vue'
import SideMenu from './SideMenu.vue'
import Main from './Main.vue'
export default {
  components: {
    Navigator,
    SideMenu,
    Main
  },
  data() {
    return {
      menuShow: true, // 侧边菜单收折flag
      transitionName: 'fold-right', // 页面切换动画名称
      navMode: 'sideMenu', // sideMenu 侧边菜单 | topMenu 顶部菜单 | topSideMenu-UD 顶部侧边联动菜单上下布局 | topSideMenu-LR 顶部侧边联动菜单左右布局
      aliasPath: [], // 当前路由菜单别名全路径
      bizMenuIndex: 0, //业务菜单一级属于前台菜单层级中的第几级
      bizMenuAlias: 'normal', // 业务菜单根别名
      showHeader: true,
      heartCheck: {},
      isCurrentWindow: true
    }
  },
  created() {
    // 在外框架中获取所有前台菜单，组件中不再请求，直接读取vuex中数据
    this.getMenus()
    this.heartCheckFun()
    this.initWebSocket()
  },
  mounted() {
    window.onresize = () => {
      this.$root.$emit('resize')
    }
    this.$bus.$on('login', () => {
      this.heartCheckFun()
    })
  },
  beforeDestroy() {
    this.isCurrentWindow = false
  },
  watch: {
    $route: 'activeAlias'
  },
  methods: {
    getMenus() {
      this.menuAll = []
      this.$store.dispatch('menu/actionFrontMenus').then(data => {
        this.menuAll = data
        this.menuReady = true
        this.activeAlias()
      })
    },
    activeAlias() {
      // 如果是顶部侧边联动部菜单则页面刷新时需要根据当前路由别名找到对应的父级节点
      if (
        this.navMode == 'topSideMenu-LR' ||
        this.navMode == 'topSideMenu-UD'
      ) {
        // 根据路由别名刷新找到对应的父级菜单全路径
        let fullPath = this.$route.path
        let path = fullPath.split('/')
        let urlAnchor = path[path.indexOf('platLayout') + 1]
        let aliasPath = []
        this.filterRootParant(this.menuAll, urlAnchor, aliasPath)
        this.aliasPath = aliasPath
      }
      this.$bus.$emit('menuPathReady', this.aliasPath)
    },
    // 找到对应的根父级菜单
    filterRootParant(data, urlAnchor, result) {
      for (let item of data) {
        if (item.alias === urlAnchor) {
          // 如何找到了则说明这里是最后一级可以返回了，将查找到的目标数据加入结果数组中
          // 可根据需求unshift(item.id)或unshift(item)
          result.unshift(item.alias)
          return true
        } else if (item.children && item.children.length > 0) {
          // 否则继续在子节点中查找
          let isFind = this.filterRootParant(item.children, urlAnchor, result)
          // 如果在当前节点的子字节点中找到了则将当前节点加入到结果数组中
          if (isFind) {
            result.unshift(item.alias)
            return true
          }
        }
      }
      // 没找到目标
      return false
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      const token = this.$store.state.login.currentUser.token
      const url =
        window.context.WebSocket.replace('https://', 'wss://').replace(
          'http://',
          'ws://'
        ) + '/websocket'
      // ?token=' +
      // token
      console.log(url, 'url')
      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) {
      let data = eval('(' + e.data + ')') //解析对象   eval('(' + e.data + ')');
      // 竞拍报价
      if (this.isCurrentWindow) {
          // console.log('-----接收消息-------', data)
          this.$bus.$emit('quo', data)
      }
      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
      //心跳检测,每10分钟心跳一次
      this.heartCheck = {
        timeout: 1000 * 60 * 10,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function() {
          clearTimeout(this.timeoutObj)
          this.start()
          return this
        },
        start: function() {
          var self = this
          this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            const account = JSON.parse(sessionStorage.getItem('currentUser'))
              .account
            that.websocketSend("{'messageType':'ping','message':'web'}")
            console.info('客户端发送心跳')
            //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
            //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            //}, self.timeout)
          }, this.timeout)
        }
      }
    }
  }
}
</script>

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

.overhidden {
  overflow: hidden;
}
.side-menu-Main {
  display: flex;
  height: 100%;
  .main-menu {
    z-index: 100;
  }
  .page-card {
    flex: 1;
  }
}
.UD-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
}
.UD-main {
  width: 100%;
  height: $--main-height;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
}
.page-main-wrapper {
  height: 100%;
}
.page-main-wrapper.short {
  height: $--main-height;
}
.main-container {
  overflow: hidden;
  width: $--main-width;
  height: 100%;
  padding: 0px;
  background: url(../../assets/img/loading.gif) no-repeat 50%
    $--background-color-base;
  transition: width 0.2s linear;
}
.main-container.menu-hidden {
  width: $--main-width-lager;
}
</style>
