import { shallowRef } from 'vue'
import { AuthType } from '@/constants/menu'
import { getMenus } from '@/services/api/user'
import { defineStore } from '../store'
import { sessionData } from '../storage'

export const useRouterStore = defineStore(() => {
    const loading = shallowRef(false)
    const userRoutes = sessionData.getRef('userRoutes')

    /** 获取用户路由 */
    const getUserRoutes = async () => {
        try {
            loading.value = true
            const res = await getMenus()
            userRoutes.value = res.data
        } finally {
            loading.value = false
        }
    }

    // 根据 code 查找对应的子路由
    const getChildrenRoutes = (routeName: string) => {
        const findChildren = (data: Model.MenusRsp[]): Model.MenusRsp[] => {
            for (const item of data) {
                const { resourceCode, children } = item
                if (resourceCode === routeName) return children ?? []
                if (children) {
                    const res = findChildren(children)
                    if (res.length) return res
                }
            }
            return []
        }
        return findChildren(userRoutes.value)
    }

    // 过滤菜单
    const filterMenus = (data: Model.MenusRsp[]) => {
        return data.reduce<Model.MenusRsp[]>((pre, cur) => {
            if (cur.show && cur.authType === AuthType.Menu) {
                pre.push({
                    ...cur,
                    children: cur.children ? filterMenus(cur.children) : [],
                })
            }
            return pre
        }, [])
    }

    // 获取用户菜单(无限级)
    const getUserMenus = (level = 0) => {
        // 过滤层级
        const filterLevel = (data: Model.MenusRsp[], n: number): Model.MenusRsp[] => {
            if (level) {
                return data.map((e) => ({ ...e, children: n <= 1 ? [] : filterLevel(e.children ?? [], n - 1) }))
            }
            return data
        }
        return filterMenus(filterLevel(userRoutes.value, level))
    }

    // 获取子菜单
    const getChildrenMenus = (routeName: string) => {
        const children = getChildrenRoutes(routeName)
        return filterMenus(children)
    }

    // 清除用户路由信息
    const clearUserRoutes = () => {
        userRoutes.value = []
    }

    return {
        loading,
        userRoutes,
        filterMenus,
        getUserRoutes,
        getChildrenRoutes,
        getUserMenus,
        getChildrenMenus,
        clearUserRoutes
    }
})