import { asyncRoutes, constantRoutes } from '@/router'
import { permissions } from "@/api/me"
import path from "path"
import Layout from "@/layout"
import Nested from "@/layout/nested.vue"

const loadView = (view) => {
  return (resolve) => require([`@/views${view}`], resolve);
}
const componentHandle = (path, route)=> {
  if (/^#+/.test(path)) {
    return Layout
  } else if (/^#+/.test(path) && route.pid !== 0) {
    return Nested
  } else {
    return loadView(path)
  }
}

export function filterAsyncRoutes(routes) {
  const res = []

  routes.forEach(route => {
    if (!route.visible) return
    let tmp= {
      key: `key-${route.id}`,
      path: route.path === '#' ? '' : route.path,
      component: componentHandle(route.url, route),
      name: route.name,
      hidden: !route.visible,
      meta: {
        title: route.title,
        icon: route.icon,
        guard: route.guard_name,
        folder: route.folder,
      }
    }

    if (route.children && route.children instanceof Array && route.children.length > 0) {
      tmp.children = filterAsyncRoutes(route.children)
    }
    res.push(tmp)
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(async (resolve, reject) => {
      try {
        const routes = await permissions()
        let accessedRoutes
        accessedRoutes = filterAsyncRoutes(routes)
        //把404拦截放在最后匹配
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      } catch (err) {
        reject(err)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
