<template>
  <el-menu :default-active="activeMenu" mode="horizontal">
    <!-- <template v-for="(item, index) in menuList" >
      <template v-if="!item.hidden">
        	<el-menu-item :style="{'--theme': theme}" @click="handleClick(item)" :index="item.path" :key="item.path"
			              v-if="index < visibleNumber && item.path && item.meta.title">
				<svg-icon :icon-class="item.meta.icon"/>
				{{ item.meta.title }}
			</el-menu-item>
      	<el-menu-item v-if="!(menuList.length > visibleNumber) && !three && user && false" @click="handleOpen('http://8.134.76.179/index.php?m=login&token='+user.code)" index="http://8.134.76.179/index" style="color: #999093">
      		<svg-icon icon-class="guide"/>
      		学习园地
      	</el-menu-item>
      </template>

    </template>-->
    <template v-for="(item, index) in menuList">
      <template v-if="!item.hidden">
        <el-popover :key="item.path" trigger="hover" :visible-arrow="false" popper-class="zero-padding-popover">
          <div slot="reference" style="display: inline-block; line-height: 50px !important">
            <el-menu-item
              :style="{ '--theme': theme }"
              @click="handleClick(item)"
              :index="item.path"
              :key="item.path"
              v-if="index < visibleNumber && item.path && item.meta.title"
            >
              <svg-icon :icon-class="item.meta.icon"/>
              {{ item.meta.title }}
            </el-menu-item>
            <el-menu-item
              v-if="!(menuList.length > visibleNumber) && !three && user && false"
              @click="handleOpen('http://8.134.76.179/index.php?m=login&token='+user.code)"
              index="http://8.134.76.179/index"
              style="color: #999093"
            >
              <svg-icon icon-class="guide"/>
              学习园地
            </el-menu-item>
          </div>
          <div v-if="item.name==='Plan/index'">
            <el-row
              :style="{'background-color':listActive===key.id?'#D2F1E8':''}"
              class="dataList"
              v-for="key in list1"
              :key="key.name"
              @click.native="clickEv(key,item)"
            >{{ key.name }}
            </el-row>
          </div>
          <div v-else-if="item.name==='Info/index'">
            <el-row class="dataList" v-for="key in list2" :key="key.name" @click.native="clickEv(key,item)">
              {{ key.name }}
            </el-row>
          </div>
          <div v-else-if="item.name==='Assistant'">
            <el-row class="dataList" v-for="key in list3" :key="key.name" @click.native="clickEv(key,item)">
              {{ key.name }}
            </el-row>
          </div>
          <div v-else-if="item.name==='Zhiyuan/index'">
            <el-row
              :style="{'background-color':listActive===key.id?'#D2F1E8':''}"
              class="dataList"
              v-for="key in list4"
              :key="key.name"
              @click.native="clickEv(key,item)"
            >{{ key.name }}
            </el-row>
          </div>
          <!--          <div v-else-if="item.name==='FillIn'">-->
          <!--            <el-row class="dataList" v-for="key in list4" :key="key.name" @click.native="clickEv(key,item)">{{key.name}}-->
          <!--            </el-row>-->
          <!--          </div>-->
        </el-popover>
      </template>
    </template>

    <template></template>
    <!--    <template v-if="!(menuList.length > visibleNumber)">-->
    <!--      <el-button v-if="firstNav" style="margin-top:10px;margin-left:10px" size="small" @click.stop="backFirstMenu()" round>返回</el-button>-->
    <!--    </template>-->

    <!-- 顶部菜单超出数量折叠 -->
    <el-submenu index="more" v-if="menuList.length > visibleNumber">
      <template slot="title">更多菜单</template>
      <template v-for="(item, index) in menuList">
        <template v-if="!item.hidden">
          <el-menu-item :index="item.path" :key="index" v-if="index >= visibleNumber  && item.path && item.meta.title"
                        @click="handleClick(item)">
            <svg-icon :icon-class="item.meta.icon"/>
            {{ item.meta.title }}
          </el-menu-item>
        </template>
      </template>
      <el-menu-item
        v-if=" !three && user && false"
        @click="handleOpen('http://8.134.76.179/index.php?m=login&token='+user.code)"
        index="http://8.134.76.179/index"
      >
        <svg-icon icon-class="guide"/>
        学习园地
      </el-menu-item>
    </el-submenu>

    <!--		<el-button v-if="three" style="margin-top:10px;margin-left:10px" size="small" @click.stop="backMenu()" round>-->
    <!--			返回-->
    <!--		</el-button>-->
    <!-- <el-button v-if="firstNav" style="margin-top:10px;margin-left:10px" size="small" @click.stop="backFirstMenu()" round>返回首页</el-button> -->
  </el-menu>
</template>

