import blueBg from '@/assets/images/SecurityServiceOverview/right/blueBg.png';
import orangeBg from '@/assets/images/SecurityServiceOverview/right/orangeBg.png';
import redBg from '@/assets/images/SecurityServiceOverview/right/redBg.png';
import yellowBg from '@/assets/images/SecurityServiceOverview/right/yellowBg.png';
import risk1 from '@/assets/images/urbanSituation/risk1.svg';
import risk2 from '@/assets/images/urbanSituation/risk2.svg';
import risk3 from '@/assets/images/urbanSituation/risk3.svg';
import risk4 from '@/assets/images/urbanSituation/risk4.svg';

import CooglMap from '@/components/CooglMap';
import Modal from '@/components/HncyModal';
import { useGlobalModalServices } from '@/pages/GlobalModalServices/provider';
import services from '@/services';
import { smoothScrollTo } from '@/utils';
import BMapService from '@/utils/mapService';
import { getColorByIndex } from '@/utils/ui';
import { useModel, useRequest } from '@umijs/max';
import { Flex, Image } from 'antd';
import dayjs from 'dayjs';
import React, { CSSProperties, useEffect, useRef, useState, useMemo, useCallback } from 'react';

import BaseInfo from '@/pages/SecurityServiceOverview/components/BaseInfo';
import { joinPictureHttp } from '@/utils/comm';
import Apps from '../components/Apps';
import LeftTab from '../components/LeftTab';
import RiskIssue from '../RiskIssue';
import styles from './index.less';
import PopoverCard from './PopoverCard';
import { useDashboard } from '../../context';
// import { CooglLoadArea } from './loadAreaNew';
// import { CooglLoadArea } from './loadArea-1.3.1';
// import { CooglLoadArea } from './loadArea-1.4.0';
import { CooglLoadArea } from './loadArea-1.4.1';
import { useMapState } from '../../MapStateContext';
import classNames from 'classnames';

export const colorConfig: Record<
  string,
  {
    color: CSSProperties['color'];
    bg: string;
    icon: string;
    bigIcon: string;
    tag: string;
  }
> = {
  红色预警: {
    //红色风险
    color: '#FFBCBC',
    bg: redBg,
    icon: risk1,
    bigIcon: 'redIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag1.png'),
  },
  橙色预警: {
    //橙色风险
    color: '#FDDFCE',
    bg: orangeBg,
    icon: risk2,
    bigIcon: 'orangeIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag2.png'),
  },
  黄色预警: {
    //黄色风险
    color: '#FFE892',
    bg: yellowBg,
    icon: risk3,
    bigIcon: 'yellowIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag3.png'),
  },
  一般预警: {
    //一般风险
    color: '#BFE4FF',
    bg: blueBg,
    icon: risk4,
    bigIcon: 'blueIcon',
    tag: require('@/assets/images/SecurityServiceOverview/dtyjtag4.png'),
  },
};

// 添加组件属性接口
interface DistrictMapCustomizedProps {
  regionCode?: string;
  dataCode?: string;
  gridType?: string;
  onMapInstanceChange?: (instance: any) => void;
}

// 在import部分下方添加辅助函数
const isOilSmokeEventDataType = (dataCode: string) => {
  return dataCode === '10127'; // 只有油烟事件才显示事件列表
};

