
<template>
  <el-container>
    <el-header> <headerNav/> </el-header>
    <el-container class="home_bd">
      <el-button class="expand_retract_icon retract" type="primary" @click="expandRetractEvent($event)"/>
      <el-aside v-if="show" class="home_left" width="15.23%">
        <div class="left_menu" style="height: 100%">
          <el-row class="tac" style="height: 100%">
            <el-col style="height: 100%;text-align:left;" >
              <el-menu
                :default-active = "String(activeIndex)"
                router
                class="el-menu-vertical-demo"
                background-color="#ffffff"
                box-shadow="2px 0px 6px 0px	rgba(0, 21, 41, 0.12)"
                text-color="#000000"
                active-text-color="#1890ff"
                style="height: 100%;"
              >
                <el-menu-item index="/home/homepage" class="router_link" tag="li" >
                  <i class="el-icon summary_hospital"/>
                  <span >首页全院汇总</span>
                </el-menu-item>
                <el-menu-item index="/home/depart" class="router_link" tag="li" >
                  <i class="el-icon depart_management "/>
                  <span >病区项目统计</span>
                </el-menu-item>
                <el-menu-item index="/home/layout" class="router_link" tag="li" >
                  <i class="el-icon layout_config "/>
                  <span >首页布局配置</span>
                </el-menu-item>
                <el-menu-item index="/home/project" class="router_link" tag="li" >
                  <i class="el-icon project_config "/>
                  <span >首页项目配置</span>
                </el-menu-item>
                <el-menu-item index="/home/education" class="router_link" tag="li" >
                  <i class="el-icon education_train "/>
                  <span >教育培训管理</span>
                </el-menu-item>
                <el-menu-item index="/home/device" class="router_link" tag="li" >
                  <i class="el-icon equip_management "/>
                  <span >设备管理</span>
                </el-menu-item>
                <el-menu-item index="/home/kettle" class="router_link" tag="li" >
                  <i class="el-icon kettle_monitor "/>
                  <span >Kettle监控</span>
                </el-menu-item>
                <el-menu-item index="/home/setting" class="router_link" tag="li">
                  <i class="el-icon system_setting "/>
                  <span >系统设置</span>
                </el-menu-item>
                <el-menu-item index="/home/center" class="router_link" tag="li" >
                  <i class="el-icon personal_center "/>
                  <span >个人中心</span>
                </el-menu-item>
              </el-menu>
            </el-col>
          </el-row>
        </div>
      </el-aside>
      <el-main class="home_container">
        <el-tabs v-model="activeTab" type="card" @tab-remove="removeTab" @tab-click="tabClickEvent">
          <!-- <el-tab-pane><span slot="label" class="crumb_home_icon"/></el-tab-pane>-->
          <el-tab-pane
            v-for="item in tabsItem"
            :key="item.name"
            :label="item.title"
            :name="item.name"
            :closable="item.closable"
            :ref="item.ref">
            <component :is="item.content" style="width:100%;height:100%" class="home_container_content"/>
          </el-tab-pane>
        </el-tabs>
        <!--<router-view/>-->
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import './common/common.css'
import Bus from './common/bus.js'
import headerNav from './common/header'
import homepage from './middle/home-page/home-middle'
import depart from './middle/depart/depart'
import layout from './middle/layout/layout-middle'
import project from './middle/project/project-middle'
import kettle from './middle/kettle/kettle-monitor'
import education from './middle/education-train/education-train'
import device from './middle/device/device-middle'
import { isBlank } from './common/common'
export default {
  components: {
    headerNav,
    homepage,
    depart,
    layout,
    project,
    education,
    device
  },

  data: function() {
    return {
      show: true,
      isRouterAlive: true,
      tabList: [],
      activeTab: '1',
      tabIndex: 1, // tab目前显示数
      tabsItem: [
        {
          title: '首页',
          name: '1',
          closable: false,
          ref: 'tabs',
          content: 'homepage'
        }
      ],
      tabsPath: [{
        name: '1',
        path: '/home/homepage'
      }]
    }
  },
  computed: {
    activeIndex() { // 当前激活的导航
      if (this.$route.path.split('/').length >= 4) {
        console.log(this.$route.path.substring(0, this.$route.path.lastIndexOf('/')))
        return this.$route.path.substring(0, this.$route.path.lastIndexOf('/'))
      } else {
        console.log(this.$route.path)
        return this.$route.path
      }
    }
  },
  watch: {
    '$route': function(to) { // 监听路由的变化，动态生成tabs
      console.log(to)
      console.log(this.tabsItem)
      let flag = true // 判断是否需要新增页面
      const path = to.path
      var _this = this
      if (Object.keys(to.matched).length != 0) {
        console.log(this.$refs.tabs)
        console.log(this.$refs.tabs.length)
        for (let i = 0; i < this.$refs.tabs.length; i++) {
          // 首页不判断 如果页面已存在，则直接定位当页面，否则新增tab页面
          console.log(this.$refs.tabs[i].label)
          console.log(to.name)
          if (this.$refs.tabs[i].label == to.name) {
            console.log(this.tabsPath)
            this.activeTab = this.$refs.tabs[i].name // 定位到已打开页面.
            flag = false
            break
          }
        }
        // 新增页面
        if (flag) {
          console.log(to)
          // 获得路由元数据的name和组件名
          const thisName = to.name
          let thisComp = to.path.split('/')[2]
          if (to.path.split('/').length >= 4) {
            thisComp = to.path.split('/')[3]
          }
          // 对tabs的当前激活下标和tabs数量进行自加
          const newActiveIndex = ++this.tabIndex + ''
          console.log(String(newActiveIndex))
          // 动态双向追加tabs
          this.tabsItem.push({
            title: thisName,
            name: String(newActiveIndex),
            closable: true,
            ref: 'tabs',
            content: thisComp
          })
          this.activeTab = newActiveIndex
          /*
            * 当添加tabs的时候，把当前tabs的name作为key，path作为value存入tabsPath数组中
            * key:tabs的name
            * value:tabs的path
            * {
            *   key: name,
            *   value: path
            * }
            * ///后面需要得到当前tabs的时候可以通过当前tabs的name获得path
            * */
          if (this.tabsPath.indexOf(path) == -1) {
            this.tabsPath.push({
              name: newActiveIndex,
              path: path
            })
          }
        }
      }
    }
  },
  mounted() {
    /*
      * 监听页面刷新事件
      * 页面刷新前 需要保存当前打开的tabs的位置，刷新后按刷新前的顺序展示
      * 使用js的sessionStorage保存刷新页面前的数据
      * */
    window.addEventListener('beforeunload', e => {
      sessionStorage.setItem('tabsItem', JSON.stringify({
        currTabsItem: this.tabsItem.filter(item => item.name !== '1'),
        currTabsPath: this.tabsPath.filter(item => item.name !== '1'),
        currActiveTabs: this.activeTab,
        currIndex: this.tabIndex
      }))
    })
  },
  created() {
    /*
      * 使用js的sessionStorage读取刷新前的数据，并按刷新前的tabs顺序重新生成tabs
      * */
    const sessionTabs = JSON.parse(sessionStorage.getItem('tabsItem'))
    if (isBlank(sessionTabs)) { return }
    if (sessionTabs.currTabsItem.length != 0 && sessionTabs.currTabsPath.length != 0) {
      for (let i = 0; i < sessionTabs.currTabsItem.length; i++) {
        this.tabsItem.push({
          title: sessionTabs.currTabsItem[i].title,
          name: sessionTabs.currTabsItem[i].name,
          closable: true,
          ref: sessionTabs.currTabsItem[i].ref,
          content: sessionTabs.currTabsItem[i].content
        })
      }
      for (let j = 0; j < sessionTabs.currTabsPath.length; j++) {
        this.tabsPath.push({
          name: sessionTabs.currTabsPath[j].name,
          path: sessionTabs.currTabsPath[j].path
        })
      }
      this.activeTab = sessionTabs.currActiveTabs
      this.tabIndex = sessionTabs.currIndex
      // 避免强制修改url 出现浏览器的url输入框的路径和当前tabs选中的路由路径不匹配
      const activePath = this.tabsPath.filter(item => item.name == this.activeTab)
      this.$router.push({
        path: activePath[0].path
      })
    }
  },
  methods: {
    handleSelect(name, title) {
      Bus.$emit('tagItem', { 'name': name, 'title': title })
      this.tabList.push({ 'name': name, 'title': title })
      console.log(this.tabList)
    },
    expandRetractEvent(event) {
      const target = event.target
      this.show = !this.show
      console.log(this.show)
      if (this.show) {
        $(target).animate({ left: '14.05%' }, 1)
        $(target).removeClass('expand').addClass('retract')
        $('.el-main.home_container').css({
          'width': '84.77%'
        })

        // this.reload()
      } else {
        $(target).animate({ left: '0' }, 1)
        $(target).removeClass('retract').addClass('expand')
        $('.el-main.home_container').css({
          'width': '100%',
          'left': '0'
        })
        // this.reload()
      }
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },
    removeTab(targetName) { // 删除Tab
      const tabs = this.tabsItem // 当前显示的tab数组
      let activeName = this.activeTab // 点前活跃的tab

      // 如果当前tab正活跃 被删除时执行
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
              this.tabClickEvent(nextTab)
            }
          }
        })
      }
      this.activeTab = activeName
      this.tabsItem = tabs.filter(tab => tab.name !== targetName)
      // 在tabsPath中删除当前被删除tab的path
      this.tabsPath = this.tabsPath.filter(item => item.name !== targetName)
    },
    tabClickEvent(thisTab) {
      console.log(thisTab)
      /*
        * thisTab:当前选中的tabs的实例
        * 通过当前选中tabs的实例获得当前实例的path 重新定位路由
        * */
      const val = this.tabsPath.filter(item => thisTab.name == item.name)
      console.log(val)
      this.$router.push({
        path: val[0].path
      })
    }

  }
}
</script>

