<template>
  <Layout style="height: 100%" class="main">
    <Sider hide-trigger collapsible :width="256" :collapsed-width="64" v-model="collapsed" class="left-sider" :style="{overflow: 'hidden'}">
      <side-menu accordion ref="sideMenu" :active-name="$route.name" :collapsed="collapsed" @on-select="turnToPage" :menu-list="menuList">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <img v-show="!collapsed" :src="newLogo" key="new-logo" />
          <img v-show="collapsed" :src="minLogo" key="min-logo" />
        </div>
      </side-menu>
    </Sider>
    <Layout>
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :message-unread-count="unreadCount" :user-avator="userAvator"/>
          <language v-if="$config.useI18n" @on-lang-change="setLocal" style="margin-right: 10px;" :lang="local"/>
          <error-store v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader" :has-read="hasReadErrorPage" :count="errorCount"></error-store>
          <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/>
          <Clear style="margin-right: 10px;"/>
          <GroupMenu @on-select="groupMenuSelect" :menu-list="firstMenusData" :group-name="groupName"></GroupMenu>

        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/>
          </div>
          <div class="breadcrumb-wrapper" style="padding: 10px 20px; background: #fff; border-bottom: 1px solid #e8e8e8;">
            <custom-bread-crumb show-icon :list="breadCrumbList"></custom-bread-crumb>
          </div>
          <Content class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view/>
            </keep-alive>
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
          </Content>
        </Layout>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import GroupMenu from './components/group-menu'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
import Clear from './components/clear'
import Language from './components/language'
import ErrorStore from './components/error-store'
import CustomBreadCrumb from './components/header-bar/custom-bread-crumb'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { getNewTagList, routeEqual, getMenuByRouter, localSave, localRead } from '@/libs/util'
import { getRouterReq } from '@/api/routers'
import routers from '@/router/routers'
import minLogo from '@/assets/images/logo-min.jpg'
// import maxLogo from '@/assets/images/logo.jpg'
import newLogo from '@/assets/images/logo1.png'
// import { firstMenus } from '@/api/system-old'
import './main.less'
export default {
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    GroupMenu,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    Clear,
    CustomBreadCrumb
  },
  data () {
    return {
      collapsed: false,
      minLogo,
      newLogo,
      isFullscreen: false,
      menuList001: [],
      firstMenusData: [],
      groupName: ''
    }
  },
  computed: {
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvator () {
      return this.$store.state.user.avatorImgPath
    },
    cacheList () {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    menuList () {
      return this.$store.getters.menuList
    },
    breadCrumbList () {
      return this.$store.state.app.breadCrumbList
    },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    }
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setFirstMenuId',
      'setHomeRoute',
      'closeTag'
    ]),
    ...mapActions([
      'handleLogin',
      'getUnreadMessageCount',
      'getAjaxRouterData'
    ]),
    turnToPage (route) {
      // console.log(route, 'main/turnToPage')
      let { name, params, query } = {}
      if (typeof route === 'string') name = route
      else {
        name = route.name
        params = route.params
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      // console.log(item, '执行main/handleClick')
      this.turnToPage(item)
    },
    getRouterListData () {
      getRouterReq('222').then(res => {
        // console.log('打印返回的信息', res.data)
        let listData = getMenuByRouter(res.data, 'admin')
        // console.log('返回的结果')
        console.log(listData)
        this.menuList001 = listData
      })
    },
    groupMenuSelect (id, menusData) {
      // this.setFirstMenuId(id)
      localSave('first-menus-data', JSON.stringify(menusData))
      this.$store.dispatch('getAjaxRouterData', id)
    }
  },
  watch: {
    '$route' (newRoute) {
      // console.log(newRoute, 'watch新的路由变化')
      // console.log(this.menuList, '获取当菜单数据')
      let tempMenuList = this.menuList
      for (let key in tempMenuList) {
        let childData = tempMenuList[key].children
        if (tempMenuList[key].name && tempMenuList[key].name === newRoute.name) {
          // console.log('ok11')
          newRoute.meta.title = tempMenuList[key].meta.title // 为了不在路由里面取名字写的循环
        } else {
          if (tempMenuList[key].children && tempMenuList[key].children.length > 0) {
            for (let k2 in childData) {
              let chid = childData[k2]
              if (chid.name === newRoute.name) {
                // console.log('ok')
                newRoute.meta.title = chid.meta.title // 为了不在路由里面取名字写的循环
              }
            }
          }
        }
      }
      const { name, query, params, meta } = newRoute
      this.addTag({
        route: { name, query, params, meta },
        type: 'push'
      })
      this.setBreadCrumb(newRoute)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      this.$refs.sideMenu.updateOpenName(newRoute.name)
    }
  },
  mounted () {
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList()
    this.setHomeRoute(routers)
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    this.setBreadCrumb(this.$route)
    // 设置初始语言
    this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
    // 获取未读消息条数
    this.getUnreadMessageCount()
    // TODO 封装成函数
    let localFirstMenus = localRead('first-menus-data')
    if (localFirstMenus !== '') {
      localFirstMenus = evil(localFirstMenus)
      if (localFirstMenus.length > 0) {
        this.firstMenusData = localFirstMenus
        let name1 = ''
        let id1 = ''
        for (let i = 0; i < localFirstMenus.length; i++) {
          if (localFirstMenus[i].isSelected === true) {
            name1 = localFirstMenus[i].name
            id1 = localFirstMenus[i].id
          }
        }
        this.groupName = name1
        this.$store.dispatch('getAjaxRouterData', id1)
      }
    } else {
      // firstMenus().then(res => {
      //   let result = res.data
      //   if (result.errcode === 0) {
      //     if (result.data.length > 0) {
      //       result.data[0].isSelected = true
      //       console.log(result.data, '接口返回来的菜单数据')
      //       localSave('first-menus-data', JSON.stringify(result.data))
      //       this.firstMenusData = result.data
      //       this.groupName = result.data[0].name
      //       this.$store.dispatch('getAjaxRouterData', result.data[0].id)
      //     }
      //   }
      // })
    }
  }
}
</script>
