<template>
  <el-container>
    <el-aside :class="menuClass" width="">
      <el-menu :default-active="menuActiveIndex" :router="true" :collapse="isCollapse" :unique-opened="true">
        <div class="site-title">
          <h1>Settlement system background<!-- 结算系统后台 --></h1>
        </div>
        <div class="user-profile">
          <img src="../../static/img/avatar/1.png" alt="" class="profile-avatar img-circle">
          <el-dropdown>
      <span class="el-dropdown-link">
        {{adminName}} <i class="el-icon-caret-bottom el-icon--right"></i>
      </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-sort" @click.native="onChangePassword">Reset password<!-- 重置密码 --></el-dropdown-item>
              <el-dropdown-item icon="el-icon-switch-button" @click.native="onLogout">Log out<!-- 退出登录 --></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <template v-for="parent in menu">
          <el-submenu :index="'/'+parent.routePath" v-if="parent.child.length">
            <template slot="title">
              <i :class="parent.icon"></i>
              <span>{{parent.name}}</span>
            </template>
            <el-menu-item-group title="">
              <el-menu-item :index="'/'+child.routePath" v-for="child in parent.child" :key="'/'+child.routePath">
                <a class="left-menu-a" :href="'#/'+child.routePath">{{child.name}}</a>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-menu-item :index="'/'+parent.routePath" v-else>
            <i :class="parent.icon"></i>
            <span>{{parent.name}}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header>
        <ul class="al-left layout-menu-left">
          <li class="mobile-menu">
            <el-button type="text" @click="onMobileMenu"><i class="el-icon-s-fold"></i></el-button>
          </li>
          <li class="scale-menu">
            <el-button type="text" @click="onMenu"><i class="el-icon-s-fold"></i></el-button>
          </li>
          <li class="top-message button" v-show="false">
            <el-button type="text" @click="onMessage"><i class="el-icon-message"></i></el-button>
            <transition name="custom-classes-transition" enter-active-class="animated bounceInDown">
              <div class="top-message-card" v-if="messageShow">

              </div>
            </transition>
          </li>
          <li>
            <h4>{{contentTitle}}</h4><!-- 控制台 -->
          </li>
        </ul>
        <div style="text-align: right;font-size: 14px;">
          Current System Time<!-- 当前系统时间 -->：{{nowDateTime}}&nbsp;&nbsp;&nbsp;&nbsp;
          Current Period<!-- 当期期数 -->：<b class="text-danger">{{periodNum}}</b>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, index) in breadcrumb" :to="{ path: item.path }" :key="index">
              {{item.title}}<!-- 顶部面包屑 -->
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <div :class="'breadcrumb-box '+menuClass" v-show="false">
        <div class="breadcrumb-content">
        </div>
      </div>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <div style="position: fixed;right:4px;bottom: 10px;z-index: 999">
      <p class="mar-btm" v-if="showBackToUp">
        <el-tooltip class="item" effect="dark" content="Top" placement="top-start"><!-- 回到顶部 -->
          <el-button type="primary" @click="backTop" circle plain><i class="fa fa-arrow-up"></i></el-button>
        </el-tooltip>
      </p>
      <p>
        <el-tooltip class="item" effect="dark" content="previous page" placement="top-start"><!-- 返回上一页 -->
          <el-button type="primary" @click="$router.go(-1)" circle plain><i class="fa fa-arrow-left"></i></el-button>
        </el-tooltip>
      </p>
    </div>
  </el-container>
</template>
<script>
import {WEBSOCKET_HOST} from '@/utils/config'
import userInfo from '@/utils/userInfo'
import network from '@/utils/network'
import tool from '@/utils/tool'
import Waves from '@/static/plugins/waves/waves.js'
import store from '@/utils/vuexStore'
import baseInfo from '@/utils/baseInfo'
import initRegion from '@/utils/region'
import '@/static/plugins/css/font-awesome.min.css'

