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

const permission = {
	state: {
		routes: [],
		sidebarRouters: [],
		tagsRouter: []
	},
	mutations: {
		SET_ROUTES: (state, routes) => {
			state.routes = routes
		},
		SET_TAGS_ROUTER: (state, routes) => {
			state.tagsRouter = routes
		},
		SET_SIDEBAR_ROUTERS: (state, routes) => {
			state.sidebarRouters = routes
		}
	},
	actions: {
		// 生成路由
		GenerateRoutes({ commit }) {
			return new Promise(resolve => {
				// 向后端请求路由数据
				getRouters().then(res => {
					const data = JSON.parse(JSON.stringify(res.data))
					const sidebarRouters = filterSideBarRouters(data)
					const rewriteRoutes = filterAsyncRouter(data)
					rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
					commit(
						'SET_ROUTES',
						data.filter(item => item.menuType === 'C')
					)
					commit('SET_SIDEBAR_ROUTERS', sidebarRouters)
					commit('SET_TAGS_ROUTER', constantRoutes.concat(rewriteRoutes))
					resolve(rewriteRoutes)
				})
			})
		}
	}
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(data) {
	return data
		.filter(item => item.menuType === 'C')
		.map(item => {
			return {
				path: '/' + item.path,
				component: Layout,
				hidden: true,
				children: [
					{
						path: '',
						component: loadView(item.component),
						name: item.path,
						meta: {
							title: item.menuName,
							icon: item.icon,
							menuId: item.menuId,
							parentId: item.parentId
						}
					}
				]
			}
		})
}

function filterSideBarRouters(data) {
	return data.filter(item => item.menuType === 'M')
}

export const loadView = view => {
	if (process.env.NODE_ENV === 'development') {
		return resolve => require([`@/views/${view}`], resolve)
	} else {
		return () => import(`@/views/${view}`)
	}
}

export default permission
