import { asyncRoutes, constantRoutes } from '@/router'
import { getModule } from '@/api/goods'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      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 }, userInfo) {
    return new Promise(resolve => {
      let accessedRoutes
      if (userInfo.roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, userInfo.roles)
      }
      getModule({ organizeId: userInfo.organizeId }).then(response => {
        const modules = response.data[0]
        accessedRoutes.forEach(routeItem => {
          if (routeItem.name === 'Goods') {
            if (modules && modules.firstModulesName) {
              accessedRoutes[0].children.unshift({
                path: '/goods/list/preferred',
                name: 'PreferredProduct',
                component: () => import('@/views/goods/list-preferred'),
                meta: { title: modules.firstModulesName, noCache: true, activeMenu: '/goods/list' },
                hidden: true
              })
            }
            if (modules && modules.secondModulesName) {
              accessedRoutes[0].children.unshift({
                path: '/goods/list/preferential',
                name: 'PreferentialProduct',
                component: () => import('@/views/goods/list-preferential'),
                meta: { title: modules.secondModulesName, noCache: true, activeMenu: '/goods/list' },
                hidden: true
              })
            }
            if (modules && modules.thirdModulesName) {
              accessedRoutes[0].children.unshift({
                path: '/goods/list/commonly',
                name: 'CommonlyProduct',
                component: () => import('@/views/goods/list-commonly'),
                meta: { title: modules.thirdModulesName, noCache: true, activeMenu: '/goods/list' },
                hidden: true
              })
            }
          }
        })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(() => {
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

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