import { useEffect, useState } from 'react';
import { Badge, Layout, Menu } from 'antd';
import { AdminRouterItem, routes } from '../../router';
import { useLocation, useNavigate } from 'react-router-dom';
import useMessagesHook from '@src/hooks/messages';

const { Sider } = Layout;

const getMenuItems = (routes: AdminRouterItem[], notReadMessageCount: number): any[] => {
  return routes.map(itm => {
    if (!itm.meta) return null
    let children: any[] = []
    if (itm.children) children = getMenuItems(itm.children, notReadMessageCount)
    
    const menuItem = children.length > 0 ? {
      ...itm.meta,
      children
    } : {
      ...itm.meta,
      path: itm.path,
			}    
    // 为消息菜单添加未读数量徽章
    if (menuItem.key === '/messages' && notReadMessageCount > 0) {
      menuItem.extra = <Badge count={notReadMessageCount} />
    }
    
    return menuItem
  }).filter(itm => !!itm)
}

/**
 * PageSidebar
 * @param props {autoCollapse?: boolean} automatic collapes menu when click another menu
 * @returns
 */
const PageSidebar = (props: {
  autoCollapse?: boolean
}) => {
	const { notReadMessageCount } = useMessagesHook()
	const [menuItems, setMenuItems] = useState<any[]>([])

	useEffect(() => {
		const _menuItems = getMenuItems(routes, notReadMessageCount)
		console.log('menuItems', _menuItems)
		setMenuItems(_menuItems)
	}, [notReadMessageCount])
  const { autoCollapse = true } = props
  const navigate = useNavigate()
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [lastOpenedMenu, setLastOpenedMenu] = useState<string[]>([])
  const location = useLocation()

	const onSwitchMenu = ({ key, keyPath }: { key: string; keyPath: string[] }) => {
    if (autoCollapse && keyPath.slice(1)) setLastOpenedMenu(keyPath.slice(1))
    navigate(key)
  }

  const onOpenChange = (openKeys: string[]) => {
    setLastOpenedMenu(openKeys)
  }

	useEffect(() => {
		setSelectedKeys([`${location.pathname}`])
		const lastOpenedMenu = location.pathname.split('/')?.[1]
		if (lastOpenedMenu) {
			setLastOpenedMenu([`/${lastOpenedMenu}`])
		}
    navigate(location.pathname)
  }, [location.pathname, navigate])

  return (
		<Sider theme='light'>
      <Menu openKeys={lastOpenedMenu} onOpenChange={onOpenChange} selectedKeys={selectedKeys} mode="inline" items={menuItems} onClick={onSwitchMenu} />
    </Sider>
  )
}

export default PageSidebar
