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/multidstatistics',
    // icon: <SettingOutlined />, 
    children: [
      {
        label: '员工统计',
        key: '/topnavbar00/multidstatistics/staffstatistics',
        // icon: <SettingOutlined />,
      },
    ]
  },
  {
    label: '人员管理',
    key: '/topnavbar00/staffmanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '人员信息',
        key: '/topnavbar00/staffmanage/staffinfo',
        // icon: <SettingOutlined />,
      },
      {
        label: '人员履历',
        key: '/topnavbar00/staffmanage/staffresume',
        // icon: <SettingOutlined />,
      },
      {
        label: '人员调整',
        key: '/topnavbar00/staffmanage/staffadjust',
        // icon: <SettingOutlined />,
      },
      {
        label: '工作流',
        key: '/topnavbar00/staffmanage/workflow',
        // icon: <SettingOutlined />,
      },
      {
        label: '',
        // label: '详情页',
        key: '/topnavbar00/staffmanage/particulars',
        // icon: <SettingOutlined />,
      },
    ]
  },
  {
    label: '组织管理',
    key: '/topnavbar00/organmanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '组织架构图',
        key: '/topnavbar00/organmanage/organchart',
        // icon: <SettingOutlined />,
      },
      {
        label: '部门维护',
        key: '/topnavbar00/organmanage/deptmaintain',
        // icon: <SettingOutlined />,
      }
    ]
  },
  {
    label: '考勤管理',
    key: '/topnavbar00/attendancemanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '考勤数据',
        key: '/topnavbar00/attendancemanage/attendancedata',
        // icon: <SettingOutlined />,
      }
    ]
  },
  {
    label: '绩效管理',
    key: '/topnavbar00/performancemanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '绩效列表',
        key: '/topnavbar00/performancemanage/performancelist',
        // icon: <SettingOutlined />,
      },
      {
        label: '绩效规则设置',
        key: '/topnavbar00/performancemanage/performanceruleset',
        // icon: <SettingOutlined />,
      },
      {
        label: '绩效评定',
        key: '/topnavbar00/performancemanage/performanceassess',
        // icon: <SettingOutlined />,
      }
    ]
  },
  {
    label: '薪酬管理',
    key: '/topnavbar00/salarymanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '薪酬数据',
        key: '/topnavbar00/salarymanage/salarydata',
        // icon: <SettingOutlined />,
      },
      {
        label: '薪酬规则设置',
        key: '/topnavbar00/salarymanage/salaryruleset',
        // icon: <SettingOutlined />,
      }
    ]
  },
  {
    label: '效率管理',
    key: '/topnavbar00/hrefficiency',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '工时仪表盘',
        key: '/topnavbar00/hrefficiency/timesheet',
        // icon: <SettingOutlined />,
      },
      {
        label: '员工仪表盘',
        key: '/topnavbar00/hrefficiency/staffsheet',
        // icon: <SettingOutlined />,
      },
      {
        label: '员工效率监控',
        key: '/topnavbar00/hrefficiency/staffuph',
        // icon: <SettingOutlined />,
      },
      {
        label: '部门效率监控',
        key: '/topnavbar00/hrefficiency/deptuph',
        // icon: <SettingOutlined />,
      },
      {
        label: '全员效率监控',
        key: '/topnavbar00/hrefficiency/allstaffuph',
        // icon: <SettingOutlined />,
      },
      {
        label: '作业明细报表',
        key: '/topnavbar00/hrefficiency/workreport',
        // icon: <SettingOutlined />,
      },
    ]
  },
  {
    label: '知识库',
    key: '/topnavbar00/knowledgebase',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '问答知识库',
        key: '/topnavbar00/knowledgebase/qaknowledgebase',
        // icon: <SettingOutlined />,
      },
      {
        label: '文档知识库',
        key: '/topnavbar00/knowledgebase/docknowledgebase',
        // icon: <SettingOutlined />,
      },
    ]
  },
  {
    label: '后台管理',
    key: '/topnavbar00/backendmanage',
    // icon: <SettingOutlined />,
    children: [
      {
        label: '数据字段',
        key: '/topnavbar00/backendmanage/datadict',
        // icon: <SettingOutlined />,
      },
      {
        label: '配置管理',
        key: '/topnavbar00/backendmanage/configmanage',
        // icon: <SettingOutlined />,
      },
      {
        label: '站内公告',
        key: '/topnavbar00/backendmanage/boardannouncement',
        // icon: <SettingOutlined />,
      },
      {
        label: '定时任务',
        key: '/topnavbar00/backendmanage/timedtask',
        // 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([])

  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}>
      <div className={styles.tabBarHeader}>
        <Row className={styles.tabBarRow}>
          <Col xs={16} sm={16} md={16} lg={16} xl={16} 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={8} sm={8} md={8} lg={8} xl={8} 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=a80&n=0&g=0n&fmt=auto?sec=1669779871&t=ec025ed48a1668dee9cfa0e803b6f787' />

            <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>

      <div className={styles.contentMain}>
        <Outlet />
      </div>
    </div>
  )
}

export default TopNavBar
