import { defineStore } from 'pinia'
import { userMenuQuery } from '@/api/system/menu'
import {
    processRouting,
    getSystemMenuData,
    getCurrentMenuData,
    getCurrentMenuDataFromParent,
    getFirstMenuPath
} from '@/utils/menu'

interface MenuItem {
    alias?: string
    routerPath?: string
    pathArr?: string[]
    children?: MenuItem[]
    [key: string]: any
}

interface RouteParamsRecord {
    params: Record<string, any>
    query: Record<string, any>
}

export const useMenuStore = defineStore('menu', {
    state: () => ({
        userMenu: [] as MenuItem[], // 用户菜单
        normalMenu: [] as MenuItem[], // 业务功能菜单
        currentMenuGroup: null as MenuItem | null, // 当前菜单组一级菜单
        currentMenuGroupAlias: '', // 当前菜单组一级菜单别名
        customMenu: [] as MenuItem[], // 动态路由菜单
        fixFirstMenu: false, // 是否固定跳转到第一个菜单   是则跳转到第一个菜单，否则跳转到用户权限菜单中第一个可访问菜单
        firstMenuPath: '/platLayout/home', // 第一个菜单路径
        routeParamsMap: {} as Record<string, RouteParamsRecord> // 路由参数存储
    }),
    getters: {
        getMenuData: (state) => state.userMenu,
        getNormalMenuData: (state) => {
            return state.normalMenu
        },
        getCurrentMenuGroupAlias: (state) => {
            return state.currentMenuGroupAlias
        },
        getCurrentMenuGroup: (state) => {
            return state.currentMenuGroup
        },
        getCustomMenuData: (state) => {
            return state.customMenu
        },
        getRouteParams: (state) => (routeName: string) => {
            return state.routeParamsMap[routeName] || null
        }
    },
    actions: {
        async userMenuData() {
            try {
                const response = await userMenuQuery()
                if (!Array.isArray(response) || !response.length) return ''
                this.processMenuData(response)
                return this.firstMenuPath
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 完整实现菜单数据处理方法
        processMenuData(response: any[]) {
            // 处理用户菜单数据
            this.userMenu = response.map((item) => {
                const { children, alias, ...i } = item
                const routerPath = alias === 'normal' ? 'platLayout' : alias
                const pathArr = [routerPath]
                return {
                    ...i,
                    alias,
                    routerPath: `/${routerPath}`,
                    pathArr: pathArr,
                    children: processRouting(children || [], pathArr)
                }
            })

            // 处理普通菜单数据
            if (this.userMenu.length > 0) {
                this.normalMenu = getSystemMenuData(this.userMenu, 'normal')
                this.currentMenuGroup = getCurrentMenuData(this.userMenu, 'normal')
                this.currentMenuGroupAlias = this.currentMenuGroup?.alias || ''
                !this.fixFirstMenu ? (this.firstMenuPath = getFirstMenuPath(this.normalMenu)) : null
            }
        },

        setMenu(userMenu: Array<MenuItem>) {
            this.userMenu = userMenu
        },
        setNormalMenu(normalMenu: Array<MenuItem>) {
            this.normalMenu = normalMenu
            this.currentMenuGroup = getCurrentMenuDataFromParent(
                normalMenu,
                this.currentMenuGroupAlias
            )
        },
        setCurrentMenuGroupAlias(currentMenuGroupAlias: string) {
            this.currentMenuGroupAlias = currentMenuGroupAlias
        },
        setCurrentMenuGroup(currentMenuGroup: MenuItem) {
            this.currentMenuGroup = currentMenuGroup
        },
        setCustomMenu(customMenu: MenuItem[]) {
            this.customMenu = customMenu
        },
        // 记录路由参数
        recordRouteParams(
            routeName: string,
            params: Record<string, any>,
            query: Record<string, any>
        ) {
            if (routeName) {
                this.routeParamsMap[routeName] = { params, query }
            }
        },
        // 清除指定路由参数
        clearRouteParams(routeName: string) {
            delete this.routeParamsMap[routeName]
        },
        clearMenu() {
            this.userMenu = []
            this.normalMenu = []
            this.currentMenuGroup = null
            this.currentMenuGroupAlias = ''
            this.customMenu = []
            this.routeParamsMap = {}
            localStorage.removeItem('menu')
        }
    },
    persist: {
        storage: localStorage,
        key: 'menu',
        pick: ['userMenu', 'normalMenu', 'currentMenuGroup', 'currentMenuGroupAlias', 'customMenu']
    }
})
