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, ConfigProvider} 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/homepage',
  },
  {
    label: '资产列表',
    key: '/topnavbar00/business/assetmanagement/assetlist',
  },
  {
    label: '资产分组',
    key: '/topnavbar00/business/assetmanagement/assetgrouping',
  },
  // 资产属性定义
  {
    label: '资产属性定义',
    key: '/topnavbar00/business/assetmanagement/assetdefined',
  },
  // 资产维保管理
  {
    label: '维保管理',
    key: '/topnavbar00/business/assetmanagement/maintenance',
  },
  // 状态管理
  {
    label: '状态管理',
    key: '/topnavbar00/business/devicemonitoring/statemanagement',
  },
  // 设备地图
  {
    label: '设备地图',
    key: '/topnavbar00/business/devicemonitoring/devicemap',
  },
  // 视频监控
  {
    label: '视频监控',
    key: '/topnavbar00/business/devicemonitoring/video',
  },
  // 工单管理
  {
    label: '工单列表',
    key: '/topnavbar00/business/serviceticket/list',
  },
  // 工单分析
  {
    label: '代办工单',
    key: '/topnavbar00/business/serviceticket/todo',
  },
  // 已办工单
  {
    label: '已办工单',
    key: '/topnavbar00/business/serviceticket/history',
  },
  // 我的工单
  {
    label: '我的工单',
    key: '/topnavbar00/business/serviceticket/my',
  },
  // 统计分析
  {
    label: '统计分析',
    key: '/topnavbar00/business/serviceticket/analysis',
  },
  // 智能巡检
  {
    label: '智能巡检',
    key: '/topnavbar00/business/inspection/inspectionTemplate',
  },
  // 巡检任务
  {
    label: '巡检任务',
    key: '/topnavbar00/business/inspection/inspectionTasks',
  },
  // 巡检记录
  {
    label: '巡检记录',
    key: '/topnavbar00/business/inspection/inspectionRecords',
  },
    //实时告警
  {
    label: '实时告警',
    key: '/topnavbar00/business/alarmcenter/implementWarnings',
  },
    //历史告警
  {
    label: '历史告警',
    key: '/topnavbar00/business/alarmcenter/historyAlarms',
  },
    //告警规则配置
  {
    label: '告警规则配置',
    key: '/topnavbar00/business/alarmcenter/ruleConfiguration',
  },
    //通知策略和告警联系人
  {
    label: '通知策略和告警联系人',
    key: '/topnavbar00/business/alarmcenter/policy',
  },
]

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} />
  )

  const theme={
    token: {
      // 核心主题色（修改这里，Input 等组件的激活态会自动同步）
      primaryColor: '#00b42a', // 例如修改为蓝色（默认），可改为 #f50、#00b42a 等
      // 可选：补充其他相关变量（如聚焦时的边框色，默认继承 primaryColor）
      colorPrimaryHover: '#39c574', // hover 时的颜色
      colorPrimaryActive: '#008743', // 点击时的颜色
    },
    components: {
      Switch: {
        colorPrimary: '#008743', // 开启状态颜色
        colorBg: '#333', // 关闭状态颜色（默认灰色）
      },
      Pagination:{
        colorPrimary:'#39c574',
      },
      Tree:{
        colorPrimary:'#006665',
        lineColor:'#006665',
        checkboxBorderColor:'#006665'
      },
      Table:{
        headerBg: '#F0F7F7', // 正确的表头背景 Token（5.x 组件专属）
        // rowSelectedBg:'#006665',
      },
      Menu:{
        activeBarHeight:0
      },
      Select:{
        activeBorderColor:'#2C9E9D',
        colorBorder:'#2C9E9D'
      },
      Input:{
        colorBorder:'#2C9E9D',
        activeBorderColor:'#2C9E9D'
      },
      DatePicker:{
        colorBorder:'#2C9E9D'
      },
      Button:{
        colorBorder:'#2C9E9D',
      },
      Checkbox:{
        colorPrimary: '#2C9E9D', // 选中时的颜色
        colorBorder: '#2C9E9D', // 未选中时的边框颜色
        colorBgChecked: '#2C9E9D', // 选中时的背景颜色
        colorText: '#333', // 文字颜色
      },
      Radio:{
        colorPrimary: '#2C9E9D', // 选中时的圆圈边框色 + 内部圆点色（核心颜色）
        colorBorder: '#2C9E9D', // 未选中时的圆圈边框色（你的需求，和选中色一致）
        colorBgChecked: '#2C9E9D', // 选中时内部圆点的颜色（可和 colorPrimary 一致）
        sizeDefault: 16, // 圆形单选框的尺寸（默认 16px，可改 14/18/20 等）
        colorText: '#333', // 单选框旁边的文字颜色（可选）
        colorTextChecked: '#2C9E9D', // 选中时的文字颜色（可选，默认继承 colorPrimary）
        // hover/聚焦状态（可选，增强交互）
        colorBorderHover: '#1A7D7C', // 未选中时 hover 边框色（比选中色深一点）
        colorPrimaryHover: '#1A7D7C', // 选中时 hover 颜色
      },
      Tabs:{
        inkBarColor:'#2C9E9D',
        itemActiveColor:'#333333',
        itemHoverColor:'#333333',
        itemSelectedColor:'#333333',
      },

    },
  }
  return (
<ConfigProvider theme={theme}>


    <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> */}
      <Outlet />
    </div>
</ConfigProvider>
  )
}

export default TopNavBar