<script>
import { constantRoutes } from '@/router'
import path from 'path'
import auth from '@/utils/auth'
import Cookies from 'js-cookie'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      // 顶部栏初始数
      visibleNumber: 10,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined,
      menuList: [],
      three: false,
      firstNav: true,
      activeMenu: '',
      time: null,
      list1: [
        { name: '生涯测评', id: 'CareerEva' },
        { name: '院校库', id: 'UniversitiesColleges' },
        { name: '专业库', id: 'ProfessLib' },
        { name: '职业库', id: 'Vocation' },
        { name: '选科查询', id: 'Subject' },
        { name: '选科报名', id: 'SubjectSign' },
        { name: '生涯课程', id: '7' }
      ],
      list2: [
        { name: '高考政策', id: 'gkzc' },
        { name: '特殊类招生', id: 'tslzs' },
        { name: '强基计划', id: 'qjjh' },
        { name: '填报技巧', id: 'tbjq' }
      ],
      list3: [
        { name: '关注的院校', id: '0' },
        { name: '关注的专业', id: '1' },
        { name: '生涯测评报告', id: '2' },
        { name: '我的志愿表', id: '3' }
      ],
      list4: [
        { name: '模拟志愿', id: 'SimulatedVolunteer' },
        { name: '批次控制线', id: 'batch' },
        { name: '一分一段', id: 'yfyd' },
        { name: '投档线', id: 'ShiftLine' },
        { name: '高考名词', id: 'gkmc' }
      ],
      listActive: ''
    }
  },
  computed: {
    ...mapGetters(['currentUser']),
    user() {
      return this.currentUser
    },
    theme() {
      return this.$store.state.settings.theme
    },

    // 所有的路由信息
    routers() {
      return this.$store.state.permission.topbarRouters
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.setVisibleNumber)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setVisibleNumber)
  },
  mounted() {
    console.log(new Date().getTime())
    this.setVisibleNumber()
    this.menuList = this.topMenus()
    let menuList = []
    let routes = []
    menuList = auth.getMenuTab()
    routes = auth.getMenuList()
    console.log(menuList, routes)
    if (menuList && menuList.length > 0) {
      this.menuList = menuList
      this.$store.commit('SET_SIDEBAR_ROUTERS', routes)
      if (menuList[0].level == 2) {
        this.three = true
      }
      this.activeMenu = auth.getActiveMenu()
    } else {
      this.$store.commit('SET_SIDEBAR_ROUTERS', routes)
      this.gouTo()
    }
    console.log(new Date().getTime())
    if (menuList && menuList[0] && menuList[0].level == 2) {
      this.firstNav = false
    }
    console.log(menuList)
  },
  watch: {
    activeMenu: function(value) {
      console.log(value)
      if (value) {
        auth.setActiveMenu(value)
      }
    },
    $route: function() {
      this.menuList = auth.getMenuTab()
      this.activeMenu = auth.getActiveMenu()
    }
  },
  methods: {
    toSecondary(data, item) {
      auth.setActiveMenu(item.path)
      this.$router.push({ path: item.path, query: data })
    },
    clickEv(data, item) {
      this.listActive = data.id
      auth.setActiveMenu(item.path)
      // this.$router.push({ path: `/career/plan/${data.id}` }).catch(() => { })
      switch (data.id) {
        case 'CareerEva':
          auth.setActiveMenu(item.path)
          this.$router.push({ path: '/career/plan/CareerEva' }).catch(() => {
          })
          break
        case 'UniversitiesColleges':
          auth.setActiveMenu(item.path)
          this.$router
            .push({ path: '/career/plan/UniversitiesColleges' })
            .catch(() => {
            })
          break
        case 'ProfessLib':
          auth.setActiveMenu(item.path)
          this.$router
            .push({ path: '/career/plan/ProfessLib' })
            .catch(() => {
            })
          break
        case 'Subject':
          this.$router.push({ path: '/career/subject/index' }).catch(() => {
          })
          break
        case 'SubjectSign':
          this.$router
            .push({ path: '/career/subjectSign/index' })
            .catch(() => {
            })
          break
        case 'Vocation':
          this.$router.push({ path: '/career/vocation/index' }).catch(() => {
          })
          break
        case 'batch':
          this.$router.push({ path: '/career/batch' }).catch(() => {
          })
          break
        case 'yfyd':
          this.$router.push({ path: '/career/yfyd' }).catch(() => {
          })
          break
        case 'gkmc':
          this.$router.push({ path: '/career/gkmc/index' }).catch(() => {
          })
          break
        case 'ShiftLine':
          this.$router.push({ path: '/career/ShiftLine' }).catch(() => {
          })
          break
        case 'SimulatedVolunteer':
          this.$router
            .push({ path: '/career/SimulatedVolunteer' })
            .catch(() => {
            })
          break
        default:
          this.toSecondary(data, item)
          break
      }
    },
    gouTo() {
      let menuList = this.topMenus()
      let actionMenu = ''
      menuList.forEach((item, index) => {
        if (this.$route.query.type == item.path) {
          this.handleClick(this.menuList[index] || {})
          if (item.children && item.children.length > 0) {
            actionMenu = item.path + '/' + item.children[0].path
          } else {
            actionMenu = item.path
          }
        }
      })
      console.log('actionMenu==', actionMenu)
      let routes = auth.getMenuList()
      if (routes.length == 0) {
        this.$router.push({ path: actionMenu })
        auth.setMenuListAction(actionMenu)
      } else {
        console.log('routes', routes)
        let path = this.gouAction(routes)
        if (path) {
          this.$router.push({ path: path })
          auth.setMenuListAction(path)
          console.log(new Date().getTime())
        }
      }
    },
    gouAction(data) {
      if (data && data.length > 0) {
        if (data[0].children && data[0].children.length > 0) {
          if (
            data[0].children[0].children &&
            data[0].children[0].children.length > 0
          ) {
            return data[0].children[0].children.path
          } else {
            return data[0].path + '/' + data[0].children[0].path
          }
        } else {
          return data[0].path
        }
      } else {
        return ''
      }
    },
    backFirstMenu() {
      this.$router.push('/login')
    },
    backMenu() {
      this.menuList = this.topMenus()
      auth.setMenuTab(this.menuList)
      this.firstNav = true
      this.three = false
    },
    handleOpen(url) {
      window.open(url)
    },
    handleClick(data) {
      this.listActive = ''
      let item = JSON.parse(JSON.stringify(data))
      let routes = [] //三级菜单
      let second = [] //二级
      if (item.level == 1) {
        //点击一级菜单
        if (item.children) {
          //有二级菜单
          item.children.forEach((item2) => {
            if (item2.children) {
              item2.children.forEach((item3) => {
                item3.path = item.path + '/' + item2.path + '/' + item3.path
              })
              if (routes.length == 0 && item2.children.length) {
                //一级菜单下面第一个有3个菜单的二级菜单
                routes = item2.children
                this.activeMenu = item.path + '/' + item2.path //默认值高亮
              }
            }
            item2.path = item.path + '/' + item2.path
            item2.level = 2
            second.push(item2)
          })

          this.menuList = second
          auth.setMenuTab(second)
          this.three = true
          this.$store.commit('SET_SIDEBAR_ROUTERS', routes)
        } else {
          //没有二级菜单
          this.$store.commit('SET_SIDEBAR_ROUTERS', [])
          this.$router.push({ path: item.path })
        }
      } else {
        auth.setActiveMenu(item.path)
        if (item.children) {
          //有三级菜单
          routes = item.children
          this.$store.commit('SET_SIDEBAR_ROUTERS', routes)
          let path = this.toPath(routes, '', '')
          auth.setMenuListAction(path)
          this.$router.push({ path: path })
        } else {
          routes = []
          this.$store.commit('SET_SIDEBAR_ROUTERS', [])
          this.$router.push({ path: item.path })
        }
      }
      auth.setMenuList(routes)
      this.firstNav = false
      this.$forceUpdate()
    },
    toPath(data, path, url) {
      data.forEach((item) => {
        if (!path && item.children && item.children.length > 0) {
          let ac = url ? url + '/' : ''
          path = this.toPath(item.children, path, ac + item.path)
        } else if (!path) {
          let ac = url ? url + '/' : ''
          path = ac + item.path
        }
      })
      return path
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = []
      this.routers.map((menu) => {
        menu.level = 1
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === '/') {
            if (menu.children) {
              topMenus.push(menu.children[0])
            }
          } else {
            topMenus.push(menu)
          }
        }
      })
      return topMenus
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width / 2
      this.visibleNumber = parseInt(width / 85)
    },

    ishttp(url) {
      return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
// .el-menu--horizontal > .el-menu-item {
// 	float: left;
// 	height: 50px;
// 	line-height: 50px;
// 	margin: 0;
// 	border-bottom: 3px solid transparent;
// 	color: #999093;
// 	padding: 0 5px;
// 	margin: 0 10px;
// }

//  .el-menu--horizontal >.el-popover__reference-wrapper > .el-menu-item.is-active {
// 		border-bottom: 3px solid #{'var(--theme)'};
// 		color: #303133;
// 	}
.navbar {
  .el-menu {
    .el-menu-item {
      float: left;
      height: 50px;
      line-height: 50px;
      margin: 0;
      border-bottom: 3px solid transparent;
      color: #999093;
      padding: 0 5px;
      margin: 0 10px;
    }

    span {
      .el-popover__reference-wrapper {
        .el-popover__reference {
          .el-menu-item.is-active {
            border-bottom: 3px solid #{"var(--theme)"} !important;
            // border:1px solid red;
            color: #303133 !important;
          }
        }
      }
    }
  }
}

.dataList {
  cursor: pointer;
  line-height: 36px;
  padding-left: 20px;

  &:hover {
    background-color: #d9ffee;
  }
}

/* submenu item */
.el-menu--horizontal > .el-submenu .el-submenu__title {
  height: 50px !important;
  line-height: 50px !important;
}
</style>
<style>
.zero-padding-popover.el-popover {
  padding: 0px !important;
}
</style>
