import Vue from 'vue'
import Router from 'vue-router'
import Cookies from 'js-cookie';
import store from '../vuex'
import Main from '@/views/index/index'

Vue.use(Router)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: (resolve) => require(['@/views/login/index'], resolve),
    meta: {
      'title': '登录'
    }
  },
  {
    path: '/',
    name: 'index',
    redirect: '/index',
    component: Main,
    children: [
      {
        path: 'index',
        name: 'index',
        component: (resolve) => require(['@/views/main/main'], resolve),
        meta: {
          'title': '首页'
        }
      },
      {
        path: '403',
        name: '403',
        component: (resolve) => require(['@/views/errorPage/403'], resolve),
        meta: {
          'title': '无权限'
        }
      },
      {
        path: '/menu',
        name: 'menu',
        component: (resolve) => require(['@/views/permission/authrule'], resolve),
        meta: {
          'title': '菜单管理'
        }
      }
    ]
  },
  {
    path: '/permission',
    name: 'permission',
    component: Main,
    children: [
      {
        path: '/authrule',
        name: 'authrule',
        component: (resolve) => require(['@/views/permission/authrule'], resolve),
        meta: {
          'title': '菜单管理'
        }
      }
    ]
  },
  {
    path: '/main',
    name: 'main',
    component: (resolve) => require(['@/views/main/index'], resolve),
    meta: {
      'title': '数据大屏'
    }
  },
  {
    path: '/command',
    name: 'command',
    component: (resolve) => require(['@/views/command/index'], resolve),
    meta: {
      'title': '指挥大屏'
    }
  }
]
const router = new Router({
  mode: 'history',
  routes
})

router.onError((error) => {
  router.push({path: '403'})
})

router.beforeEach(async (to, from, next) => {
  // 登录界面登录成功之后，会把用户信息保存在会话
  // 存在时间为会话生命周期，页面关闭即失效。
  if(to.path=='/main'){
    next()
    return
  }
  if(to.path == '/login'){
    await store.dispatch('user/resetToken')
    next()
  }
  let token = Cookies.get(location.host+'-token')
  if (!token) {
    if (to.path != '/login') {
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    } else {
      next()
    }
  } else{
    if(to.path=='/command'){
      next()
      return
    }
    if (!store.state.user.roles) {
      if (!store.state.user.info) {
        await store.dispatch('user/getInfo')
      }
      if (!store.state.user.menuList.length > 0) {
        await store.dispatch('user/getMenuList')
      }
      const {menuList, permission, isAdmin} = store.state.user
      let roles = []
      if (isAdmin) {
        roles = JSON.parse(JSON.stringify(menuList))
      } else {
        let rules = permission ? permission.split(',') : []
        rules.map(id => {
          let item = menuList.find(child => child.id == id)
          if (item) {
            roles.push(item)
          }
        })
      }
      store.dispatch('user/setRole', roles)
      let btnList = roles.filter(item=>item.type == 1 && item.status == 1)
      let btnRule = {}
      btnList.map(item => {
        item.permission=item.permission.replace(/:/g,"_")
        btnRule[item.permission]=true
      })
      store.dispatch('user/setTtnRule', btnRule)
      console.log(btnRule)
      addDynamicMenuAndRoutes(to, from)
      next(to.path)
    }
    if (to.name == 'login' || to.path == '/index' || to.name == '403') {
      if (to.name == 'index' || to.name == '403') {
        let tagList = store.state.user.tagList
        for (let i = 0; i < tagList.length; i++) {
          tagList[i].isSelect = false
        }
        if (to.name == 'index') {
          store.dispatch('user/setIsIndexTag', true)
        }
        if (to.name == '403') {
          store.dispatch('user/setIsIndexTag', false)
        }
      }
      next()
    } else {
      document.documentElement.style.fontSize = '14px';
      store.dispatch('user/setIsIndexTag', false)
      let roleList = JSON.parse(JSON.stringify(store.state.user.roles))
      let child = roleList.find(item => item.name == ('/' + to.name) && item.type == 2 && item.status == 1)
      if (child) {
        let breadcrumb = []
        let tagList = store.state.user.tagList
        let tagChild = {
          id: child.id,
          title: child.title,
          path: child.name,
        }
        if (child.pid !== 0) {
          let item = roleList.find(item => item.id == child.pid && item.type == 2 && item.status == 1)
          if (item) {
            breadcrumb.push(item.title)
            tagChild.path = item.name + tagChild.path
          }
        }
        if (tagList.length > 0) {
          if (!tagList.some(item => item.id == child.id)) {
            tagList.push(tagChild)
          }
        } else {
          tagList.push(tagChild)
        }
        for (let i = 0; i < tagList.length; i++) {
          if (tagList[i].id == child.id) {
            tagList[i].isSelect = true
          } else {
            tagList[i].isSelect = false
          }
        }
        breadcrumb.push(child.title)
        store.dispatch('user/setBreadcrumb', breadcrumb)
        store.dispatch('user/setTagList', tagList)
        next()
      }
    }
  }
})

function addDynamicMenuAndRoutes(to, from) {
  const {roles}=store.state.user
  let filterMenuList = roles.filter(item => item.type == 2 && item.status == 1)
  // 添加动态路由
  let dynamicRoutes = addDynamicRoutes(filterMenuList)
  handleStaticComponent(router, dynamicRoutes)
  router.addRoutes(router.options.routes)
}

/**
 * 处理路由到本地直接指定页面组件的情况
 * 比如'代码生成'是要求直接绑定到'Generator'页面组件
 */
function handleStaticComponent(router, dynamicRoutes) {
  dynamicRoutes.push({path: '*', redirect: '/403', hidden: true})
  router.options.routes = router.options.routes.concat(dynamicRoutes)
}


function addDynamicRoutes(menuList, routes = []) {
  let rootMenuList = menuList.filter(item => item.pid == 0)
  rootMenuList.map(item => {
    let route = {
      path: item.name,
      component: Main,
      name: item.name.replace('/', ''),
      meta: {
        icon: item.icon ? item.icon : '',
        index: item.sort,
        title: item.title
      }
    }
    let childMenuList = menuList.filter(child => child.pid == item.id)
    if (childMenuList.length > 0) {
      let children = []
      childMenuList.map(child => {
        let childRoute = {
          path: child.name.replace('/', ''),
          component: (resolve) => require([`@/views${item.name}${child.name}`], resolve),
          name: child.name.replace('/', ''),
          meta: {
            icon: child.icon ? child.icon : '',
            index: child.sort,
            title: child.title
          }
        }
        children.push(childRoute)
      })
      route.children = children
      routes.push(route)
    }
  })
  return routes
}


export default router;

