import React, { createContext, useContext, useEffect, useState, useCallback, useRef } from 'react';
import { useDashboard } from './context';
import { 
  DATA_TYPE, 
  GRID_TYPE, 
  DATA_TO_GRID_TYPE_MAP, 
  PANEL_ACTIVATION, 
  PAGE_DEFAULT_DATA_TYPES, 
  REGION_CODES 
} from '@/constants/dataTypes';
import { useLatestValue, useLatestValues } from '@/pages/Home_v_2504/hooks/useLatestValue';
import dayjs from 'dayjs';

// 简单的防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return (...args: any[]) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = window.setTimeout(() => {
      fn(...args);
      timer = null;
    }, delay);
  };
};

// 定义地图状态类型
interface MapState {
  // 地图实例
  mapInstance: any;
  // 行政区域代码
  regionCode: string;
  // 数据类型代码
  dataCode: string;
  // 网格类型
  gridType: string;
  // 左侧面板时间范围（餐饮油烟实况）
  leftPanelTime: {
    startTime: string;
    endTime: string;
    type: string;
  };
  // 右侧面板时间范围（餐饮油烟事件）
  rightPanelTime: {
    startTime: string;
    endTime: string;
    type: string;
  };
  // 当前激活的面板
  activePanel: 'left' | 'right';
  // 最近变化的面板
  changedPanel: 'left' | 'right';
  // 页面级别的时间设置，用于隔离不同页面的时间状态
  pageTimeSettings: Record<string, {
    leftPanelTime: {
      startTime: string;
      endTime: string;
      type: string;
    };
    rightPanelTime: {
      startTime: string;
      endTime: string;
      type: string;
    };
  }>;
}

// 定义上下文类型
interface MapStateContextType {
  mapState: MapState;
  // 设置地图实例
  setMapInstance: (instance: any) => void;
  // 更新行政区域
  updateRegion: (regionCode: string) => void;
  // 更新数据类型
  updateDataType: (dataCode: string, withoutMapUpdate?: boolean) => void;
  // 更新时间范围
  updateTimeRange: (panel: 'left' | 'right', type: string, startTime: string, endTime: string, instanceId?: string, pageId?: string) => void;
  // 更新网格类型
  updateGridType: (gridType: string) => void;
  // 重置为页面默认值
  resetToPageDefaults: (pageId: string, preserveInstance?: boolean) => void;
  // 更新地图显示
  updateMapDisplay: () => void;
  // 设置激活面板
  setActivePanel: (panel: 'left' | 'right') => void;
}

// 默认值
const defaultMapState: MapState = {
  mapInstance: null,
  regionCode: REGION_CODES.CHENGDU, // 默认成都市
  dataCode: DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT,  // 默认油烟事件
  gridType: GRID_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT,  // 默认油烟事件网格类型
  leftPanelTime: {
    startTime: '',
    endTime: '',
    type: 'day' // 左侧默认为日视图
  },
  rightPanelTime: {
    startTime: '',
    endTime: '',
    type: 'month' // 右侧默认为月视图
  },
  activePanel: 'right', // 默认激活右侧面板
  changedPanel: 'right',
  pageTimeSettings: {}
};

// 创建上下文
const MapStateContext = createContext<MapStateContextType | undefined>(undefined);

// 用于持久化存储地图实例，确保页面切换时不丢失
let persistentMapInstance: any = null;

