/**
 *  定义初始化菜单
 */
import {
  setToken,
  getToken,
  localSave,
  localRead
} from '@/libs/util'
// import Cookies from 'js-cookie'
// import config from '@/config'
import {
  lazyLoadingCop
} from '@/libs/tools'
import {
  getMockMenuData
} from '@/api/data'
import Main from '@/components/main' // Main 是架构组件，不在后台返回，在文件里单独引入
import blank from '@/components/main/blank.vue' // blank 是架构组件，不在后台返回，在文件里单独引入
import parentView from '@/components/parent-view' // 获取组件的方法
import store from '@/store'
// import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'

// eslint-disable-next-line no-unused-vars
const _import = require('@/router/_import_' + process.env.NODE_ENV)
var gotRouter
// 初始化路由
export const initRouter = (bl, boo) => {
  if (!getToken()) {
    return
  }
  // console.log(boo)
  var routerData
  if (!gotRouter || !boo) {
    getMockMenuData(
      bl
    ).then(res => {
      routerData = res.data.data // 后台拿到路由

      localSave('sigerdatadynamicRouter', JSON.stringify(routerData)) // 存储路由到localStorage
      gotRouter = filterAsyncRouter(routerData) // 过滤路由,路由组件转换
      store.commit('updateMenuList', gotRouter)
      dynamicRouterAdd()
    })
  } else {
    gotRouter = dynamicRouterAdd()
  }
  return gotRouter
}

// 加载路由菜单,从localStorage拿到路由,在创建路由时使用
export const dynamicRouterAdd = () => {
  let dynamicRouter = []
  let data = localRead('sigerdatadynamicRouter')
  if (!data) { // 本地不存在menu数据
    initRouter()
    return dynamicRouter
  } else if (data.slice(1, 10) == 'Exception') {
    initRouter()
    return dynamicRouter
  }
  dynamicRouter = filterAsyncRouter(JSON.parse(data))
  return dynamicRouter
}

// 清空所有的cookies, 本方法依赖于getAllCookies()，clearCookieByKey(key)
// function clearAllCookies() {
//   var keys = Object.keys(getAllCookies());
//   keys.forEach(function (item) {
//       clearCookieByKey(item);
//   });
// }
// @函数: 遍历后台传来的路由字符串，转换为组件对象
export const filterAsyncRouter = asyncRouterMap => {
  var accessedRouters = []
  if (typeof (asyncRouterMap.filter) !== 'function') {
    setToken('')
    window.location.reload()
    // alert('该模块目录未在数据库创建，请点击其他模块，会加载相应的目录')
    // return false
  } else {
    accessedRouters = asyncRouterMap.filter(route => {
      route.meta.parentvalue = route.parentvalue
      if (route.component) {
        if (route.component === 'Main') {
          // Main组件特殊处理
          route.component = Main
        } else if (route.component === 'parentView') {
          // parentView组件特殊处理
          route.component = parentView
        } else if (route.component === 'blank') {
          // parentView组件特殊处理
          route.component = blank
        } else {
          // route.component = _import(route.component)
          route.component = lazyLoadingCop(route.component)
        }
      }
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
      }
      return true
    })
  }
  // const
  return accessedRouters
}