/** 地图 */
const DistrictMapCustomized: React.FC<DistrictMapCustomizedProps> = ({
  regionCode = '5101',
  dataCode = '10127',
  gridType = '02', // 油烟事件
  onMapInstanceChange
}) => {
  const { initialState } = useModel('@@initialState');
  const { areaId } = initialState;
  const { dispatch } = useGlobalModalServices();
  const { mapState } = useMapState();
  const [playingStatus, setPlayingStatus] = useState(false);
  //区域选择
  const [selected, setSelected] = useState<any>();

  const [checkedKeys, setCheckedKeys] = useState([
    // '安全风险',
    // '红色预警',
    // '橙色预警',
    // '黄色预警',
    // '一般预警',
    '城市问题',
    '其他问题',
    '突出问题',
  ]);
  const MapRef = useRef<any>();

  const eventHtmlRef = useRef<HTMLDivElement>(null);
  const { indexs } = useModel('regionalIndex', (store) => ({
    indexs: store.indexs,
  }));

  // 预警事件详情弹窗
  const [detailModalOpt, setDetailModalOpt] = useState<any>({
    open: false,
    title: '',
    eventId: '',
  });

  const [leftTabKey, setLeftTabKey] = useState('1');
  const [data, setData] = useState<any[]>([]);
  const [eventData, setEventData] = useState<any[]>([]);

  // Add this state to track the current zoom level
  const [currentZoom, setCurrentZoom] = useState(8);

  // Modify the fetchVisiblePolygons to store full data
  const [fullPolygonData, setFullPolygonData] = useState<any[]>([]);

  // Add a state to track if map is ready
  const [isMapReady, setIsMapReady] = useState(false);

  const { activePage } = useDashboard();
  const isHomePage = activePage === 'home';

  // 修改状态声明，使用useRef同步最新值
  const currentZoomRef = useRef(currentZoom);
  useEffect(() => {
    currentZoomRef.current = currentZoom;
  }, [currentZoom]);

  // Add state to track the CooglLoadArea instance
  const [areaMapInstance, setAreaMapInstance] = useState<any>(null);

  // 存储 dispatch 的引用以便在回调中使用
  const dispatchRef = useRef<any>(null);

  // 添加 mapState 引用以获取最新值
  const mapStateRef = useRef<any>(null);

  // 保存最新的 dispatch 引用
  useEffect(() => {
    dispatchRef.current = dispatch;
  }, [dispatch]);

  // 保存最新的 mapState 引用
  useEffect(() => {
    mapStateRef.current = mapState;
  }, [mapState]);

  // 在地图实例状态变化时，调用父组件传递的回调
  useEffect(() => {
    if (areaMapInstance && onMapInstanceChange) {
      onMapInstanceChange(areaMapInstance);
    }
  }, [areaMapInstance, onMapInstanceChange]);

  // 添加 ref 存储当前数据类型
  const dataCodeRef = useRef(dataCode);

  // 存储时间范围参数
  const [timeRange, setTimeRange] = useState({
    startTime: '',
    endTime: ''
  });

  const getGridTypeByDataCode = (dataCode: string) => {
    if (dataCode === '10127') {
      return '02'; // 油烟事件
    } else if (dataCode === '399') {
      return '09'; // 餐饮企业
    } else if (dataCode === '20102') {
      return '01'; // 油烟告警，保持与油烟事件相同gridType
    }
    return gridType;
  }

  // 加载地图js区域数据
  const loadCooglMapAreaData = (viewer: any) => {
    try {
      console.log('开始初始化地图实例');
      // 创建地图实例
      let token = '24e46ea5-73df-4c84-93b1-7513a2507f8f';
      const areaMapIns = new CooglLoadArea(viewer, token);

      console.log('地图实例创建成功，设置初始参数');

      // 设置实例的初始参数 - 使用 MapStateContext 中的参数
      const initialRegionCode = mapState.regionCode || regionCode;
      const initialDataCode = mapState.dataCode || dataCode;
      const initialGridType = mapState.gridType || getGridTypeByDataCode(initialDataCode);

      // 确保使用激活面板的时间
      const currentTimeRange = mapState.activePanel === 'left' ? 
        mapState.leftPanelTime : 
        mapState.rightPanelTime;

      console.log('地图初始化参数:', {
        regionCode: initialRegionCode,
        dataCode: initialDataCode,
        gridType: initialGridType,
        activePanel: mapState.activePanel,
        startTime: currentTimeRange.startTime,
        endTime: currentTimeRange.endTime
      });

      areaMapIns.params = {
        regionCode: initialRegionCode,
        gridType: initialGridType,
        startTime: currentTimeRange.startTime,
        endTime: currentTimeRange.endTime,
        dataCode: initialDataCode,
        hasChildren: 1
      };

      // 设置点位点击回调 - 使用引用解决闭包问题
      // @ts-ignore
      areaMapIns.imageGraphicOfCommunityEvent = function (detail: any) {
        // 处理点位点击事件
        console.log('点位详情:', detail);

        // 使用引用获取最新的 dispatch 和 mapState
        const currentDispatch = dispatchRef.current;
        const currentMapState = mapStateRef.current;

        // 根据最新的 dataCode 决定弹窗类型
        if (detail && currentDispatch && currentMapState) {
          const currentDataCode = currentMapState.dataCode;
          console.log('当前 dataCode:', currentDataCode);

          if (currentDataCode === '399') {
            // 餐饮企业 - 显示企业详情
            currentDispatch.push('RestaurantOilFacility', {
              title: '餐饮油烟企业详情',
              w: 'fit-content',
              props: {
                deviceId: detail.eventId || detail.id,
                deviceName: detail.deviceName || detail.standardEventTitle,
                startTime: currentMapState.activePanel === 'left' ? 
                  currentMapState.leftPanelTime.startTime : 
                  currentMapState.rightPanelTime.startTime,
                endTime: currentMapState.activePanel === 'left' ? 
                  currentMapState.leftPanelTime.endTime : 
                  currentMapState.rightPanelTime.endTime
              },
            });
          } else if (currentDataCode === '20102') {
            // 油烟告警 - 显示告警详情
            currentDispatch.push('RestaurantOilAlarm', {
              title: '餐饮油烟告警详情',
              w: 'fit-content',
              props: {
                deviceId: detail.eventId || detail.id,
                deviceName: detail.deviceName || detail.standardEventTitle,
                startTime: currentMapState.activePanel === 'left' ? 
                  currentMapState.leftPanelTime.startTime : 
                  currentMapState.rightPanelTime.startTime,
                endTime: currentMapState.activePanel === 'left' ? 
                  currentMapState.leftPanelTime.endTime : 
                  currentMapState.rightPanelTime.endTime
              },
            });
          } else {
            // 事件（默认）或油烟事件 - 显示事件详情
            let theTitle = currentDataCode === '10127' ? '餐饮油烟事件详情' : '事件详情';
            currentDispatch.push('EventDetail', {
              title: theTitle,
              w: 'fit-content',
              props: {
                eventId: detail.eventId || detail.id,
              },
            });
          }
        }
      };

      // 添加处理区域切换的方法
      const originalAddArea = areaMapIns.addArea;
      areaMapIns.addArea = function (clearData = false) {
        console.log(`地图区域更新: 区域=${this.params.regionCode}, 清除数据=${clearData}`);
        return originalAddArea.call(this, clearData);
      };

      // 初始化地图
      console.log('调用地图初始化方法');
      areaMapIns.mapInit();

      // 保存实例引用并通知父组件
      console.log('地图初始化完成，设置实例引用');
      setAreaMapInstance(areaMapIns);

      // 确保实例被正确传递给父组件
      if (onMapInstanceChange) {
        console.log('通知父组件地图实例已创建');
        onMapInstanceChange(areaMapIns);
      } else {
        console.warn('onMapInstanceChange回调未提供，无法通知父组件');
      }

      return areaMapIns;
    } catch (error) {
      console.error('地图初始化失败:', error);
      return null;
    }
  };

  // 监听数据类型变化
  useEffect(() => {
    // 更新 ref 值以获取最新的 dispatch
    dispatchRef.current = dispatch;

    // 更新当前数据类型
    dataCodeRef.current = dataCode;

    // 监听数据类型变化事件
    const handleDataTypeChange = (event: CustomEvent) => {
      const newDataCode = event.detail?.dataCode;
      if (newDataCode) {
        dataCodeRef.current = newDataCode;
      }
    };

    // 添加事件监听
    window.addEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);

    // 清理事件监听
    return () => {
      window.removeEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
    };
  }, [dataCode, dispatch]);

  // 获取采样率
  const getSamplingRate = (zoomLevel: number) => {
    let samplingRate;

    if (zoomLevel <= 7) {
      samplingRate = 20; // 1/20 sampling for very zoomed out
    } else if (zoomLevel <= 9) {
      samplingRate = 15; // 1/10 sampling for normal view
    } else if (zoomLevel <= 12) {
      samplingRate = 10; // 1/5 sampling for zoomed in
    } else if (zoomLevel <= 15) {
      samplingRate = 2; // 1/2 sampling for more detail
    } else {
      samplingRate = 1; // Full detail for maximum zoom
    }

    return samplingRate;
  }


  useEffect(() => {
    // 获取地图边界 只获取一次 --- 现在不需要获取了
    services.Physicalsign.getObjectPolygon({
      physicalSignType: 1,
      objectHierarchy: 1,
      // objectId: '510107',
    }).then((res) => {
      setData(res.data);
    });
  }, []);

  // 添加当前数据类型的状态
  const [currentDataType, setCurrentDataType] = useState(dataCode);

  // 修改fetchEvents函数，添加时间参数
  const fetchEvents = useCallback((overrideRegionCode?: string, overrideDataCode?: string) => {
    // 获取当前的数据类型，优先使用传入的覆盖值
    const effectiveDataCode = overrideDataCode || currentDataType;
    
    // 只有当数据类型为油烟事件时才获取事件数据
    if (!isOilSmokeEventDataType(effectiveDataCode)) {
      console.log('当前数据类型不是油烟事件，跳过获取事件列表');
      return;
    }
    
    // 获取当前的区域码，根据不同级别处理参数
    // 优先使用传入的覆盖值，否则使用 mapState 中的值
    const currentRegionCode = overrideRegionCode || mapState.regionCode;
    let districtCode, streetCode;

    // 处理参数规则：成都市不填，区县只填区县码，街道两个都填
    if (currentRegionCode && currentRegionCode.length > 4) {
      if (currentRegionCode === '5101') {
        // 成都市级，不需要填写区县和街道码
        districtCode = undefined;
        streetCode = undefined;
      } else if (currentRegionCode.length === 6) {
        // 区县级，只填区县码
        districtCode = currentRegionCode;
        streetCode = undefined;
      } else if (currentRegionCode.length === 9) {
        // 街道级，区县码和街道码都要填
        districtCode = currentRegionCode.substring(0, 6);
        streetCode = currentRegionCode;
      }
    }

    // 数据类型对应 subTypeCode
    const subTypeCode = effectiveDataCode;
    
    // 获取最新的右侧面板时间参数 - 使用 mapStateRef 确保获取最新值
    const currentMapState = mapStateRef.current;
    const rightPanelTime = currentMapState?.rightPanelTime || mapState.rightPanelTime;
    
    // 准备时间参数
    const timeParams: any = {
      type: rightPanelTime.type, // 1.年 2.月 3.日 4.自定义
    };
    
    // 根据时间类型设置不同的参数
    if (rightPanelTime.type === 'year') {
      timeParams.type = '1';
      timeParams.date = rightPanelTime.startTime;
    } else if (rightPanelTime.type === 'month') {
      timeParams.type = '2';
      timeParams.date = rightPanelTime.startTime;
    } else if (rightPanelTime.type === 'day') {
      timeParams.type = '3';
      timeParams.date = rightPanelTime.startTime;
    } else if (rightPanelTime.type === 'range') {
      timeParams.type = '4';
      timeParams.customizeStart = rightPanelTime.startTime;
      timeParams.customizeEnd = rightPanelTime.endTime;
    }

    console.log('获取最新事件，参数:', {
      regionCode: currentRegionCode,
      districtCode,
      streetCode,
      subTypeCode,
      timeParams
    });

    services.CityProblemApi.getUpToDateEventOther({
      page: 1,
      count: 10,
      subTypeCode: subTypeCode,
      districtCode: districtCode,
      streetCode: streetCode,
      // 添加时间参数
      type: timeParams.type,
      date: timeParams.date,
      customizeStart: timeParams.customizeStart,
      customizeEnd: timeParams.customizeEnd
    }).then((res: any) => {
      console.log('getUpToDateEvent', res);
      if (res.code === 200) {
        setEventData(res.data?.items);
      }
    });
  }, [currentDataType, mapState.regionCode, mapState.rightPanelTime]);

  // 修改监听数据类型变化的事件处理函数
  useEffect(() => {
    // 初始获取事件数据 - 只有当当前数据类型为油烟事件时才获取
    if (isOilSmokeEventDataType(dataCode)) {
      fetchEvents();
    }

    // 监听区域变化事件
    const handleRegionChange = (event: CustomEvent) => {
      console.log('====>区域变化', event.detail);
      
      // 只有当当前数据类型为油烟事件时才获取
      if (isOilSmokeEventDataType(currentDataType)) {
        // 使用事件中的区域代码，而不是 mapState 中的值
        if (event.detail && event.detail.regionCode) {
          fetchEvents(event.detail.regionCode);
        } else {
          fetchEvents();
        }
      }
    };

    // 监听数据类型变化事件
    const handleDataTypeChange = (event: CustomEvent) => {
      console.log('====>数据类型变化', event.detail);
      
      // 更新当前数据类型状态
      if (event.detail && event.detail.dataCode) {
        setCurrentDataType(event.detail.dataCode);
        
        // 只有当变化后的数据类型为油烟事件时才获取事件数据
        if (isOilSmokeEventDataType(event.detail.dataCode)) {
          // 直接使用事件中的dataCode，无需等待mapState更新
          fetchEvents(undefined, event.detail.dataCode);
        } else {
          // 如果不是油烟事件，清空事件数据
          setEventData([]);
        }
      } else {
        fetchEvents();
      }
    };

    // 添加事件监听
    window.addEventListener('mapRegionChange', handleRegionChange as EventListener);
    window.addEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);

    // 组件卸载时移除事件监听
    return () => {
      window.removeEventListener('mapRegionChange', handleRegionChange as EventListener);
      window.removeEventListener('mapDataTypeChange', handleDataTypeChange as EventListener);
    };
  }, [fetchEvents, dataCode, currentDataType]);

  // 添加时间变化事件监听
  useEffect(() => {
    // 只在数据类型为油烟事件时才处理时间变化
    if (isOilSmokeEventDataType(currentDataType)) {
      // 时间变化时重新获取事件数据
      fetchEvents();
    }
  }, [mapState.rightPanelTime, fetchEvents, currentDataType]);

  // 添加时间变化事件处理
  useEffect(() => {
    const handleMapDateChange = (event: CustomEvent) => {
      console.log('====>地图时间变化', event.detail);
      
      // 获取最新的地图数据类型
      const currentDataCode = dataCodeRef.current;
      
      // 只有当变更的面板是当前激活面板时才更新地图
      if (event.detail?.panel === mapState.activePanel && areaMapInstance) {
        try {
          // 更新地图参数
          if (event.detail.panel === 'left') {
            areaMapInstance.params.startTime = event.detail.startTime;
            areaMapInstance.params.endTime = event.detail.endTime;
          } else {
            areaMapInstance.params.startTime = event.detail.startTime;
            areaMapInstance.params.endTime = event.detail.endTime;
          }
          
          console.log('更新地图时间参数:', {
            panel: event.detail.panel,
            activePanel: mapState.activePanel,
            dataCode: currentDataCode,
            startTime: areaMapInstance.params.startTime,
            endTime: areaMapInstance.params.endTime
          });
          
          // 根据区域代码长度决定调用不同的方法
          const isCommunityLevel = mapState.regionCode.length === 9;
          if (isCommunityLevel) {
            areaMapInstance.setPoints(true);
          } else {
            areaMapInstance.addArea(true);
          }
        } catch (error) {
          console.error('时间更新失败:', error);
        }
      } else {
        console.log('时间变化但不更新地图:', {
          changedPanel: event.detail?.panel,
          activePanel: mapState.activePanel,
          dataCode: currentDataCode
        });
      }
    };
    
    // 添加事件监听
    window.addEventListener('mapDateChange', handleMapDateChange as EventListener);
    
    // 组件卸载时移除事件监听
    return () => {
      window.removeEventListener('mapDateChange', handleMapDateChange as EventListener);
    };
  }, [areaMapInstance, mapState.regionCode, mapState.activePanel]);

  // 添加事件面板时间变化处理
  useEffect(() => {
    const handleEventPanelTimeChange = (event: CustomEvent) => {
      // 只处理右侧面板时间变化，且当前数据类型为油烟事件时
      if (event.detail?.panel === 'right' && isOilSmokeEventDataType(currentDataType)) {
        console.log('====>事件面板时间变化，重新加载事件列表', event.detail);
        // 使用延迟确保状态已更新
        setTimeout(() => {
          fetchEvents();
        }, 100);
      }
    };
    
    // 添加时间变化事件监听
    window.addEventListener('mapDateChange', handleEventPanelTimeChange as EventListener);
    
    return () => {
      window.removeEventListener('mapDateChange', handleEventPanelTimeChange as EventListener);
    };
  }, [fetchEvents, currentDataType]);

  useEffect(() => {
    if (!eventHtmlRef.current || !playingStatus) return;

    const viewBoxH = eventHtmlRef.current.clientHeight;
    const scrollHandler = () => {
      if (!eventHtmlRef.current) return;

      if (eventHtmlRef.current.scrollHeight - viewBoxH <= eventHtmlRef.current.scrollTop) {
        eventHtmlRef.current.scrollTo({ top: 0, behavior: 'instant' });
        return;
      }

      eventHtmlRef.current.scrollTop += 1; // Smoother scrolling with less overhead
    };

    const intervalId = setInterval(scrollHandler, 50);
    return () => clearInterval(intervalId);
  }, [playingStatus]);

  const { data: signData } = useRequest(() =>
    services.districtController.getListIndexInstance({
      physicalSignType: '1',
      indexType: '1',
      indexId: '',
      objectId: areaId,
      indexHierarchy: '1',
      objectHierarchy: '1',
    }),
  );

  /** 标题渲染 */
  const titleRender = () => {
    return (
      <Flex align="center" className={styles.modalTitle}>
        <div className={styles.title}>{detailModalOpt?.riskdescription}</div>
        <img
          src={colorConfig[detailModalOpt?.riskLevelName!]?.tag}
          alt=""
          style={{ width: 136, height: 30, marginLeft: 36, marginRight: 13 }}
        />

        <span className={styles.type}>
          {detailModalOpt?.industry_name_dl}-{detailModalOpt?.name}
        </span>
      </Flex>
    );
  };

  // Modify the memoizedPolygons function to apply dynamic sampling
  const memoizedPolygons = useMemo(() => {
    if (!data) return null;

    let totalPoints = 0;

    // Determine sampling rate based on current zoom level
    let samplingRate = getSamplingRate(currentZoom);

    console.log(`Rendering polygons with sampling rate 1/${samplingRate} at zoom level ${currentZoom}`);

    return data.map((item, index) => {
      // Sample the points based on samplingRate
      const sampledPoints = item.multiPoints?.map((pointsArray: any[]) => {
        totalPoints += pointsArray.length;
        return pointsArray.filter((_, idx) => idx % samplingRate === 0);
      });

      // Return the sampled polygons
      return sampledPoints?.map((points: any, idx: number) => (
        <CooglMap.Polygon
          fillColor={getColorByIndex(Number(item.qualitySign))!}
          key={`${item.objectId}_${idx}`}
          strokeColor="#fff"
          points={points}
          strokeWidth={2}
          fillOpacity={0.2}
        />
      ));
    });
  }, [data, currentZoom]);

  // Force garbage collection opportunity when component unmounts or map changes
  useEffect(() => {
    return () => {
      setData([]); // Clear large data structures
      setEventData([]);
      setSelected(undefined);
      // Other cleanup
    };
  }, []);

  // 清理函数
  useEffect(() => {
    return () => {
      if (areaMapInstance) {
        areaMapInstance.destory();
      }
    };
  }, [areaMapInstance]);

  const tagUseWhitchClass = (dealOverdue: string) => {
    return {
      '0': styles.normalTag, // 限时正常
      '1': styles.redTag, // 临近超期
      '2': styles.redTag, // 轻微超期
      '3': styles.redTag, // 严重超期
    }[dealOverdue]
  }

  // 监听激活面板变化
  useEffect(() => {
    const handleActivePanelChange = () => {
      if (!areaMapInstance) return;
      
      try {
        // 根据激活面板设置时间范围
        if (mapState.activePanel === 'left') {
          areaMapInstance.params.startTime = mapState.leftPanelTime.startTime;
          areaMapInstance.params.endTime = mapState.leftPanelTime.endTime;
        } else {
          areaMapInstance.params.startTime = mapState.rightPanelTime.startTime;
          areaMapInstance.params.endTime = mapState.rightPanelTime.endTime;
        }
        
        console.log('面板切换，更新地图时间参数:', {
          activePanel: mapState.activePanel,
          startTime: areaMapInstance.params.startTime,
          endTime: areaMapInstance.params.endTime
        });
        
        // 更新地图
        const isCommunityLevel = mapState.regionCode.length === 9;
        if (isCommunityLevel) {
          areaMapInstance.setPoints(true);
        } else {
          areaMapInstance.addArea(true);
        }
      } catch (error) {
        console.error('更新激活面板时间失败:', error);
      }
    };
    
    // 当激活面板变化时，更新地图时间参数
    handleActivePanelChange();
    
  }, [areaMapInstance, mapState.activePanel, mapState.leftPanelTime, mapState.rightPanelTime]);

  return (
    <div className={styles.container}>
      <CooglMap.MapView
        // <CooglMap.MapViewCustomized
        zoom={8}
        ref={MapRef}
        center={{ x: 103.96, y: 30.658842 }}
        // showOriginMap={false}
        customInitCallback={(viewer: any) => loadCooglMapAreaData(viewer)}
        changeSize={{ x1: 908, y1: 430, x2: 908, y2: 572 }}
        mode={'2D'}
      >
        {leftTabKey === '1' ? (
          <>
            {/**区域 */}
            {/* {memoizedPolygons} */}
            {isHomePage && data?.map((item, index) => {
              const point = [Number(item.centerX), Number(item.centerY)];

              return (
                <CooglMap.CustomOverlay
                  key={index}
                  position={point}
                  onSet={() => {
                    const obj = signData?.find(
                      (signItem: any) => item.objectId === signItem?.objectId,
                    );
                    setSelected({
                      ...item,
                      eventCount: obj?.eventCount,
                      diffValue: obj?.diffValue,
                      desc: obj?.desc,
                    });
                  }}
                >
                  <div
                    data-event-key="set"
                    className={styles.indexMarker}
                    style={
                      BMapService.getMakerCSS(
                        Number(item.qualitySign),
                      ) as CSSProperties
                    }
                  >
                    {Number(item.qualitySign)}
                  </div>
                </CooglMap.CustomOverlay>
              );
            })}
            {selected && (
              <CooglMap.CustomOverlay
                position={[Number(selected.centerX), Number(selected.centerY)]}
                offset={{
                  top: -50,
                }}
                onClose={(e: any) => {
                  setSelected(undefined);
                }}
                onDetail={(e: any) => {
                  dispatch.push('districtIndex', {
                    title: selected?.objectName + '运行情况',
                    props: {
                      data: selected,
                      indexs: indexs,
                    },
                  });
                }}
              >
                <div className={styles.window1}>
                  <PopoverCard data={selected}></PopoverCard>
                </div>
              </CooglMap.CustomOverlay>
            )}
          </>
        ) : (
          <RiskIssue
            checkedKeys={checkedKeys}
            // setModalOpt={setModalOpt}
            setDetailModalOpt={setDetailModalOpt}
          />
        )}
      </CooglMap.MapView>
      {/* </CooglMap.MapViewCustomized> */}

      {/* 状态栏 - 添加区域选择器并传递地图实例 */}
      {/* <div className={styles.statusBar}>
        <LeftTab
          leftTabKey={leftTabKey}
          checkedKeys={checkedKeys}
          setLeftTabKey={setLeftTabKey}
          setCheckedKeys={setCheckedKeys}
        />
        <AreaSelector mapInstance={areaMapInstance} />
        <Apps></Apps>
      </div> */}
      {!isHomePage && isOilSmokeEventDataType(currentDataType) && eventData.length > 0 && <div className={styles.leftWarp}>
        <div className={styles.menuBg}></div>

        <div className={styles.eventWarp}>
          <div className={styles.title}>{isHomePage ? '最新事件' : '餐饮油烟事件'}</div>
          <div
            className={styles.listWarp}
            ref={eventHtmlRef}
            // onMouseMove={() => {
            //   setPlayingStatus(false);
            // }}
            // onMouseLeave={() => {
            //   setPlayingStatus(true);
            // }}
          >
            {eventData?.map((item, index) => {
              return (
                <div
                  key={'event_' + item?.eventId}
                  className={styles.items}
                  onClick={() => {
                    dispatch.push('EventDetail', {
                      title: isHomePage ? '事件详情' : '餐饮油烟事件详情',
                      w: 'fit-content',
                      props: {
                        eventId: item?.eventId,
                      },
                    });
                  }}
                >

                  <div className={styles.title}>{item?.standardEventTitle}</div>
                  <div className={styles.tags}>
                    {item?.districtName && <div className={classNames(styles.tag, styles.blueTag)}>{item?.districtName}</div>}
                    {
                      item?.dealOverdueText
                      &&
                      <div className={classNames(styles.tag, tagUseWhitchClass(item?.dealOverdue))}>
                        {item?.dealOverdueText}
                      </div>
                    }
                    {item?.caseStatusText && <div className={classNames(styles.tag, styles.greenTag)}>{item?.caseStatusText}</div>}
                  </div>
                  <Image
                    src={joinPictureHttp(item?.disposePicPath)}
                    alt=""
                    // {...imageOptions}
                    preview={false}
                    className={styles.img}
                  />
                  <Flex vertical gap={3}>
                    {/* <div className={`${styles.org}`}>责任单位：{item?.informantUnitName}</div> */}
                    <div className={styles.time}>
                      上报时间：{dayjs(item?.reportTime).format('YYYY-MM-DD')}
                    </div>
                    <div className={styles.address}>
                      <div style={{ flexShrink: 0 }}>案件地址：</div>
                      <div>{item?.address}</div>
                    </div>
                  </Flex>
                  <div className={styles.mainTypeName}>{item?.mainTypeName}</div>
                  {/* <div className={styles.time}>{item?.reportTime}分钟前</div> */}
                </div>
              );
            })}
          </div>
          {/* <div className={styles.otherWarp}>
            <div className={styles.other}>更多</div>
          </div> */}
        </div>
      </div>
      }
      {/* 风险事件详情 */}
      <Modal
        open={detailModalOpt?.open}
        titleRender={titleRender}
        onCancel={() => {
          setDetailModalOpt({
            open: false,
            title: '事件详情',
            eventId: '',
          });
        }}
        width={2650}
        height={900}
      >
        {detailModalOpt?.open && (
          <BaseInfo
            eventId={detailModalOpt?.eventId}
            detail={detailModalOpt}
            onChangeOpt={(val) => {
              setDetailModalOpt({
                ...detailModalOpt,
                position: val?.region_name,
                riskLevelName: val?.risklevel,
              });
            }}
          />
        )}
      </Modal>
    </div>
  );
};

export default DistrictMapCustomized;