// Provider 组件
export const MapStateProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [mapState, setMapState] = useState<MapState>(defaultMapState);
  const { activePage } = useDashboard();
  
  // 使用自定义Hook保持最新引用
  const mapStateRef = useLatestValues(mapState);
  const prevActivePageRef = useRef<string>('home');
  const lastDateChangeRef = useRef<string>(''); // 用于跟踪最后一次日期变更
  const isUpdatingRef = useRef<boolean>(false); // 用于防止重复更新

  // 确保地图实例在页面切换时被持久化保存
  useEffect(() => {
    // 如果有持久化存储的实例但状态中没有，则恢复它
    if (persistentMapInstance && !mapState.mapInstance) {
      console.log('从持久化存储恢复地图实例');
      setMapState(prev => ({
        ...prev,
        mapInstance: persistentMapInstance
      }));
    }
  }, [mapState.mapInstance]);

  // 在页面切换时保存当前页面和处理状态变更
  useEffect(() => {
    if (activePage !== prevActivePageRef.current) {
      console.log(`页面从 ${prevActivePageRef.current} 切换到 ${activePage}`);
      
      // 保存上一个页面
      prevActivePageRef.current = activePage;
      
      // 重置为新页面的默认值，但保留地图实例
      if (activePage) {
        console.log(`设置 ${activePage} 页面的默认参数`);
        resetToPageDefaults(activePage, true);
      }
    }
  }, [activePage]);

  // 初始化默认时间范围
  useEffect(() => {
    const now = new Date();
    const today = now.toISOString().split('T')[0];
    // 正确的获取本月第一天和最后一天
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth() , 2).toISOString().split('T')[0];
    const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1).toISOString().split('T')[0];
    
    // 初始化左右面板的时间设置
    const leftPanelTime = {
      type: 'day',
      startTime: `${today} 00:00:00`,
      endTime: `${today} 23:59:59`
    };
    
    const rightPanelTime = {
      type: 'month',
      startTime: `${firstDayOfMonth} 00:00:00`,
      endTime: `${lastDayOfMonth} 23:59:59`
    };
    
    // 初始化页面级别的时间设置 - 每个页面都有自己的默认值
    const pageTimeSettings = {
      home: { // 首页
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      restaurantOil: { // 餐饮油烟
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      environment: { // 环境卫生
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      municipal: { // 市政设施
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      landscapeLighting: { // 景观照明
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      lawEnforcementPunishment: { // 行政处罚
        leftPanelTime: { ...leftPanelTime, type: 'lastMonth' },
        rightPanelTime: { ...rightPanelTime, type: 'lastMonth' }
      },
      lawEnforcementCoordination: { // 市区协同
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime, type: 'lastMonth' }
      },
      lawEnforcementPatrol: { // 日常巡查
        leftPanelTime: { ...leftPanelTime, type: 'yesterday' },
        rightPanelTime: { ...rightPanelTime, type: 'yesterday' }
      },
      domesticWaste: { // 生活垃圾
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      },
      constructionWaste: { // 建筑垃圾
        leftPanelTime: { ...leftPanelTime, type: 'month'  },
        rightPanelTime: { ...rightPanelTime }
      },
      cityAppearance: { // 市容秩序
        leftPanelTime: { ...leftPanelTime },
        rightPanelTime: { ...rightPanelTime }
      }
    };
    
    // 针对不同页面设置不同的日期
    // 上个月的日期
    const lastMonth = dayjs().subtract(1, 'month');
    const lastMonthStart = lastMonth.startOf('month').format('YYYY-MM-DD');
    const lastMonthEnd = lastMonth.endOf('month').format('YYYY-MM-DD');
    
    // 昨天的日期
    const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
    
    // 更新行政处罚页面的日期 - lastMonth
    pageTimeSettings.lawEnforcementPunishment.leftPanelTime.startTime = `${lastMonthStart} 00:00:00`;
    pageTimeSettings.lawEnforcementPunishment.leftPanelTime.endTime = `${lastMonthEnd} 23:59:59`;
    pageTimeSettings.lawEnforcementPunishment.rightPanelTime.startTime = `${lastMonthStart} 00:00:00`;
    pageTimeSettings.lawEnforcementPunishment.rightPanelTime.endTime = `${lastMonthEnd} 23:59:59`;
    
    // 更新市区协同页面的日期 - lastMonth
    pageTimeSettings.lawEnforcementCoordination.rightPanelTime.startTime = `${lastMonthStart} 00:00:00`;
    pageTimeSettings.lawEnforcementCoordination.rightPanelTime.endTime = `${lastMonthEnd} 23:59:59`;
    
    // 更新日常巡查页面的日期 - yesterday
    pageTimeSettings.lawEnforcementPatrol.leftPanelTime.startTime = `${yesterday} 00:00:00`;
    pageTimeSettings.lawEnforcementPatrol.leftPanelTime.endTime = `${yesterday} 23:59:59`;
    pageTimeSettings.lawEnforcementPatrol.rightPanelTime.startTime = `${yesterday} 00:00:00`;
    pageTimeSettings.lawEnforcementPatrol.rightPanelTime.endTime = `${yesterday} 23:59:59`;
    
    setMapState(prev => ({
      ...prev,
      leftPanelTime,
      rightPanelTime,
      // 初始化页面级别的时间设置
      pageTimeSettings
    }));
  }, []);

  // 更新时间范围 - 使用防抖确保不会短时间内多次触发
  const debouncedUpdateTimeRange = useCallback(
    debounce((panel: 'left' | 'right', type: string, startTime: string, endTime: string, instanceId?: string, pageId?: string) => {
      // 获取最新状态以避免闭包问题
      const currentMapState = mapStateRef.current;
      
      // 确定当前页面ID，默认为'home'
      const currentPageId = pageId || 'home';
      
      // 检查时间是否实际发生了变化，避免重复更新
      const isChanged = panel === 'left' 
        ? (currentMapState.leftPanelTime.type !== type || 
           currentMapState.leftPanelTime.startTime !== formatDateTime(startTime) || 
           currentMapState.leftPanelTime.endTime !== formatDateTime(endTime, true))
        : (currentMapState.rightPanelTime.type !== type || 
           currentMapState.rightPanelTime.startTime !== formatDateTime(startTime) || 
           currentMapState.rightPanelTime.endTime !== formatDateTime(endTime, true));
      
      if (!isChanged) {
        console.log('时间范围未变化，跳过更新:', {
          panel,
          type,
          startTime,
          endTime,
          pageId: currentPageId
        });
        return;
      }
      
      // 生成当前更新的唯一标识
      const updateId = JSON.stringify({panel, type, startTime, endTime, pageId: currentPageId});
      
      // 检查是否与上次更新相同
      if (updateId === lastDateChangeRef.current) {
        console.log('重复的时间范围更新，跳过');
        return;
      }
      
      // 记录本次更新标识
      lastDateChangeRef.current = updateId;
      
      // 防止重复更新
      if (isUpdatingRef.current) {
        console.log('已有更新正在进行中，跳过');
        return;
      }
      
      isUpdatingRef.current = true;
      
      console.log('更新时间范围:', {
        panel,
        type,
        startTime,
        endTime,
        pageId: currentPageId,
        activePanel: currentMapState.activePanel,
        dataCode: currentMapState.dataCode,
        currentType: panel === 'left' ? currentMapState.leftPanelTime.type : currentMapState.rightPanelTime.type
      });
      
      // 创建格式化后的时间对象
      const formattedTimeObj = {
        type,
        startTime: formatDateTime(startTime),
        endTime: formatDateTime(endTime, true)
      };
      
      // 使用函数式更新，确保拿到最新的state
      setMapState(prev => {
        // 检查页面级别的时间设置是否已经存在这个配置
        const existingPageSettings = prev.pageTimeSettings?.[currentPageId];
        const existingPanelTime = panel === 'left' 
          ? existingPageSettings?.leftPanelTime 
          : existingPageSettings?.rightPanelTime;
        
        // 如果已有完全相同的设置，不进行更新以减少不必要的渲染
        if (existingPanelTime && 
            existingPanelTime.type === type && 
            existingPanelTime.startTime === formattedTimeObj.startTime && 
            existingPanelTime.endTime === formattedTimeObj.endTime) {
          console.log('页面时间设置无变化，跳过状态更新');
          // 即使不更新状态，也需要重置isUpdatingRef
          setTimeout(() => {
            isUpdatingRef.current = false;
          }, 0);
          return prev; // 不更新状态
        }
        
        // 否则创建新的状态对象
        const newState = { ...prev };
        
        // 更新主时间范围（保持向后兼容）
        if (panel === 'left') {
          newState.leftPanelTime = formattedTimeObj;
        } else {
          newState.rightPanelTime = formattedTimeObj;
        }
        
        // 更新页面级别的时间设置
        const pageTimeSettings = {
          ...(prev.pageTimeSettings || {}),
          [currentPageId]: {
            ...(prev.pageTimeSettings?.[currentPageId] || {
              leftPanelTime: { ...prev.leftPanelTime },
              rightPanelTime: { ...prev.rightPanelTime }
            }),
            [panel === 'left' ? 'leftPanelTime' : 'rightPanelTime']: formattedTimeObj
          }
        };
        
        newState.pageTimeSettings = pageTimeSettings;
        newState.changedPanel = panel;
        return newState;
      });
      
      // 发布日期变更事件，用于其他组件感知
      const mapDateChangeEvent = new CustomEvent('mapDateChange', {
        detail: {
          panel,
          type,
          startTime: formatDateTime(startTime),
          endTime: formatDateTime(endTime, true),
          instanceId: instanceId || null, // 包含实例ID以便识别事件来源
          activePanel: currentMapState.activePanel, // 包含当前激活面板信息
          dataCode: currentMapState.dataCode, // 包含当前数据类型信息
          pageId: currentPageId // 包含页面ID以便识别事件来源
        }
      });
      console.log('MapStateContext mapDateChangeEvent', mapDateChangeEvent.detail);
      window.dispatchEvent(mapDateChangeEvent);
      
      // 检查面板和数据类型的兼容性
      const shouldUpdateMap = () => {
        // 获取当前数据类型
        const currentDataCode = currentMapState.dataCode;
        
        // 判断数据类型与面板的兼容性
        if (panel === 'left') {
          // 左侧面板兼容的数据类型
          return PANEL_ACTIVATION.ACTIVATE_LEFT.includes(currentDataCode);
        } else {
          // 右侧面板兼容的数据类型
          return PANEL_ACTIVATION.ACTIVATE_RIGHT.includes(currentDataCode);
        }
      };
      
      // 只有当面板与当前数据类型兼容时才更新地图
      if (panel === currentMapState.activePanel && shouldUpdateMap()) {
        console.log('面板变更与数据类型兼容，更新地图:', {
          panel,
          dataCode: currentMapState.dataCode
        });
        
        setTimeout(() => {
          updateMapDisplay();
          isUpdatingRef.current = false;
        }, 50);
      } else {
        console.log('时间变化但不触发地图更新:', {
          reason: panel !== currentMapState.activePanel ? '非活动面板' : '面板与数据类型不兼容',
          changedPanel: panel,
          activePanel: currentMapState.activePanel,
          dataCode: currentMapState.dataCode
        });
        isUpdatingRef.current = false;
      }
    }, 300),
    []
  );

  // 设置地图实例
  const setMapInstance = useCallback((instance: any) => {
    console.log('设置地图实例:', instance);
    
    // 保存到持久化存储
    if (instance && instance.params) {
      persistentMapInstance = instance;
    }
    
    // 先更新状态
    setMapState(prev => ({ ...prev, mapInstance: instance }));
    
    // 如果实例存在，确保使用最新的实例直接更新而不依赖状态
    if (instance && instance.params) {
      console.log('地图实例有效，准备更新参数');
      
      // 使用最新的mapState直接更新，不依赖状态中的mapInstance
      setTimeout(() => {
        // 获取当前状态的副本进行更新
        const currentState = mapStateRef.current;
        
        // 更新地图参数
        instance.params.regionCode = currentState.regionCode;
        instance.params.dataCode = currentState.dataCode;
        instance.params.gridType = currentState.gridType;
        
        // 根据激活面板选择时间参数
        if (currentState.activePanel === 'left') {
          instance.params.startTime = currentState.leftPanelTime.startTime;
          instance.params.endTime = currentState.leftPanelTime.endTime;
        } else {
          instance.params.startTime = currentState.rightPanelTime.startTime;
          instance.params.endTime = currentState.rightPanelTime.endTime;
        }
        
        console.log('初始化地图参数:', {
          regionCode: instance.params.regionCode,
          dataCode: instance.params.dataCode,
          gridType: instance.params.gridType,
          startTime: instance.params.startTime,
          endTime: instance.params.endTime
        });
        
        // 根据区域代码长度决定调用不同的方法
        const isCommunityLevel = currentState.regionCode.length === 9;
        try {
          if (isCommunityLevel) {
            instance.setPoints(true);
          } else {
            instance.addArea(true);
          }
          console.log('地图初始化更新成功');
        } catch (error) {
          console.error('地图初始化更新失败:', error);
        }
      }, 300); // 给予足够的时间确保一切准备就绪
    } else {
      console.warn('地图实例无效或未初始化params');
    }
  }, []);

  // 更新行政区域
  const updateRegion = useCallback((regionCode: string) => {
    console.log(`MapStateContext收到区域更新请求: ${regionCode}`);
    
    // 检查区域代码有效性
    if (!regionCode) {
      console.error('区域代码无效: 为空');
      return;
    }
    
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    if (regionCode === currentMapState.regionCode) {
      console.warn(`区域代码未变化: ${regionCode} vs ${currentMapState.regionCode}`);
      return;
    }
    
    console.log(`执行区域切换: ${currentMapState.regionCode} -> ${regionCode}`);
    
    // 先更新状态
    setMapState(prev => {
      console.log(`更新区域状态: ${prev.regionCode} -> ${regionCode}`);
      return { ...prev, regionCode };
    });
    
    // 使用持久化实例立即更新地图，不依赖异步状态更新
    if (persistentMapInstance && persistentMapInstance.params) {
      console.log(`使用持久化实例直接更新区域: ${regionCode}`);
      
      // 延迟执行确保状态已更新
      setTimeout(() => {
        try {
          // 在更新前记录当前区域代码
          const oldRegionCode = persistentMapInstance.params.regionCode;
          
          // 更新区域参数
          persistentMapInstance.params.regionCode = regionCode;
          
          // 根据区域代码长度决定调用不同的方法
          const isCommunityLevel = regionCode.length === 9;
          
          console.log(`更新地图区域: ${oldRegionCode} -> ${regionCode}, isCommunityLevel=${isCommunityLevel}`);
          
          if (isCommunityLevel) {
            console.log(`调用setPoints方法: ${regionCode}`);
            persistentMapInstance.setPoints(true);
          } else {
            console.log(`调用addArea方法: ${regionCode}, 清除数据=true`);
            persistentMapInstance.addArea(true);
          }
          
          // 发布自定义事件，通知区域变更
          const regionChangeEvent = new CustomEvent('mapRegionChange', {
            detail: { regionCode, oldRegionCode }
          });
          window.dispatchEvent(regionChangeEvent);
          
          console.log(`区域更新成功: ${regionCode}`);
        } catch (error) {
          console.error(`区域更新失败: ${regionCode}`, error);
        }
      }, 100); // 减少延迟时间以提高响应速度
    } else {
      console.error('无法更新地图区域: 地图实例或实例参数不存在');
      
      // 记录详细信息以辅助调试
      console.log('地图实例状态:', {
        hasPersistentInstance: !!persistentMapInstance,
        hasStateInstance: !!currentMapState.mapInstance,
        currentRegionCode: currentMapState.regionCode,
        targetRegionCode: regionCode
      });
      
      // 发布自定义事件，通知区域变更
      const regionChangeEvent = new CustomEvent('mapRegionChange', {
        detail: { regionCode, oldRegionCode: currentMapState.regionCode }
      });
      window.dispatchEvent(regionChangeEvent);
    }
  }, []);

  // 设置激活面板
  const setActivePanel = useCallback((panel: 'left' | 'right') => {
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    // 如果面板未变化，不执行更新
    if (panel === currentMapState.activePanel) {
      return;
    }
    
    console.log(`设置激活面板: ${currentMapState.activePanel} -> ${panel}`);
    
    // 更新状态
    setMapState(prev => ({
      ...prev,
      activePanel: panel
    }));
    
    // 同时更新地图时间参数
    if (persistentMapInstance && persistentMapInstance.params) {
      try {
        if (panel === 'left') {
          persistentMapInstance.params.startTime = currentMapState.leftPanelTime.startTime;
          persistentMapInstance.params.endTime = currentMapState.leftPanelTime.endTime;
        } else {
          persistentMapInstance.params.startTime = currentMapState.rightPanelTime.startTime;
          persistentMapInstance.params.endTime = currentMapState.rightPanelTime.endTime;
        }
        
        // 更新地图显示
        setTimeout(() => {
          updateMapDisplay();
        }, 50);
      } catch (error) {
        console.error('更新面板时间参数失败:', error);
      }
    }
  }, []);

  // 更新数据类型 - 修改后的版本，基于常量定义判断激活面板
  const updateDataType = useCallback((dataCode: string, withoutMapUpdate = false) => {
    console.log('更新数据类型:', dataCode);
    
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    // 根据数据类型设置激活面板
    let activePanel = currentMapState.activePanel;
    
    // 使用常量定义判断哪个面板应该被激活
    if (PANEL_ACTIVATION.ACTIVATE_LEFT.includes(dataCode)) {
      activePanel = 'left';
    } else if (PANEL_ACTIVATION.ACTIVATE_RIGHT.includes(dataCode)) {
      activePanel = 'right';
    }
    // PRESERVE_ACTIVE类型不改变当前激活面板
    
    // 根据数据类型从映射表获取对应的gridType
    const gridType = DATA_TO_GRID_TYPE_MAP[dataCode] || currentMapState.gridType;
    
    // 更新状态
    setMapState(prev => ({ 
      ...prev, 
      dataCode,
      gridType,
      activePanel,
      changedPanel: activePanel
    }));

    // 发布数据类型变更事件，用于其他组件感知
    const dataTypeChangeEvent = new CustomEvent('mapDataTypeChange', {
      detail: { dataCode, gridType, activePanel }
    });
    window.dispatchEvent(dataTypeChangeEvent);
    
    // 立即使用实例更新地图，避免等待状态更新
    if (!withoutMapUpdate && persistentMapInstance && persistentMapInstance.params) {
      persistentMapInstance.params.dataCode = dataCode;
      persistentMapInstance.params.gridType = gridType;
      
      // 根据激活面板设置时间范围
      if (activePanel === 'left') {
        persistentMapInstance.params.startTime = currentMapState.leftPanelTime.startTime;
        persistentMapInstance.params.endTime = currentMapState.leftPanelTime.endTime;
      } else {
        persistentMapInstance.params.startTime = currentMapState.rightPanelTime.startTime;
        persistentMapInstance.params.endTime = currentMapState.rightPanelTime.endTime;
      }
      
      console.log('更新地图数据类型和时间:', {
        dataCode,
        gridType,
        activePanel,
        startTime: persistentMapInstance.params.startTime,
        endTime: persistentMapInstance.params.endTime
      });
      
      // 更新地图
      setTimeout(() => {
        try {
          const isCommunityLevel = currentMapState.regionCode.length === 9;
          if (isCommunityLevel) {
            persistentMapInstance.setPoints(true);
          } else {
            persistentMapInstance.addArea(true);
          }
          console.log('数据类型更新成功');
        } catch (error) {
          console.error('数据类型更新失败:', error);
        }
      }, 50);
    }
  }, []);

  // 更新时间范围
  const updateTimeRange = useCallback((panel: 'left' | 'right', type: string, startTime: string, endTime: string, instanceId?: string, pageId?: string) => {
    debouncedUpdateTimeRange(panel, type, startTime, endTime, instanceId, pageId);
  }, [debouncedUpdateTimeRange]);

  // 更新网格类型
  const updateGridType = useCallback((gridType: string) => {
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    setMapState(prev => ({ ...prev, gridType }));
    
    // 立即使用实例更新地图，避免等待状态更新
    if (persistentMapInstance && persistentMapInstance.params) {
      persistentMapInstance.params.gridType = gridType;
      
      setTimeout(() => {
        try {
          const isCommunityLevel = currentMapState.regionCode.length === 9;
          if (isCommunityLevel) {
            persistentMapInstance.setPoints(true);
          } else {
            persistentMapInstance.addArea(true);
          }
          console.log('网格类型更新成功');
        } catch (error) {
          console.error('网格类型更新失败:', error);
        }
      }, 50);
    }
  }, []);

  // 重置为页面默认值
  const resetToPageDefaults = useCallback((pageId: string, preserveInstance: boolean = false) => {
    // 获取页面默认数据类型
    const dataCode = PAGE_DEFAULT_DATA_TYPES[pageId] || DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
    
    // 根据数据类型确定激活面板
    let activePanel: 'left' | 'right' = 'right';
    
    if (PANEL_ACTIVATION.ACTIVATE_LEFT.includes(dataCode)) {
      activePanel = 'left';
    } else if (PANEL_ACTIVATION.ACTIVATE_RIGHT.includes(dataCode)) {
      activePanel = 'right';
    }
    
    // 根据数据类型从映射表获取对应的gridType
    const gridType = DATA_TO_GRID_TYPE_MAP[dataCode] || GRID_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
    
    setMapState(prev => {
      // 创建新的状态对象
      const newState = {
        ...prev,
        dataCode,
        regionCode: REGION_CODES.CHENGDU, // 重置为成都市
        gridType,
        activePanel
      };
      
      // 如果需要保留地图实例
      if (preserveInstance) {
        // 使用持久化存储的实例或当前实例
        newState.mapInstance = persistentMapInstance || prev.mapInstance;
      } else {
        newState.mapInstance = null;
      }
      
      return newState;
    });
    
    // 发布数据类型变更事件
    const dataTypeChangeEvent = new CustomEvent('mapDataTypeChange', {
      detail: { dataCode, activePanel }
    });
    window.dispatchEvent(dataTypeChangeEvent);
    
    // 如果有持久化的地图实例，页面切换后更新地图
    if (preserveInstance && persistentMapInstance) {
      console.log('页面切换后使用持久化实例更新地图');
      setTimeout(() => {
        updateMapDisplayWithInstance(persistentMapInstance);
      }, 500);
    }
  }, []);

  // 使用指定实例更新地图显示
  const updateMapDisplayWithInstance = useCallback((instance: any) => {
    if (!instance || !instance.params) {
      console.warn('更新地图显示失败: 无效实例');
      return;
    }
    
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    try {
      // 更新地图参数
      instance.params.regionCode = currentMapState.regionCode;
      instance.params.dataCode = currentMapState.dataCode;
      instance.params.gridType = currentMapState.gridType;
      
      // 根据激活面板选择时间参数
      if (currentMapState.activePanel === 'left') {
        instance.params.startTime = currentMapState.leftPanelTime.startTime;
        instance.params.endTime = currentMapState.leftPanelTime.endTime;
      } else {
        instance.params.startTime = currentMapState.rightPanelTime.startTime;
        instance.params.endTime = currentMapState.rightPanelTime.endTime;
      }
      
      console.log('更新地图参数(使用指定实例):', {
        regionCode: currentMapState.regionCode,
        dataCode: currentMapState.dataCode,
        gridType: currentMapState.gridType,
        startTime: instance.params.startTime,
        endTime: instance.params.endTime
      });
      
      // 根据区域代码长度决定调用不同的方法
      const isCommunityLevel = currentMapState.regionCode.length === 9;
      if (isCommunityLevel) {
        instance.setPoints(true);
      } else {
        instance.addArea(true);
      }
      console.log('地图更新成功(使用指定实例)');
    } catch (error) {
      console.error('更新地图显示出错(使用指定实例):', error);
    }
  }, []);

  // 更新地图显示
  const updateMapDisplay = useCallback(() => {
    // 获取最新状态以避免闭包问题
    const currentMapState = mapStateRef.current;
    
    // 优先使用状态中的实例，如果不存在则使用持久化存储的实例
    const effectiveInstance = currentMapState.mapInstance || persistentMapInstance;   
    
    // 详细记录状态便于排查问题
    console.log('尝试更新地图显示:', { 
      hasInstance: !!currentMapState.mapInstance,
      hasParams: currentMapState.mapInstance ? !!currentMapState.mapInstance.params : false,
      hasPersistedInstance: !!persistentMapInstance,
      regionCode: currentMapState.regionCode, 
      dataCode: currentMapState.dataCode
    });
    
    if (!effectiveInstance) {
      // 根据激活面板选择时间参数
      console.log('更新地图参数:', {
        regionCode: currentMapState.regionCode,
        dataCode: currentMapState.dataCode,
        gridType: currentMapState.gridType,
        activePanel: currentMapState.activePanel,
        startTime: currentMapState.activePanel === 'left' ? currentMapState.leftPanelTime.startTime : currentMapState.rightPanelTime.startTime,
        endTime: currentMapState.activePanel === 'left' ? currentMapState.leftPanelTime.endTime : currentMapState.rightPanelTime.endTime
      });
      console.warn('地图实例不存在');
      return;
    } 
    
    if (!effectiveInstance.params) {
      console.warn('地图实例params不存在');
      return;
    }
    
    try {
      // 更新地图参数
      effectiveInstance.params.regionCode = currentMapState.regionCode;
      effectiveInstance.params.dataCode = currentMapState.dataCode;
      effectiveInstance.params.gridType = currentMapState.gridType;
      
      // 根据激活面板选择时间参数
      if (currentMapState.activePanel === 'left') {
        effectiveInstance.params.startTime = currentMapState.leftPanelTime.startTime;
        effectiveInstance.params.endTime = currentMapState.leftPanelTime.endTime;
      } else {
        effectiveInstance.params.startTime = currentMapState.rightPanelTime.startTime;
        effectiveInstance.params.endTime = currentMapState.rightPanelTime.endTime;
      }
      
      console.log('更新地图参数:', {
        regionCode: currentMapState.regionCode,
        dataCode: currentMapState.dataCode,
        gridType: currentMapState.gridType,
        activePanel: currentMapState.activePanel,
        startTime: effectiveInstance.params.startTime,
        endTime: effectiveInstance.params.endTime
      });
      
      // 根据区域代码长度决定调用不同的方法
      const isCommunityLevel = currentMapState.regionCode.length === 9;
      if (isCommunityLevel) {
        effectiveInstance.setPoints(true);
      } else {
        effectiveInstance.addArea(true);
      }
      console.log('地图更新成功');
    } catch (error) {
      console.error('更新地图显示出错:', error);
    }
  }, []);

  // 格式化日期时间
  const formatDateTime = (dateStr: string, isEndTime: boolean = false) => {
    if (!dateStr) return '';
    
    // 如果已经包含时间部分，直接返回
    if (dateStr.includes(':')) return dateStr;
    
    const timeStr = isEndTime ? '23:59:59' : '00:00:00';
    
    if (dateStr.includes('T')) {
      const dateOnly = dateStr.split('T')[0];
      return `${dateOnly} ${timeStr}`;
    } else if (dateStr.includes('-')) {
      return `${dateStr} ${timeStr}`;
    }
    
    return '';
  };

  // 提供上下文值
  const contextValue: MapStateContextType = {
    mapState,
    setMapInstance,
    updateRegion,
    updateDataType,
    updateTimeRange,
    updateGridType,
    resetToPageDefaults,
    updateMapDisplay,
    setActivePanel
  };

  return (
    <MapStateContext.Provider value={contextValue}>
      {children}
    </MapStateContext.Provider>
  );
};

// 自定义hook，用于在组件中访问地图状态
export const useMapState = () => {
  const context = useContext(MapStateContext);
  if (!context) {
    throw new Error('useMapState 必须在 MapStateProvider 内部使用');
  }
  return context;
}; 

// 简化数据类型选择的hook，基于常量定义
export const useDataType = (typeStr: string) => {
  // 根据typeStr返回对应的数据类型代码
  switch (typeStr) {
    case '餐饮油烟事件':
      return DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
    case '餐饮油烟告警':
      return DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_ALERT;
    case '餐饮油烟企业':
    case '餐饮企业':
      return DATA_TYPE.RESTAURANT_OIL.RESTAURANT_FACILITY;
    case '环卫事件':
      return DATA_TYPE.ENVIRONMENT.SANITATION_EVENT;
    case '环卫告警':
      return DATA_TYPE.ENVIRONMENT.SANITATION_ALERT;
    case '环卫设施':
      return DATA_TYPE.ENVIRONMENT.SANITATION_FACILITY;
    case '市政设施':
      return DATA_TYPE.MUNICIPAL.MUNICIPAL_EVENT;
    case '景观照明':
      return DATA_TYPE.LANDSCAPE_LIGHTING.LIGHTING_EVENT;
    case '生活垃圾':
      return DATA_TYPE.DOMESTIC_WASTE.WASTE_EVENT;
    case '建筑垃圾':
      return DATA_TYPE.CONSTRUCTION_WASTE.CONSTRUCTION_EVENT;
    case '行政处罚':
      return DATA_TYPE.LAW_ENFORCEMENT.PUNISHMENT;
    case '市区协同':
      return DATA_TYPE.LAW_ENFORCEMENT.COORDINATION;
    case '日常巡查':
      return DATA_TYPE.LAW_ENFORCEMENT.PATROL;
      
    default:
      return DATA_TYPE.RESTAURANT_OIL.OIL_SMOKE_EVENT;
  }
}; 
