import { defineStore } from "pinia";
import { getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList, setKeeAliveRoute, extractButtonPermissions } from "@/utils";

// 定义权限相关类型
interface ButtonPermissionMap {
    [key: string]: boolean;
}

interface PageButtonMap {
    [pageName: string]: string[];
}

export const useAuthStore = defineStore({
    id: "wms-auth",
    state: (): {
        authMenuList: any[];
        routeName: string;
        buttonPermissions: ButtonPermissionMap;
        pageButtonMap: PageButtonMap;
    } => ({
        // 菜单权限列表
        authMenuList: [],
        // 当前页面的 router name，用来做按钮权限筛选
        routeName: "",
        // 按钮权限映射表 {按钮name: 是否有权限}
        buttonPermissions: {},
        // 页面与按钮的映射关系 {页面name: [按钮name1, 按钮name2]}
        pageButtonMap: {}
    }),
    getters: {
        // 菜单权限列表 ==> 处理缓存路由
        authMenuListGet: state => setKeeAliveRoute(state.authMenuList),
        // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 hidden == true
        showMenuListGet: state => getShowMenuList(state.authMenuList),
        // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
        flatMenuListGet: state => getFlatMenuList(state.authMenuList),
        // 递归处理后的所有面包屑导航列表
        breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList),
        // 当前页面的按钮权限列表
        currentPageButtons: state => {
            return state.pageButtonMap[state.routeName] || [];
        },
        // 检查是否有权限
        hasPermission: state => (permissionName: string | string[]) => {
            if (Array.isArray(permissionName)) {
                return permissionName.some(name => state.buttonPermissions[name]);
            }
            return !!state.buttonPermissions[permissionName];
        },
        // 检查当前页面是否有指定按钮权限
        hasCurrentPagePermission: state => (buttonName: string | string[]) => {
            // 先检查是否有页面访问权限
            if (!state.pageButtonMap[state.routeName]) return false;

            if (Array.isArray(buttonName)) {
                return buttonName.some(
                    name => state.pageButtonMap[state.routeName].includes(name) && state.buttonPermissions[name]
                );
            }
            return state.pageButtonMap[state.routeName].includes(buttonName) && state.buttonPermissions[buttonName];
        }
    },
    actions: {
        // 获取权限菜单列表并处理按钮权限
        async getAuthMenuList() {
            const { data } = await getAuthMenuListApi();
            let dataClone = data;

            // 如果没有路由数据，设置默认首页
            this.authMenuList = dataClone || [
                {
                    path: "/index",
                    name: "home",
                    component: "/home/index",
                    hidden: true,
                    children: [],
                    meta: {
                        icon: "",
                        title: "首页",
                        isKeepAlive: true
                    }
                }
            ];

            // 提取按钮权限
            this.buttonPermissions = extractButtonPermissions(this.authMenuList);
            // 构建页面与按钮的映射关系
            this.buildPageButtonMap();
        },

        // 构建页面与按钮的映射关系
        buildPageButtonMap() {
            const pageButtonMap: PageButtonMap = {};

            // 递归处理路由，建立页面与按钮的关联
            const processRoutes = (routes: any[], parentPageName?: string) => {
                routes.forEach((route: any) => {
                    // 页面路由(type:1)
                    if (route.type === 1 && route.name) {
                        // 如果页面没有按钮列表，初始化一个空数组
                        if (!pageButtonMap[route.name]) {
                            pageButtonMap[route.name] = [];
                        }

                        // 处理子节点中的按钮权限
                        if (route.children && route.children.length > 0) {
                            route.children.forEach((child: any) => {
                                // 按钮权限(type:0)
                                if (child.type === 0 && child.name) {
                                    pageButtonMap[route.name].push(child.name);
                                }
                                // 如果有嵌套的子路由，继续递归
                                if (child.children && child.children.length > 0) {
                                    processRoutes(child.children, route.name);
                                }
                            });
                        }
                    }
                    // 如果当前路由有子路由，继续递归处理
                    else if (route.children && route.children.length > 0) {
                        processRoutes(route.children, parentPageName);
                    }
                });
            };

            processRoutes(this.authMenuList);
            console.log(pageButtonMap, "=pageButtonMap=");
            this.pageButtonMap = pageButtonMap;
        },

        // 设置当前路由名称
        setRouteName(name: string) {
            this.routeName = name;
        },

        // 检查页面是否有权限访问
        hasPageAccess(pageName: string): boolean {
            // 检查页面是否在权限列表中且未被禁用
            const checkPage = (routes: any[]): boolean => {
                return routes.some(route => {
                    if (route.type === 1 && route.name === pageName && !route.disable) {
                        return true;
                    }
                    if (route.children && route.children.length > 0) {
                        return checkPage(route.children);
                    }
                    return false;
                });
            };

            return checkPage(this.authMenuList);
        }
    }
});