<style>
*{
  padding:0;
  margin:0;
}
.home_bd .home_container {
  position: relative;
  background-color:#f0f2f5;
  padding:0;
  width:84.77%;
  flex:none;
  z-index:90;
}
.home_bd .home_container .el-tabs{
  width:100%;
  height:100%
}
.el-tabs__content{
  width:100%;
  height: calc(100% - 44px);
}
.home_container .el-tab-pane{
 /**display:block !important;**/
 width: 100%;
height:100%
}
.home_container .el-tabs__header{
  margin-bottom:0px;
  background-color:#fff
}
.el-tabs--card>.el-tabs__header{
  margin-bottom: 0px;
}
.home_bd{
  width:100%;
  position: absolute;
  top: 48PX;
  bottom: 0;
}
.home_left{
  top:0;
  z-index:99;
  box-shadow: 2PX 0PX 6PX 0PX
		rgba(0, 21, 41, 0.12);
}
.home_content{
  width:100%;
  position:absolute;
  top:0px;
  bottom:0;
  overflow:auto;
}
.home_bd .expand_retract_icon{
  display:inline-block;
  width: 16px;
	height: 42px;
	background-color: rgba(0, 0, 0, 0.09);
	border-radius: 4px 0px 0px 4px;
  position:absolute;
  left:calc(15.23% - 16px);
  top:calc(50% - 21px);
  padding:0;
  border:none;
  z-index:999;
}
.home_bd .expand_retract_icon.expand{
  background:url(../assets/images/expand.png) no-repeat center center;
  background-size:16px 42px;
}
.home_bd .expand_retract_icon.retract{
  background:url(../assets/images/retract.png) no-repeat center center;
  background-size:16px 42px;
}
.el-menu-vertical-demo .router_link{
  height:40px;
  line-height:40px;
  margin-top:8px;
  padding-left: 13px !important;
}
.el-menu-vertical-demo .router_link:first-child{
  margin-top:20px;
}
.el-menu-vertical-demo .router_link .el-icon{
  display:inline-block;
  width:19px;
  height:40px;
  margin-right:10px;
  float:left;
}
.el-menu-vertical-demo .router_link.is-active{
  background-color: #e6f7ff !important;
  border-right: 2px solid #1890ff;
}
.el-menu-vertical-demo .router_link>span {
  display:inline-block;
    font-size: 1.4rem;
    float:left;
    line-height:40px;
    color:rgba(0,0,0,0.85)
}
.el-menu-vertical-demo .router_link.is-active>span{
  color:#37a0ff;
}
.el-icon.summary_hospital{
  background:url(../assets/images/summary-hos.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.summary_hospital{
  background:url(../assets/images/summary-hos-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.depart_management{
  background:url(../assets/images/depart-manage.png) no-repeat center center;
  background-size:16px 15px;
}
.router_link.is-active .el-icon.depart_management{
  background:url(../assets/images/depart-manage-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.layout_config{
  background:url(../assets/images/layout-config.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.layout_config{
  background:url(../assets/images/layout-config-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.project_config{
  background:url(../assets/images/project-config.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.project_config{
  background:url(../assets/images/project-config-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.education_train{
  background:url(../assets/images/education-train.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.education_train{
  background:url(../assets/images/education-train-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.equip_management{
  background:url(../assets/images/equip-manage.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.equip_management{
  background:url(../assets/images/equip-manage-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.kettle_monitor{
  background:url(../assets/images/kettle-monitor.png) no-repeat center center;
  background-size:14px 18px;
}
.router_link.is-active .el-icon.kettle_monitor{
  background:url(../assets/images/kettle-monitor-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.system_setting{
  background:url(../assets/images/system-setting.png) no-repeat center center;
  background-size:16px 16px;
}
.router_link.is-active .el-icon.system_setting{
  background:url(../assets/images/system-setting-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.el-icon.personal_center{
  background:url(../assets/images/personal-center.png) no-repeat center center;
  background-size:18px 18px;
}
.router_link.is-active .el-icon.personal_center{
  background:url(../assets/images/personal-center-selected.png) no-repeat center center;
  background-size:18px 18px;
}
.home_container .el-tabs__item.is-active {
    color: #409EFF;
    background-color: #e6f7ff;
    border-top: 1px solid #1890ff;
}
</style>
