app.js 5.29 KB
import { utils } from 'glsx-common'
import Layout from '@/views/Layout'
import { constants } from '@/common'
import router from '@/router'
const app = {
  namespaced: true,
  state: () => ({
    routers: null,
    menuList: [],
    currentPage: null,
    currentApp: null,
    microApps: [],
    isBase: true,
    isLoading: false,
    flatten: [],
    currentNav2: {}
  }),
  mutations: {
    SET_CURRENT_PAGE(state, page) {
      const { id, isBase } = page
      state.isBase = !!isBase
      if (!id) return
      const [lv1, lv2] = id.split('-')
      state.currentApp = state.flatten.find(mod => mod.id == lv1)
      state.currentNav2 = state.flatten.find(item => item.id == `${lv1}-${lv2}`)
      utils.storage.setSession(constants.SCRM_BASE_CURRENTPAGE, page)
      state.currentPage = page
    },
    SET_MENU_LIST(state, list) {
      state.menuList = list
      state.flatten = utils.array.flattenDeep(list)
      utils.storage.setSession(constants.SCRM_BASE_MENULIST, list)
    },
    SET_MICROAPPS(state, payload) {
      state.microApps = payload
    },
    SET_ROUTES(state, payload) {
      state.routers = router.constantRoutes.concat(payload)
    },
    SET_CURRENT_APP(state, payload) {
      state.currentApp = payload
    },
    SET_CURRENT_NAV2(state, nav2) {
      state.currentNav2 = nav2
    },
    SET_LOADING(state, isLoading) {
      state.isLoading = isLoading
    },
    CLEAR(state) {
      state.menuList = []
      state.flatten = []
      state.microApps = []
      state.currentApp = null
      state.currentNav2 = {}
      state.currentPage = null
      state.isLoading = false
      utils.storage.removeSession(constants.SCRM_BASE_MENULIST)
      utils.storage.removeSession(constants.SCRM_BASE_CURRENTPAGE)
    }
  },
  actions: {
    async login({ dispatch }, form) {
      // 向后端请求路由数据
      router.reset()
      const { code, message, menus } = await dispatch('auth/login', form, { root: true })
      if (menus) {
        const menuFormat = formatData(menus, '')
        await dispatch('persisted', { data: menuFormat, isWithModuleName: true })
      }
      return { code, message }
    },
    async logout({ dispatch }) {
      await dispatch('auth/logout', null, { root: true })
      await dispatch('init/reset', null, { root: true })
    },
    clear({ commit }) {
      commit('CLEAR')
    },
    setCurrentPage({ commit, dispatch }, page) {
      dispatch('menu/clear', null, { root: true })
      commit('SET_CURRENT_PAGE', page)
    },
    setCurrentApp({ commit }, payload) {
      commit('SET_CURRENT_APP', payload)
    },
    setCurrentNav2({ commit }, nav2) {
      commit('SET_CURRENT_NAV2', nav2)
    },
    setLoading({ commit }, isLoading) {
      commit('SET_LOADING', isLoading)
    },
    async persisted({ commit }, { data, isWithModuleName }) {
      const { routes, apps } = data.reduce(
        ({ routes, apps }, module) => {
          let { entry, name, id, children } = module
          apps.push({ name, entry, activeRule: `/${name}`, id })
          if (children && children.length) {
            const route = getMenuItem(isWithModuleName ? name : '', children)
            routes = routes.concat(route)
          }
          return { routes, apps }
        },
        { routes: [], apps: [] }
      )
      await commit('SET_MENU_LIST', data)
      await commit('SET_MICROAPPS', apps)
      await commit('SET_ROUTES', routes)
      return routes
    }
  }
}

/**
 * 解析后台返回数据,format 系统所需要的格式
 * @param {*} menus
 * @returns
 */
function formatData(menus, concatId) {
  const formatMenus = []
  for (let i = 0; i < menus.length; i++) {
    if (!menus[i]) continue
    const menu = {}
    let { menuUrl: path, id, label: title, url, children, logo: icon, name } = menus[i]
    if (!concatId) {
      if (!name) {
        if (!path.includes('@')) continue
        const [entry, name] = path.split('@')
        menu.entry = entry
        menu.name = name
        menu.icon = name
      } else {
        menu.name = name
        menu.entry = path
        menu.icon = name
      }
      icon
      // menu.icon = icon
      menu.id = `${id}`
    } else {
      menu.id = `${concatId}-${id}`
      if (path.includes('@')) {
        const [p, u] = path.split('@')
        path = p
        url = u
      }
    }
    if (title.startsWith('*')) {
      title = title.slice(1)
      menu.hidden = true
    }
    menu.title = title
    menu.path = path
    menu.url = url
    if (children) {
      menu.children = formatData(children, menu.id)
    }
    formatMenus.push(menu)
  }
  return formatMenus
}

// 组装路由数据
function getMenuItem(moduleName, menus) {
  let routers = []
  const flattenMenus = utils.array.flattenDeep(menus)
  for (let index = 0; index < flattenMenus.length; index++) {
    const menu = flattenMenus[index]
    const route = __gen(moduleName, menu)
    router.addRoute(route)
    routers.push(route)
  }
  return routers
}

function __gen(moduleName, menu) {
  const { path, meta = {}, id, title, url } = menu
  const [, m, n] = path.split('/')
  const name = `${m}${n ? `-${n}` : ''}_${id}`
  const _path = `${moduleName ? `/${moduleName}` : ''}${path.startsWith('/') ? path : `/${path}`}`
  menu.path = _path
  const route = {
    path: _path,
    component: Layout,
    name,
    meta: { ...meta, id, title, name, url, path: _path }
  }
  return route
}

export default app