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

import { useMenuStore } from '@/stores/menu'

// 递归补充全路由路径方法
export const processRouting = (treeData, parentPathArr = [] as any) => {
    return treeData.map((item) => {
        // 将当前节点的alias添加到路径数组中
        const currentPath = parentPathArr.concat(item.alias)
        let children = []
        if (Array.isArray(item.children) && item.children.length) {
            children = processRouting(item.children, currentPath)
        }
        return {
            ...item,
            children,
            routerPath: '/' + currentPath.join('/'),
            pathArr: currentPath
        }
    })
}

export const getSystemMenuData = (
    treeData: MenuItem[] = [],
    alias: string = 'normal'
): MenuItem[] => {
    const found = treeData.find((item) => item.alias === alias)
    return found && Array.isArray(found.children) ? found.children : []
}

// 获取当前业务菜单数据
export const getCurrentMenuData = (
    treeData: MenuItem[] = [],
    alias: string = 'normal',
    subAlias: string = ''
): MenuItem | {} => {
    const found = treeData.find((item) => item.alias === alias)
    const sysMenu = found && Array.isArray(found.children) ? found.children : []
    if (subAlias) {
        return sysMenu.find((item) => item.alias === subAlias) || sysMenu[0] || ({} as MenuItem)
    } else {
        return sysMenu[0] || ({} as MenuItem)
    }
}

// 获取当前业务菜单数据
export const getCurrentMenuDataFromParent = (
    parentData: MenuItem[] = [],
    alias: string = ''
): MenuItem | {} => {
    const found = parentData.find((item) => item.alias === alias)
    if (found) {
        return found
    } else {
        return parentData[0] || ({} as MenuItem)
    }
}

/** 获取登录后首个跳转菜单地址
 * @param menuData 菜单数据
 * @param firstMenuType 首个菜单策略，normal：系统菜单（默认），custom：自定义菜单
 * @param customTarget  自定义菜单策略下的目标菜单别名
 * @returns string 首个跳转菜单地址
 */
export const getFirstMenuPath = (menuData: MenuItem[] = []): string => {
    // 默认返回系统菜单的第一个可访问路径
    return getFisrtModulePath(menuData, '/platLayout')
}

/**
 *  获取第一个可访问路径
 * @param treeData
 * @param path
 */
export const getFisrtModulePath = (treeData: MenuItem[], path = ''): string => {
    if (
        Array.isArray(treeData[0].children) &&
        treeData[0].children.length &&
        !treeData[0].customRoute
    ) {
        path += `/${treeData[0].alias}`
        return getFisrtModulePath(treeData[0].children, path)
    } else if (!treeData[0].customRoute) {
        return path + `/${treeData[0].alias}`
    } else {
        return path
    }
}

/**
 * 根据当前路由path生成面包屑路径
 * @param currentPath 当前路由路径
 * @param menuData 菜单数据
 * @returns 面包屑路径数组
 */
export function generateBreadcrumbPath(currentPath: string, menuData: MenuItem[]): MenuItem[] {
    const breadcrumbPath: MenuItem[] = []

    const findPath = (nodes: MenuItem[], path: string): boolean => {
        for (const node of nodes) {
            // 检查当前节点是否匹配
            if (node.routerPath === path) {
                breadcrumbPath.push(node)
                return true
            }

            // 递归检查子节点
            if (node.children && node.children.length > 0) {
                if (findPath(node.children, path)) {
                    breadcrumbPath.push(node)
                    return true
                }
            }
        }
        return false
    }

    // 从根节点开始查找
    findPath(menuData, currentPath)

    // 反转数组使顺序从父到子
    return breadcrumbPath.reverse()
}

/**
 *  添加当前激活菜单,主要用于面包屑导航
 * @param route
 * @returns
 */
export function addActiveMenu(route: any) {
    const menuStore = useMenuStore()
    const normalMenuData = menuStore.getNormalMenuData
    const { title, path, parentName, name, parentRoutePath } = route
    const newActiveMenu = {
        alias: name,
        name: title,
        routerPath: '/' + parentRoutePath + '/' + path,
        pathArr: path.split('/'),
        children: [],
        customRoute: true
    }
    _addActiveMenu(normalMenuData, parentName, newActiveMenu)
    menuStore.setNormalMenu(normalMenuData)
}

function _addActiveMenu(menuData: MenuItem[], alias: string, newMenu: MenuItem) {
    for (const item of menuData) {
        if (item.alias === alias) {
            if (item.children) {
                const menuOld = item.children.find((child) => child.alias === newMenu.alias)
                if (!menuOld) {
                    item.children.push(newMenu)
                }
            } else {
                item.children = [newMenu]
            }
            return
        }
        if (item.children && item.children.length > 0) {
            _addActiveMenu(item.children, alias, newMenu)
        }
    }
}
/**
 *  添加动态路由到缓存
 *
 */
export function addCustomRoute(parentRoutePath: string, routeObj: object) {
    const menuStore = useMenuStore()
    const customMenuData = menuStore.getCustomMenuData

    customMenuData.push({
        parentRoutePath,
        routeObj
    })
    menuStore.setCustomMenu(customMenuData)
}

/**
 * 更新自定义路由
 */
export function updateCustomRoute(parentRoutePath: string, routeObj: object) {
    const menuStore = useMenuStore()
    const customMenuData = menuStore.getCustomMenuData

    // 查找并更新现有的路由
    const index = customMenuData.findIndex(
        (item: any) => (item.routeObj as any).name === (routeObj as any).name
    )

    if (index !== -1) {
        // 更新现有路由
        customMenuData[index] = {
            parentRoutePath,
            routeObj
        }
    } else {
        // 如果没找到，添加新路由
        customMenuData.push({
            parentRoutePath,
            routeObj
        })
    }

    menuStore.setCustomMenu(customMenuData)
}

const customRoutes: MenuItem[] = []
const getCustomRoutes = (treeData: MenuItem[]) => {
    treeData.forEach((item) => {
        if (item.customRoute) {
            customRoutes.push(item)
        }
        if (Array.isArray(item.children) && item.children.length > 0) {
            getCustomRoutes(item.children)
        }
    })
    return customRoutes
}

export const getCustomRouteData = (treeData: MenuItem[]) => {
    customRoutes.length = 0 // 清空之前的自定义路由
    return getCustomRoutes(treeData)
}
