import { Module } from 'vuex';
import { useAsRouter } from '@/hooks/useAsRouter';
import { routesModuleList } from '@/router/dynamic';
import { LayoutRoute } from '@/router/routes';
import { GetUserMenulist } from '@/apis/models';
import { message } from 'ant-design-vue';

const { routerDynamic, routerAdd, routerInit, routerTo } = useAsRouter();


export interface PermissionState {
	arrresult : string[];
	menuList : string[];
	permissionList : string[] | null;
	breadcrumbList : string[];
}

const state : PermissionState = {
	arrresult: [],
	menuList: [],
	permissionList: null,
	breadcrumbList: []
};

const mutations = {
	SET_PERMISSION(state, routes) {
		state.permissionList = routes
	},
	SET_MENU(state, menu) {
		state.menuList = menu
	}
};

const actions = {
	async FETCH_PERMISSION({
		state,
		commit
	}) {
		let res = await GetUserMenulist().catch((error) => {
			setTimeout(() => {
				sessionStorage.clear()
				routerTo('/login')
				window.location.reload()
			}, 1500);
		});
		res.data.menulist.map(item => {
			pushItem(item)
		})
		let arr = state.arrresult;
		// let arr = ['permission', 'role', 'account', 'company', 'vip', 'member', 'homemake', 'homemakeType', 'homemakePosition', 'homemakeDemand', 'homemakeAppointment', 'job', 'department', 'jobSeeker', 'jobResume', 'jobFair', 'jobFairList', 'jobFairCompany', 'information', 'section', 'article', 'list', 'putIn', 'advertisementList', 'advertisement', 'activity', 'activityList', 'activityAddress', 'statistics', 'statisticsResume', 'statisticsResumeMajor','statisticsResumeAgeSex','statisticsResumeCertificateSkill','statisticsResumeEducation','statisticsResumeHolidaysAccommodation','statisticsResumeJobIntention','statisticsResumeTitleSkill','statisticsResumeWorkExperience'];
		let routes = routerDynamic(routesModuleList, arr);
		LayoutRoute.children.push(...routes);
		commit('SET_MENU', LayoutRoute.children);
		routerAdd(LayoutRoute);
		let initialRoutes = routerInit();
		commit('SET_PERMISSION', [...initialRoutes]);
	}
};

const onClose = () => {
	debugger
	sessionStorage.clear();
	routerTo('/login')
	window.location.reload()
}

const pushItem = (item : Object) => {
	state.arrresult.push({ action: item.action, name: item.name })
	if (item.childs) {
		for (const child of item.childs) {
			pushItem(child)
		}
	}

	return state.arrresult;
}




export const permissionsModule : Module<PermissionState> = {
	namespaced: true,
	state,
	mutations,
	actions
};