import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import { useDashboard } from '../../context';
import styles from './index.less';
import { useSpecialServices } from '../../../hooks/useSpecialServices';
import { SPECIAL_SERVICES } from '../../../config/specialServices';

// 导航项数据类型
interface NavItem {
  key: string;
  label: string;
  icon: string;
  hasChildren?: boolean;
  children?: NavSubItem[];
  nonClickable?: boolean; // 添加标识不可点击的属性
  alwaysShowChildren?: boolean; // 添加标识总是展示子菜单的属性
}

interface NavSubItem {
  key: string;
  label: string;
  pageKey?: string; // 对应的页面key
  serviceId?: string; // 对应专项服务ID
  children?: NavSubItem[]; // 允许子项嵌套，支持二级子菜单
  nonClickable?: boolean; // 添加标识不可点击的属性
  alwaysShowChildren?: boolean; // 允许子项总是显示子菜单
}

const NavigationBar: React.FC = () => {
  const { backToHome, navigateTo, activePage } = useDashboard();
  const [hoveredKey, setHoveredKey] = useState<string | null>(null);
  const { serviceList, handleServiceAction } = useSpecialServices();
  
  // 专项服务配置映射表
  const [serviceConfigs, setServiceConfigs] = useState<Record<string, any>>({});
  
  // 初始化专项服务配置映射表
  useEffect(() => {
    if (serviceList.length > 0) {
      const configMap: Record<string, any> = {};
      
      // 根据API获取的服务列表更新服务配置
      SPECIAL_SERVICES.forEach(service => {
        const apiService = serviceList.find(item => item.id === service.id);
        configMap[service.id] = {
          ...service,
          targetUrl: apiService?.linkUrl || ''
        };
      });
      
      setServiceConfigs(configMap);
    }
  }, [serviceList]);
  
  // 导航项数据
  const navItems: NavItem[] = [
    {
      key: 'home',
      label: '首页',
      icon: 'map-navigate-logo-1.png',
    },
    {
      key: 'overview',
      label: '整体概况',
      icon: 'map-navigate-logo-5.png',
    },
    {
      key: 'cityStatus',
      label: '城市实况',
      icon: 'map-navigate-logo-2.png',
      hasChildren: true,
      children: [
        { key: 'cityStatus1', label: '智慧照明' },
        { key: 'cityStatus2', label: '智慧井盖' },
        { key: 'cityStatus3', label: '共享单车' },
        { key: 'cityStatus4', label: '餐饮油烟', pageKey: 'restaurantOil' },
        { key: 'cityStatus5', label: '智慧管廊' },
        { key: 'cityStatus6', label: '智慧公厕' },
        { key: 'cityStatus7', label: '数字巡查' },
        { key: 'cityStatus8', label: '网络舆情' },
        { key: 'cityStatus9', label: '百姓投诉' },
      ]
    },
    {
      key: 'videoMonitor',
      label: '视频监控',
      icon: 'map-navigate-logo-3.png',
      hasChildren: true,
      children: [
        { key: 'videoMonitor1', label: '重点区域', pageKey: 'videoKeyAreas'  },
        { key: 'videoMonitor2', label: '背街小巷', pageKey: 'videoBackStreets' },
        { key: 'videoMonitor3', label: '农贸市场', pageKey: 'videoFarmersMarket'  },
        { key: 'videoMonitor4', label: '地铁口', pageKey: 'videoSubwayEntrances'  },
      ]
    },
    {
      key: 'industryStatus',
      label: '行业概况',
      icon: 'map-navigate-logo-4.png',
      hasChildren: true,
      children: [
        // { key: 'industryStatus1', label: '环境卫生' },
        { key: 'industryStatus1', label: '环境卫生', pageKey: 'environment' },
        { key: 'industryStatus2', label: '市政设施', pageKey: 'municipal' },
        { key: 'industryStatus3', label: '景观照明', pageKey: 'landscapeLighting' },
        { 
          key: 'industryStatus4', 
          label: '执法管理',
          nonClickable: true, // 标识不可点击
          alwaysShowChildren: true, // 标识总是展示子菜单
          children: [
            { key: 'lawEnforcement1', label: '行政处罚', pageKey: 'lawEnforcementPunishment' },
            { key: 'lawEnforcement2', label: '市区协同', pageKey: 'lawEnforcementCoordination' },
            { key: 'lawEnforcement3', label: '日常巡查', pageKey: 'lawEnforcementPatrol' },
          ]
        },
        { key: 'industryStatus5', label: '生活垃圾', pageKey: 'domesticWaste' },
        { key: 'industryStatus6', label: '建筑垃圾', pageKey: 'constructionWaste' },
        { key: 'industryStatus7', label: '市容秩序', pageKey: 'cityAppearance' },
      ]
    },
    {
      key: 'specialService',
      label: '专项服务',
      icon: 'map-navigate-logo-6.png',
      hasChildren: true,
      children: [
        { key: 'specialService1', label: '指挥调度', serviceId: 'zhdd' },
        { key: 'specialService2', label: '众智成城', serviceId: 'zzcc' },
        { key: 'specialService3', label: '诚管24', serviceId: 'cgtf' },
        { key: 'specialService4', label: '体征指数', serviceId: 'tzzs' },
        { key: 'specialService5', label: '网格基座', serviceId: 'wgjz' },
        { key: 'specialService6', label: '数据底座', serviceId: 'zzcc_sjdz' },
        { key: 'specialService7', label: '感知治理', serviceId: 'zzcc_gz' },
        { key: 'specialService8', label: '信息安全', serviceId: 'xxaq' },        
      ]
    },
  ];

  // 处理导航项点击
  const handleNavItemClick = (item: NavItem) => {
    if (item.nonClickable) {
      return; // 如果是不可点击的项，直接返回
    }
    if (item.key === 'home') {
      // 首页按钮点击时返回首页
      backToHome();
      setHoveredKey(null);
    } else if (item.key === 'overview') {
      // 按钮点击时跳转  整体概况
      navigateTo('overallSituation');
      setHoveredKey(item.key);
    } else if (!item.hasChildren) {
      // 普通导航项，设置为激活状态
      setHoveredKey(item.key);
    }
  };

  // 处理导航项悬停
  const handleNavItemHover = (item: NavItem) => {
    // console.log('**/////// handleNavItemHover item', item, item.hasChildren)
    if (item.hasChildren) {
      // 有子项的导航项，展开子菜单
      setHoveredKey(item.key);
    }
  };
  
  // 处理导航容器鼠标离开
  const handleNavContainerMouseLeave = (item: NavItem) => {
    // console.log('***** handleNavContainerMouseLeave item', item, item.hasChildren)
    if (item.hasChildren) {
      setHoveredKey(null);
    }
  };

  // 处理子导航项点击
  const handleSubItemClick = (parentKey: string, subItem: NavSubItem) => {
    if (subItem.nonClickable) {
      return; // 如果是不可点击的项，直接返回
    }
    
    // 处理专项服务类型
    if (parentKey === 'specialService' && subItem.serviceId) {
      const serviceConfig = serviceConfigs[subItem.serviceId];
      if (serviceConfig) {
        handleServiceAction(serviceConfig);
      }
      // 关闭子菜单
      setHoveredKey(null);
      return;
    }
    
    // 检查子项是否有对应的页面key
    if (subItem.pageKey) {
      // 导航到对应页面
      navigateTo(subItem.pageKey);
      // 关闭子菜单
      setHoveredKey(null);
    } else {
      console.log(`Clicked sub item: ${parentKey} - ${subItem.key}`);
    }
  };

  // 判断子项是否为当前页面
  const isActiveSubItem = (subItem: NavSubItem) => {
    return subItem.pageKey === activePage;
  };

  return (
    <div className={styles.navigationBar}>
      <div className={styles.navItems}>
        {navItems.map(item => (
          <div 
            key={item.key} 
            className={styles.navItemContainer}
            onMouseLeave={() => handleNavContainerMouseLeave(item)}
          >
            <div
              className={classNames(styles.navItem, {
                [styles.navItemActive]: hoveredKey === item.key || 
                  (item.hasChildren && item.children?.some(sub => sub.pageKey === activePage)) || 
                  (item.hasChildren && item.children?.some(sub => sub.children && sub.children?.some(subSub => subSub.pageKey === activePage))) || 
                  (item.key === 'overview' && activePage === 'overallSituation')
              })}
              onClick={() => handleNavItemClick(item)}
              onMouseEnter={() => handleNavItemHover(item)}
            >
              <img 
                src={require(`@/assets/images/V-2504/${item.icon}`)} 
                className={styles.navIcon}
                alt=""
              />
              <span className={styles.navLabel}>{item.label}</span>
            </div>
            
            {/* 子导航项 */}
            {hoveredKey === item.key && item.hasChildren && item.children && (
              <div 
                className={styles.subNavItems}
                onMouseEnter={() => {
                  //console.log('***** son onMouseEnter item', item)
                  setHoveredKey(item.key)
                }} // 确保子菜单悬停时父菜单仍保持激活
              >
                {item.children.map(subItem => (
                  <div
                    key={subItem.key}
                    className={classNames(styles.subNavItem, {
                      [styles.subNavItemActive]: isActiveSubItem(subItem),
                      // [styles.subNavItemDisabled]: false,
                      // [styles.subNavItemDisabled]: isActiveSubItem(subItem),
                      [styles.subNavItemDisabled]: isActiveSubItem(subItem) || subItem.nonClickable,
                      [styles.subNavItemWithChildren]: subItem.children && subItem.children.length > 0
                    })}
                    onClick={() => !isActiveSubItem(subItem) && !subItem.children && !subItem.nonClickable && handleSubItemClick(item.key, subItem)}
                  >
                    {subItem.label}
                    {subItem.nonClickable && subItem.children && <span className={styles.subNavArrow}>›</span>}
                    
                    {/* 渲染二级子菜单 */}
                    {(hoveredKey === item.key || subItem.alwaysShowChildren) && subItem.children && subItem.children.length > 0 && (
                      <div 
                        className={classNames(styles.subSubNavItems, {
                          [styles.alwaysVisible]: subItem.alwaysShowChildren
                        })}
                        onMouseEnter={() => setHoveredKey(item.key)} // 确保子菜单悬停时父菜单仍保持激活
                      >
                        {subItem.children.map(subSubItem => (
                          <div
                            key={subSubItem.key}
                            // className={classNames(styles.subNavItem)}
                            className={classNames(styles.subNavItem, {
                              [styles.subNavItemActive]: isActiveSubItem(subSubItem),
                              [styles.subNavItemDisabled]: isActiveSubItem(subSubItem)
                            })}
                            onClick={() => !isActiveSubItem(subSubItem) && handleSubItemClick(item.key, subSubItem)}
                          >
                            {subSubItem.label}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default NavigationBar; 