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)

            setRouteActive({ key: mathRoute?.length ? pathName : defaultKey }, routes)
        }

        setMenuItems(newList)
    }, [pathName])

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

        mathRoute?.map((item, index) => {
            mathRoute?.length !== index + 1 && (openKeys = [...openKeys, item.pathname])
            mathRoute?.length === index + 1 && (selectedKeys = [...selectedKeys, item.pathname])
        })

        setOpenKey(openKeys)
        setSelectedKey(selectedKeys)
        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
