import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'

const permission = {
  state: {
    isInit: false,
    routes: [],
    addRoutes: [],
    btnPower: []
  },
  mutations: {
    INIT: (state) => {
      state.isInit = true
    },
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = routes
    },
    SET_BTNPOWER: (state, btnPower) => {
      state.btnPower = btnPower
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes ({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const menuList = res.data;
          if (!menuList) {
            menuList = []
          }
          const accessedRoutes = parseRouterFromMenu(menuList)
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          // 插入首页
          menuList.unshift({
            // menuId 用于菜单的 active判断，如果 meta.menuInfo不存在，会取 path进行 active判断，所以此处写成和 path一致
            menuId: '/index',
            menuType: 'component',
            path: '/index',
            meta: {
              title: '首页',
              icon: 'dashboard',
              affix: true
            }
          })
          commit('SET_ROUTES', menuList)
          resolve(accessedRoutes)
        })
      })
    },
    // 保存当前页面按钮权限
    BtnPower ({ commit }, btnPower) {
      commit('SET_BTNPOWER', btnPower)
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function parseRouterFromMenu (menus) {
  const parseRouter = function (menuList) {
    if (!menuList || !menuList.length) {
      return []
    }
    const routers = []
    for (let i = 0; i < menuList.length; i++) {
      const menu = menuList[i]
      if (menu.menuType === 'button') {
        continue;
      }
      routers.push({
        path: menu.path ? menu.path : '/',
        component: menu.component ? loadView(menu.component) : null,
        redirect: null,
        meta: {
          title: menu.title,
          icon: menu.icon,
          menuInfo: menu
        },
        children: parseRouter(menu.children)
      })
    }
    return routers
  }
  return parseRouter(menus)
}

export const loadView = (view) => { // 路由懒加载
  if (view === 'Layout') {
    return Layout
  }
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
