import React, { useState, useEffect } from 'react'
import { history, Outlet, useLocation, matchRoutes } from '@umijs/max'
import { Menu, Tabs } from 'antd'
import './SystemContentList.less'
import { formatRoute, getDefaultRoute } from '@/utils/routeUtils'

const SystemContentList = (props) => {
    const dynamicRoute = window.dynamicRoute
    console.log(dynamicRoute)
    const location = useLocation()
    const pathName = location.pathname
    const [openKey, setOpenKey] = useState([])
    const [selectedKey, setSelectedKey] = useState([])
    const [menuItems, setMenuItems] = useState([])
    let defaultKey = ''

    useEffect(() => {
        if (!dynamicRoute || dynamicRoute?.length === 0) return
        let newList = []
        let routes = []

        if (dynamicRoute?.length) {
            let tempRoute = dynamicRoute?.filter(item => pathName.indexOf(item.key) !== -1) ?? []

            newList = formatRoute(tempRoute[0]?.children)
            routes = formatRoute(tempRoute[0]?.children, true)
            defaultKey = getDefaultRoute(routes)
            const mathRoute = matchRoutes(routes, pathName)

            // 如果当前路径匹配到菜单路由，或者是以当前模块开头的路径（如详情页），都不强制跳转
            const shouldUseCurrentPath = mathRoute?.length > 0 || pathName.startsWith(tempRoute[0]?.key + '/')
            setRouteActive({ key: shouldUseCurrentPath ? pathName : defaultKey }, routes)
        }

        setMenuItems(newList)
    }, [pathName])

    const setRouteActive = (value, menu) => {
        const curKey = value.key
        console.log(curKey,'7777777777777')
        const tempMenu = menu ?? menuItems ?? []
        const mathRoute = matchRoutes(tempMenu, curKey)
        let openKeys = []
        let selectedKeys = []

        if (mathRoute?.length > 0) {
            // 如果找到匹配的菜单路由，正常处理
            mathRoute?.map((item, index) => {
                mathRoute?.length !== index + 1 && (openKeys = [...openKeys, item.pathname])
                mathRoute?.length === index + 1 && (selectedKeys = [...selectedKeys, item.pathname])
            })
        } else {
            // 如果是不在菜单中的路由（如详情页），尝试激活父级菜单
            const pathSegments = curKey.split('/').filter(Boolean)
            for (let i = pathSegments.length - 1; i > 0; i--) {
                const parentPath = '/' + pathSegments.slice(0, i).join('/')
                const parentRoute = matchRoutes(tempMenu, parentPath)
                if (parentRoute?.length > 0) {
                    parentRoute?.map((item, index) => {
                        parentRoute?.length !== index + 1 && (openKeys = [...openKeys, item.pathname])
                        parentRoute?.length === index + 1 && (selectedKeys = [...selectedKeys, item.pathname])
                    })
                    break
                }
            }
        }

        setOpenKey(openKeys)
        setSelectedKey(selectedKeys)
        
        // 只有当前路径与目标路径不同时才执行跳转
        if (location.pathname !== curKey) {
            history.replace(curKey)
        }
    }

    return (
        <div className='pageContainer systemContent'>
            <div className='leftMenu'>
                <Menu
                    openKeys={openKey}
                    selectedKeys={selectedKey}
                    items={menuItems}
                    onClick={value => setRouteActive(value)}
                    onOpenChange={value => setOpenKey(value)}
                    mode='horizontal'
                />
            </div>

            <div className='rightContentMain'>
                <Outlet />
            </div>
        </div>
    )
}

export default SystemContentList
