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/hrefficiency',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '文档审阅',
        key: '/topnavbar00/hrefficiency/timesheet',
        // icon: <SettingOutlined />,
      },
      {
        label: '文档修改',
        key: '/topnavbar00/hrefficiency/documentUpdate',
        // icon: <SettingOutlined />,
      },
      {
        label: '智能体配置',
        key: '/topnavbar00/hrefficiency/agentSetting',
        // icon: <SettingOutlined />,
      },
      {
        label: '知识库',
        key: '/topnavbar00/hrefficiency/dataSet',
        // icon: <SettingOutlined />,
      },
      {
        label: '系统监控',
        key: '/topnavbar00/hrefficiency/systemMonitoring',
        // icon: <SettingOutlined />,
      },
      {
        label: '系统应用统计',
        key: '/topnavbar00/hrefficiency/systemApplicationStatistics',
        // icon: <SettingOutlined />,
      },
      {
        label: '后台管理',
        key: '/topnavbar00/hrefficiency/backgroundManagement',
        // icon: <SettingOutlined />,
      },
      {
        label: '智能对话',
        key: '/topnavbar00/hrefficiency/ChatConversation',
      },
      // {
      //   label: '智能体配置1',
      //   key: '/topnavbar00/hrefficiency/staffuph',
      //   // icon: <SettingOutlined />,
      // },
      // {
      //   label: '知识库',
      //   key: '/topnavbar00/hrefficiency/deptuph',
      //   // icon: <SettingOutlined />,
      // },
      // {
      //   label: '系统监控',
      //   key: '/topnavbar00/hrefficiency/allstaffuph',
      //   // icon: <SettingOutlined />,
      // },
      // {
      //   label: '系统应用统计',
      //   key: '/topnavbar00/hrefficiency/allstaffuph',
      //   // icon: <SettingOutlined />,
      // },
      // {
      //   label: '后台管理',
      //   key: '/topnavbar00/hrefficiency/allstaffuph',
      //   // icon: <SettingOutlined />,
      // },
    ]
  },
]

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([])




  const [collapsed, setCollapsed] = useState(false);
  const toggleCollapsed = () => setCollapsed(c => !c);


  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,
          children: item?.children?.map(child => ({
            key: child?.key,
            label: child?.label,
            // icon: child?.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: '12px' }} />退出登录</>,
      key: 'logout'
    }
  ]

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

  return (
    <div className={styles.layoutContainer}>
      <div className={styles.tabBarHeader} style={{ position: 'sticky', zIndex: '100', top: '0', height: '60px', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
        <Row className={styles.tabBarRow} style={{ height: '60px' }}>
          <Col xs={12} sm={12} md={12} lg={12} xl={12} className={styles.tabBarLeft}>
            {/* <img src={Logo} alt='logo' className={styles.leftLogo} /> */}
            <div style={{ fontSize: '1.2em', color: 'white', fontWeight: 'bold' }}>AI文档审阅系统</div>
            {/* <Menu mode='horizontal' className={styles.leftMenu} selectedKeys={[activeKey]} items={menuItems} onClick={value => setRouteActive(value)} /> */}
          </Col>
 
          {/* <Col xs={12} sm={12} md={12} lg={12} xl={12} className={styles.tabBarLeft}>
            <img src={Logo} alt='logo' className={styles.leftLogo} />
            <Menu mode='horizontal' className={styles.leftMenu} selectedKeys={[activeKey]} items={menuItems} onClick={value => setRouteActive(value)} />
          </Col> */}

          <Col xs={12} sm={12} md={12} lg={12} xl={12} className={styles.tabBarRight}>
            <Avatar className={styles.tabBarRightAvaTor} src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F31%2F20170731021444_2YUfe.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a120&n=0&g=0n&fmt=auto?sec=12697791271&t=ec025ed412a12612dee9cfa0e1203b6f7127' />

            <span className={styles.tabBarRightName}>{userInfo?.user_name_cn ? userInfo.user_name_cn : (userInfo?.user_name || '')}</span>

            <Dropdown dropdownRender={dropDownMenu}>
              <Button type='text' className={styles.tabBarRightBtn}><SettingOutlined /></Button>
            </Dropdown>
          </Col>
        </Row>
      </div>

      {/* 修改：当路由为智能对话页时，渲染历史会话组件（renderPageContent），其它路由不变 */}
      <div className={styles.contentMain} style={{ height: 'auto', backgroundColor: 'inherit' }}>
        <Outlet />
      </div>
 
      {/* 底部版权信息 */}
      <div className='footerCopyright' style={{
        // position: 'fixed', 
        bottom: '0',
        left: '0',
        width: '100%',
        padding: '10px 0',
        textAlign: 'center',
        backgroundColor: '#f0f2f5',
        borderTop: '1px solid #d9d9d9',
        fontSize: '14px',
        color: 'rgba(0, 0, 0, 0.45)',
        height: '69.5px',
        lineHeight: '59.5px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <div>© 2025 AI文档审阅系统. All rights reserved.</div>

      </div>
    </div>
  )
}

export default TopNavBar
