import React, { useState, useEffect } from 'react'
import { history, Outlet, useModel, useDispatch, useLocation, matchRoutes } from '@umijs/max'
import styles from './TopNavBar.less'
import { Menu, Row, Col, Avatar, Dropdown, Button } from 'antd'
import { HomeOutlined, SettingOutlined, LogoutOutlined } from '@ant-design/icons'
import { getPageQuery } from '@/utils/utils'
import Logo from '@/assets/logo.png'
import { userInfo } from '@/utils/globalCommon'

const menuItem = [
  {
    label: '基础信息',
    key: '/topnavbar00/business/basic',
  },
  {
    label: '计划管理',
    key: '/topnavbar00/business/planmanage',
  },
]

const TopNavBar = (props) => {
  const dispatch = useDispatch()
  const { initialState: { menu }, setInitialState } = useModel('@@initialState')
  // 测试时候放开启用本地菜单
  window.dynamicRoute = menuItem
  const dynamicRoute = window.dynamicRoute
  const location = useLocation()
  const pathName = location.pathname

  const [activeKey, setActiveKey] = useState(pathName ?? '/topnavbar00/home')
  const [menuItems, setMenuItems] = useState([])

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

    if (dynamicRoute?.length) {
      dynamicRoute?.map(item => {
        newList.push({
          key: item?.key,
          label: item?.label,
          icon: item?.icon
        })
      })

      setActiveKey(newList?.filter(item => pathName.indexOf(item.key) !== -1)[0]?.key ?? '')
    }

    setMenuItems(newList)
  }, [dynamicRoute])

  const setRouteActive = value => {
    const curKey = value.key
    const activeKeys = menuItems?.filter(item => curKey.indexOf(item.key) !== -1)[0]?.key ?? ''

    setActiveKey(activeKeys)
    history.replace(curKey)
  }

  const loginOut = async () => {
    // await outLogin()
    const { redirect } = getPageQuery()

    if (window.location.pathname !== '/login/login' && !redirect) {
      history.replace({
        pathname: '/login',
        // search: stringify({
        //   redirect: window.location.href,
        // }),
      })

      setInitialState({ currentUser: null, menu: null, menuMap: null })
      window.dynamicRoute = null
      localStorage.clear()
    }
  }

  const handleMenuClick = (e) => {
    switch (e.key) {
      case 'logout':
        loginOut()
        break
      default:
        break
    }
  }

  const dropDownMenuItems = [
    {
      label: <><LogoutOutlined style={{ marginRight: '8px' }} />退出登录</>,
      key: 'logout'
    }
  ]

  const dropDownMenu = () => (
    <Menu items={dropDownMenuItems} onClick={handleMenuClick} selectedKeys={[]} className={styles.tabBarMenu} />
  )

  return (
    <div className={styles.layoutContainer}>
      <Outlet />
    </div>
  )
}

export default TopNavBar
