import { constantRoutes } from '@/router'
import { getRouters } from '@/api/basicsModules/index'
import Layout from '@/layout/index'
import ParentView from '@/layout/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import store from '@/store'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          //过滤多余路由
          let routesList = [];
          res.data.forEach(item=>{
            if(item.path == process.env.VUE_APP_MOD_NAME){
              routesList.push(item);
            }
          })
          //路由版权限处理
          let permissions = store.getters.permissions;
          if(permissions[0] != "*:*:*"){
            let routeList = routePermissionsData(routesList);
            commit('SET_PERMISSIONS', routeList)
          }
          let dataList = JSON.parse(JSON.stringify(routesList));
          let newData = routeSetData(dataList);
          localStorage.setItem('safetyEducationExaminationRouteData',JSON.stringify(newData))
          const sdata = JSON.parse(JSON.stringify(newData))
          const rdata = JSON.parse(JSON.stringify(newData))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          rewriteRoutes.push({ path: '*', redirect: '/login', hidden: true })
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          resolve(rewriteRoutes)
        })
      })
    }
  }
}

//路由数据权限化处理
function routePermissionsData(list){
  let newList = JSON.parse(JSON.stringify(list));
  let routeList = [];
  for(let i=0;i<newList.length;i++){
    if(newList[i].menuType == 1 && newList[i].child && newList[i].visible){
      let obj = {
        path:newList[i].path,
        permissions:[],
      };
      for(let o=0;o<newList[i].child.length;o++){
        if(newList[i].child[o].menuType == 2 && newList[i].child[o].visible && newList[i].child[o].perms){
          obj.permissions.push(newList[i].child[o].perms)
        }
      }
      routeList.push(obj);
    }else if(newList[i].menuType == 0 && newList[i].child){
      let newRouteList = routePermissionsData(newList[i].child)
      if(newRouteList[0]){
        routeList = routeList.concat(newRouteList)
      }
    }
  }
  return routeList;
}


//路由数据格式处理(后台返回数据与路由参数不匹配在这里重新处理格式)
function routeSetData(list,type){
  if(list && list[0]){
    let newList = JSON.parse(JSON.stringify(list))
    let listData = [];
    for(let i=0;i<newList.length;i++){
      let obj = {
        menuId : newList[i].menuId,
        alwaysShow : !newList[i].visible,
        hidden : !newList[i].visible,
        isFrame : newList[i].isFrame,
        linkId : newList[i].linkId,
        meta : {
          icon:newList[i].icon?newList[i].icon:'#',
          link:null,
          noCache:false,
          title:newList[i].menuName,
        },
        component : newList[i].component,
        name : newList[i].path,
      }
      if(!type){
        obj.redirect = 'noRedirect'
        obj.path = '/'+newList[i].path
      }else{
        obj.path = newList[i].path
      }
      if(newList[i].child && newList[i].menuType == 0){
        obj.children = routeSetData(newList[i].child,true);
      }
      listData.push(obj);
    }
    return listData
  }
}
function firstToUpper1(str) {
  return str[0].toUpperCase() + str.substr(1);
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else{
        route.component = loadView(route)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => { // 路由懒加载
  //通过层级判断是否需要字段切割
  let pathList = view.component.split('/');
  let pathUrl = ''
  let pathName = pathList[0];
  for(let i=0;i<pathList.length;i++){
    if(i !== 0){
      pathUrl = pathUrl +'/'+ pathList[i]
    }
  }
  if(pathName === 'basicsModules'){
    // 基础模块
    return (resolve) => require([`@/views/basicsModules${pathUrl}`], resolve)
  }else if(pathName === 'safetyEducationExaminationNew'){
    // 安全教育考试
    return (resolve) => require([`@/views/safetyEducationExaminationNew${pathUrl}`], resolve)
  }
}

export default permission