export default {
  name: 'layout',
  beforeCreate () {
    let vueObj = this
    // 检测用户是否已经登录，如果已经登录则直接跳转到控制台页
    if (!userInfo.hasLogin()) {
      this.$router.push('/login')
      return
    }
    // websocket连接
    let wsServer = WEBSOCKET_HOST
    let webSocket = new WebSocket(wsServer)
    store.state.socket.socketObj = webSocket
    webSocket.onopen = function (evt) {
      let userId = userInfo.userId()
      let sendData = {app: 'admin', userId: userId}
      webSocket.send(JSON.stringify(sendData))
    }
    webSocket.onmessage = function (env) {
      let data = JSON.parse(env.data)
      if (data.handle === 'adminAsync') {
        vueObj.$message({
          message: data.message,
          type: data.success ? 'success' : 'error',
          showClose: !data.success,
          duration: data.success ? 3000 : 0
        })
        if (store.state.socket.onMessageCallback !== null) {
          store.state.socket.onMessageCallback()
        }
      } else if (data.handle === 'adminAsyncPercent') {
        if (store.state.socket.onMessageCallback !== null) {
          store.state.socket.onMessageCallback(data)
        }
      }
    }
    // 获取系统相关信息
    // network.getData(`site/base-info`).then(response => {
    //     store.state.baseInfo.decLevels = response.decLevels;
    //     store.state.baseInfo.empLevels = response.empLevels;
    //     store.state.baseInfo.adminRoles = response.adminRoles;
    //     store.state.baseInfo.menu = response.menu;
    // });
    // 获取地区信息
    initRegion(this)
  },
  mounted () {
    Waves.init()
    this.calcTime()
    Waves.attach('.waves-btn')
    this.activeNav()
    this.$nextTick(function () {
      window.addEventListener('scroll', this.scrollToTop, true)
    })
    // 取消菜单a标签的默认动作
    let allLeftMenuA = document.getElementsByClassName('left-menu-a')
    for (let i in allLeftMenuA) {
      if (allLeftMenuA[i].onclick) {
        allLeftMenuA[i].onclick = function (e) {
          e.preventDefault()
        }
      }
    }
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop)
  },
  data () {
    return {
      isCollapse: false,
      menuActiveIndex: this.$route.meta.highLight || this.$route.path,
      mainTitle: this.$route.meta.title,
      messageShow: false,
      profileShow: false,
      adminNameShow: true,
      menuClass: '',
      adminName: userInfo.adminName(),
      nowTime: tool.getTimestamp(),
      periodNum: baseInfo.nowPeriodNum(),
      showBackToUp: false
    }
  },
  computed: {
    nowDateTime: function () {
      // console.log(this.nowTime)
      return this.$moment(this.nowTime * 1000).utcOffset('+0100' ).format('YYYY-MM-DD HH:mm:ss') + ' (WAT)'
      // return tool.formatDate(this.nowTime)
    },
    menu: function () {
      return baseInfo.menu()
    },
    contentTitle: function () {
      return this.$route.meta.title
    },
    breadcrumb: function () {
      let breadcrumbArr = []
      for (let i in this.$route.meta.breadcrumb) {
        breadcrumbArr.push(this.$route.meta.breadcrumb[i])
      }
      breadcrumbArr.push({title: this.$route.meta.title, path: ''})
      return breadcrumbArr
    },
  },
  methods: {
    calcTime () {
      let obj = this
      setInterval(function () {
        obj.nowTime += 1
      }, 1000)
    },
    onMenu () {
      if (this.isCollapse) {
        this.isCollapse = false
        document.getElementsByTagName('body')[0].className = ''
      } else {
        this.isCollapse = true
        document.getElementsByTagName('body')[0].className = 'content-wrapper'
      }
    },
    onMobileMenu () {
      if (this.menuClass === 'show-menu') {
        this.menuClass = ''
      } else {
        this.menuClass = 'show-menu'
      }
    },
    onMessage () {
      this.messageShow = !this.messageShow
    },
    onProfile () {
      this.profileShow = !this.profileShow
    },
    onLogout () {
      userInfo.clear()
      this.$router.push('/login')
    },
    onChangePassword () {
      this.$router.push('/admin/change-password')
    },
    onCloseProfile () {
      this.profileShow = false
    },
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop () {
      let that = this
      let timer = setInterval(() => {
        let _speed = Math.floor(-that.scrollTop / 5)
        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + _speed
        if (that.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 16)
    },
    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop () {
      let that = this,
        _scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      that.scrollTop = _scrollTop
      if (that.scrollTop > 60) {
        that.showBackToUp = true
      } else {
        that.showBackToUp = false
      }
    },
    activeNav () {
      let currentRouteMeta = this.$route.meta
      if (typeof currentRouteMeta['activeRoute'] !== 'undefined') {
        this.menuActiveIndex = currentRouteMeta['activeRoute']
      } else {
        this.fixedMenuActive()
      }
    },
    fixedMenuActive () {
      let module = this.$route.matched[1].path
      // fixed shop nav
      // if(module === '/shop') module = '/shop/goods';
      this.menuActiveIndex = module + '/index'
    }
  }
}
</script>

<style>
  @import '../../static/css/animate.css';
  @import '../../static/plugins/waves/waves.css';
  @import '../../static/css/style.css';

  .el-menu-item-group__title {
    display: none;
  }
  .el-menu-item .left-menu-a {
    color: #3e4d6c;
  }
  .el-breadcrumb{padding-left: 20px;}
</style>
