import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useData, useMap } from "../MapComponent";
import ToolbarButton from "@/components/olmap/common/ToolbarButton";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import PaletteOutlinedIcon from "@mui/icons-material/PaletteOutlined";
import QueryStatsOutlinedIcon from "@mui/icons-material/QueryStatsOutlined";
import CompareArrowsOutlinedIcon from "@mui/icons-material/CompareArrowsOutlined";
import PropertyPanel from "./PropertyPanel"; // 引入属性面板组件
import DrawPanel from "./DrawPanel"; // 引入绘图面板组件

import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { Style, Stroke, Fill, Circle } from "ol/style";
import Feature from "ol/Feature";
import StyleEditorPanel from "./StyleEditorPanel";
import { createDefaultLayerStyleStates } from "./styleEditorPresets";
import { LayerStyleState } from "./styleEditorTypes";
import StyleLegend from "./StyleLegend"; // 引入图例组件
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
import { useNotification } from "@refinedev/core";
import ToolbarHistoryPanel from "./ToolbarHistoryPanel";
import {
  buildFeatureProperties,
} from "./toolbarFeatureHelpers";
import { useToolbarChatActions } from "./useToolbarChatActions";
import { useStyleEditor } from "./useStyleEditor";

import { config, NETWORK_NAME } from "@/config/config";
import { useProject } from "@/contexts/ProjectContext";
import { apiFetch } from "@/lib/apiFetch";
import { permissionCodes } from "@/lib/permissions";
import { useAccessStore } from "@/store/accessStore";

// 添加接口定义隐藏按钮的props
interface ToolbarProps {
  hiddenButtons?: string[]; // 可选的隐藏按钮列表，例如 ['info', 'draw', 'style']
  queryType?: string; // 可选的查询类型参数
  schemeType?: string; // 可选的方案类型参数
  HistoryPanel?: React.ComponentType<any>; // 可选的自定义历史数据面板
  enableCompare?: boolean;
}

type LinkStatus = "OPEN" | "CLOSED" | "ACTIVE";
type ValveProperties = {
  vType: string | null;
  setting: string | null;
};

const isValveLayer = (layerId: string | undefined) =>
  layerId === "geo_valves_mat" || layerId === "geo_valves";

const isLinkStatus = (value: unknown): value is LinkStatus =>
  value === "OPEN" || value === "CLOSED" || value === "ACTIVE";

const normalizeValveSetting = (value: unknown): string | null => {
  if (value === undefined || value === null) return null;
  return String(value);
};

const validateValveSetting = (
  valveType: string | null,
  value: string,
): string | null => {
  const normalizedType = valveType?.toUpperCase();
  const trimmedValue = value.trim();
  const numericTypes = new Set(["PRV", "PSV", "PBV", "FCV", "TCV"]);

  if (normalizedType === "GPV") {
    return trimmedValue ? null : "GPV 阀门设置值必须是非空曲线 ID。";
  }

  if (numericTypes.has(normalizedType ?? "")) {
    if (!trimmedValue) {
      return "阀门设置值必须是 0 或正数。";
    }

    const numericValue = Number(trimmedValue);
    if (!Number.isFinite(numericValue) || numericValue < 0) {
      return "阀门设置值必须是有限数字，且大于或等于 0。";
    }

    return null;
  }

  return trimmedValue ? null : "阀门设置值不能为空。";
};

const Toolbar: React.FC<ToolbarProps> = ({
  hiddenButtons,
  queryType,
  schemeType,
  HistoryPanel,
  enableCompare = false,
}) => {
  const map = useMap();
  const data = useData();
  const project = useProject();
  const canEditNetwork = useAccessStore((state) =>
    state.permissions.includes(permissionCodes.webgisEdit),
  );
  const { open } = useNotification();
  const [activeTools, setActiveTools] = useState<string[]>([]);
  const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
  const [showPropertyPanel, setShowPropertyPanel] = useState<boolean>(false);
  const [showDrawPanel, setShowDrawPanel] = useState<boolean>(false);
  const [showStyleEditor, setShowStyleEditor] = useState<boolean>(false);
  const [showHistoryPanel, setShowHistoryPanel] = useState<boolean>(false);
  const [highlightLayer, setHighlightLayer] =
    useState<VectorLayer<VectorSource> | null>(null);
  const currentTime = data?.currentTime;
  const selectedDate = data?.selectedDate;
  const schemeName = data?.schemeName;
  const networkName = project?.networkName || NETWORK_NAME;
  const isCompareMode = data?.isCompareMode ?? false;
  const toggleCompareMode = data?.toggleCompareMode;
  const canToggleCompare = Boolean(
    enableCompare && (isCompareMode || (queryType === "scheme" && schemeName)),
  );

  useEffect(() => {
    if (!enableCompare && isCompareMode) {
      toggleCompareMode?.();
    }
  }, [enableCompare, isCompareMode, toggleCompareMode]);

  useEffect(() => {
    if (!canEditNetwork) {
      setShowDrawPanel(false);
      setActiveTools((previous) =>
        previous.filter((tool) => tool !== "draw"),
      );
    }
  }, [canEditNetwork]);

  // Chat tool action → direct featureInfos override (bypasses OL Feature lookup)
  const [chatPanelFeatureInfos, setChatPanelFeatureInfos] = useState<
    [string, string][] | null
  >(null);
  const [chatPanelType, setChatPanelType] = useState<
    "realtime" | "scheme" | "none"
  >("none");
  const [chatPanelTimeRange, setChatPanelTimeRange] = useState<{
    startTime?: string;
    endTime?: string;
  } | null>(null);

  // 样式状态管理 - 在 Toolbar 中管理，带有默认样式
  const [layerStyleStates, setLayerStyleStates] = useState<LayerStyleState[]>(
    () => createDefaultLayerStyleStates()
  );
  const styleEditor = useStyleEditor({
    layerStyleStates,
    setLayerStyleStates,
    workspace: project?.workspace || config.MAP_WORKSPACE,
  });

  useToolbarChatActions({
    setHighlightFeatures,
    setChatPanelFeatureInfos,
    setChatPanelType,
    setChatPanelTimeRange,
    setShowHistoryPanel,
    setShowStyleEditor,
    setActiveTools,
    applyExternalStyle: styleEditor.applyExternalStyle,
    resetExternalStyle: styleEditor.resetExternalStyle,
  });

  // 计算激活的图例配置
  const activeLegendConfigs = layerStyleStates
    .filter((state) => state.isActive && state.legendConfig.property)
    .map((state) => ({
      ...state.legendConfig,
      layerName: state.layerName,
      layerId: state.layerId,
    }));
  // 创建高亮图层
  useEffect(() => {
    if (!map) return;

    const highLightSource = new VectorSource();
    const highLightLayer = new VectorLayer({
      source: highLightSource,
      style: new Style({
        stroke: new Stroke({
          color: `rgba(255, 0, 0, 1)`,
          width: 5,
        }),
        fill: new Fill({
          color: `rgba(255, 0, 0, 0.2)`,
        }),
        image: new Circle({
          radius: 7,
          stroke: new Stroke({
            color: `rgba(255, 0, 0, 1)`,
            width: 3,
          }),
          fill: new Fill({
            color: `rgba(255, 0, 0, 0.2)`,
          }),
        }),
      }),
      properties: {
        name: "属性查询高亮图层", // 设置图层名称
        value: "info_highlight_layer",
        queryable: false,
        type: "multigeometry",
        properties: [],
      },
    });

    map.addLayer(highLightLayer);
    setHighlightLayer(highLightLayer);

    return () => {
      map.removeLayer(highLightLayer);
    };
  }, [map]);
  // 高亮要素的函数
  useEffect(() => {
    if (!highlightLayer) {
      return;
    }
    const source = highlightLayer.getSource();
    if (!source) {
      return;
    }
    // 清除之前的高亮
    source.clear();
    // 添加新的高亮要素
    highlightFeatures.forEach((feature) => {
      if (feature instanceof Feature) {
        source.addFeature(feature);
      }
    });
  }, [highlightFeatures, highlightLayer]);
  // 地图点击选择要素事件处理函数
  const handleMapClickSelectFeatures = useCallback(
    async (event: { coordinate: number[] }) => {
      if (!map) return;
      const feature = await mapClickSelectFeatures(event, map); // 调用导入的函数

      if (!feature || !(feature instanceof Feature)) {
        // 如果没有点击到要素，且当前是 info 模式，则清除高亮
        if (activeTools.includes("info")) {
          setHighlightFeatures([]);
        }
        return;
      }

      if (activeTools.includes("history")) {
        // 历史查询模式：支持同类型多选
        const featureId = feature.getProperties().id;
        const layerId = feature.getId()?.toString().split(".")[0] || "";
        console.log("点击选择要素", feature, "图层：", layerId);
        // 简单的类型检查函数
        const getBaseType = (lid: string) => {
          if (lid.includes("pipe")) return "pipe";
          if (lid.includes("junction")) return "junction";
          if (lid.includes("tank")) return "tank";
          if (lid.includes("reservoir")) return "reservoir";
          if (lid.includes("pump")) return "pump";
          if (lid.includes("valve")) return "valve";
          return lid;
        };

        // 检查是否与已选要素类型一致
        if (highlightFeatures.length > 0) {
          const firstLayerId =
            highlightFeatures[0].getId()?.toString().split(".")[0] || "";

          if (getBaseType(layerId) !== getBaseType(firstLayerId)) {
            // 如果点击的是已选中的要素（为了取消选中），则不报错
            const isAlreadySelected = highlightFeatures.some(
              (f) => f.getProperties().id === featureId,
            );
            if (!isAlreadySelected) {
              open?.({
                type: "error",
                message: "请选择相同类型的要素进行多选查询。",
              });
              return;
            }
          }
        }

        setHighlightFeatures((prev) => {
          const existingIndex = prev.findIndex(
            (f) => f.getProperties().id === featureId,
          );

          if (existingIndex !== -1) {
            // 如果已存在，移除
            return prev.filter((_, i) => i !== existingIndex);
          } else {
            // 如果不存在，添加
            return [...prev, feature];
          }
        });
      } else {
        // 其他模式（如 info）：单选
        setHighlightFeatures([feature]);
      }
    },
    [map, activeTools, highlightFeatures, open],
  );
  // 添加矢量属性查询事件监听器
  useEffect(() => {
    if (!map) return;
    // 监听 info 或 history 工具激活时添加
    if (activeTools.includes("info") || activeTools.includes("history")) {
      map.on("click", handleMapClickSelectFeatures);

      return () => {
        map.un("click", handleMapClickSelectFeatures);
      };
    }
  }, [activeTools, map, handleMapClickSelectFeatures]);

  // 处理工具栏按钮点击事件
  const handleToolClick = (tool: string) => {
    // 样式工具的特殊处理 - 只有再次点击时才会取消激活和关闭
    if (tool === "style") {
      if (activeTools.includes("style")) {
        // 如果样式工具已激活，点击时关闭
        setShowStyleEditor(false);
        setActiveTools((prev) => prev.filter((t) => t !== "style"));
      } else {
        // 激活样式工具，打开样式面板
        setActiveTools((prev) => [...prev, "style"]);
        setShowStyleEditor(true);
      }
      return;
    }

    // 其他工具的处理逻辑
    if (activeTools.includes(tool)) {
      // 如果当前工具已激活，再次点击时取消激活并关闭面板
      deactivateTool(tool);
      setActiveTools((prev) => prev.filter((t) => t !== tool));
    } else {
      // 如果当前工具未激活，保留其他已打开工具，仅新增当前工具
      setActiveTools((prev) => [...prev, tool]);

      // 激活当前工具并打开对应面板
      activateTool(tool);
    }
  };

  // 取消激活指定工具并关闭对应面板
  const deactivateTool = (tool: string) => {
    switch (tool) {
      case "info":
        setShowPropertyPanel(false);
        if (!activeTools.includes("history")) {
          setHighlightFeatures([]);
        }
        break;
      case "draw":
        setShowDrawPanel(false);
        break;
      case "history":
        setShowHistoryPanel(false);
        if (!activeTools.includes("info")) {
          setHighlightFeatures([]);
        }
        setChatPanelFeatureInfos(null);
        setChatPanelTimeRange(null);
        break;
    }
  };

  // 激活指定工具并打开对应面板
  const activateTool = (tool: string) => {
    switch (tool) {
      case "info":
        setShowPropertyPanel(true);
        break;
      case "draw":
        setShowDrawPanel(true);
        break;
      case "history":
        setShowHistoryPanel(true);
        // 激活历史查询后：HistoryDataPanel 自行负责根据传入的 props 拉取数据。
        break;
    }
  };

  const [computedProperties, setComputedProperties] = useState<
    Record<string, any>
  >({});
  const [valveStatus, setValveStatus] = useState<LinkStatus | null>(null);
  const [isValveStatusLoading, setIsValveStatusLoading] = useState(false);
  const [isValveStatusSaving, setIsValveStatusSaving] = useState(false);
  const [valveProperties, setValveProperties] = useState<ValveProperties>({
    vType: null,
    setting: null,
  });
  const [isValvePropertiesLoading, setIsValvePropertiesLoading] =
    useState(false);
  const [isValveSettingSaving, setIsValveSettingSaving] = useState(false);

  const selectedFeature = highlightFeatures[0];
  const selectedFeatureLayer = selectedFeature
    ?.getId()
    ?.toString()
    .split(".")[0];
  const selectedFeatureId = selectedFeature?.getProperties?.().id;
  const selectedFeatureValveType = selectedFeature?.getProperties?.().v_type;
  const selectedValveType =
    valveProperties.vType ??
    (selectedFeatureValveType ? String(selectedFeatureValveType) : null);
  const selectedValveId =
    showPropertyPanel && isValveLayer(selectedFeatureLayer) && selectedFeatureId
      ? String(selectedFeatureId)
      : null;

  useEffect(() => {
    if (!selectedValveId) {
      setValveStatus(null);
      setIsValveStatusLoading(false);
      return;
    }

    let cancelled = false;

    const queryValveStatus = async () => {
      setIsValveStatusLoading(true);
      setValveStatus(null);

      try {
        const params = new URLSearchParams({
          link: selectedValveId,
        });
        const response = await apiFetch(
          `${config.BACKEND_URL}/api/v1/status?${params.toString()}`,
        );

        if (!response.ok) {
          throw new Error(`getstatus failed: ${response.status}`);
        }

        const data = await response.json();
        if (!cancelled) {
          setValveStatus(isLinkStatus(data?.status) ? data.status : null);
        }
      } catch (error) {
        console.error("Error querying valve status:", error);
        if (!cancelled) {
          setValveStatus(null);
          open?.({
            type: "error",
            message: "读取阀门开关状态失败。",
          });
        }
      } finally {
        if (!cancelled) {
          setIsValveStatusLoading(false);
        }
      }
    };

    queryValveStatus();

    return () => {
      cancelled = true;
    };
  }, [networkName, open, selectedValveId]);

  useEffect(() => {
    if (!selectedValveId) {
      setValveProperties({ vType: null, setting: null });
      setIsValvePropertiesLoading(false);
      return;
    }

    let cancelled = false;

    const queryValveProperties = async () => {
      setIsValvePropertiesLoading(true);
      setValveProperties({ vType: null, setting: null });

      try {
        const params = new URLSearchParams({
          valve: selectedValveId,
        });
        const response = await apiFetch(
          `${config.BACKEND_URL}/api/v1/valves/properties?${params.toString()}`,
        );

        if (!response.ok) {
          throw new Error(`getvalveproperties failed: ${response.status}`);
        }

        const data = await response.json();
        if (!cancelled) {
          setValveProperties({
            vType: data?.v_type ? String(data.v_type) : null,
            setting: normalizeValveSetting(data?.setting),
          });
        }
      } catch (error) {
        console.error("Error querying valve properties:", error);
        if (!cancelled) {
          setValveProperties({ vType: null, setting: null });
          open?.({
            type: "error",
            message: "读取阀门设置值失败。",
          });
        }
      } finally {
        if (!cancelled) {
          setIsValvePropertiesLoading(false);
        }
      }
    };

    queryValveProperties();

    return () => {
      cancelled = true;
    };
  }, [networkName, open, selectedValveId]);

  const handleValveStatusSave = useCallback(
    async (nextStatus: string) => {
      if (!selectedValveId || !isLinkStatus(nextStatus)) {
        return;
      }

      setIsValveStatusSaving(true);
      try {
        const params = new URLSearchParams({
          link: selectedValveId,
        });
        const response = await apiFetch(
          `${config.BACKEND_URL}/api/v1/status-properties?${params.toString()}`,
          {
            method: "PATCH",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ status: nextStatus }),
          },
        );

        if (!response.ok) {
          throw new Error(`setstatus failed: ${response.status}`);
        }

        setValveStatus(nextStatus);
        open?.({
          type: "success",
          message: "阀门开关状态已更新。",
        });
      } catch (error) {
        console.error("Error updating valve status:", error);
        open?.({
          type: "error",
          message: "阀门开关状态更新失败。",
        });
      } finally {
        setIsValveStatusSaving(false);
      }
    },
    [open, selectedValveId],
  );

  const handleValveSettingSave = useCallback(
    async (nextSetting: string) => {
      if (!selectedValveId) {
        return;
      }

      if (valveStatus === "OPEN" || valveStatus === "CLOSED") {
        open?.({
          type: "error",
          message: "开启或关闭状态下不能编辑阀门设置值。",
        });
        return;
      }

      const validationMessage = validateValveSetting(
        selectedValveType,
        nextSetting,
      );
      if (validationMessage) {
        open?.({
          type: "error",
          message: validationMessage,
        });
        return;
      }

      const trimmedSetting = nextSetting.trim();
      setIsValveSettingSaving(true);
      try {
        const params = new URLSearchParams({
          valve: selectedValveId,
        });
        const response = await apiFetch(
          `${config.BACKEND_URL}/api/v1/valves/properties?${params.toString()}`,
          {
            method: "PATCH",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ setting: trimmedSetting }),
          },
        );

        if (!response.ok) {
          throw new Error(`setvalveproperties failed: ${response.status}`);
        }

        setValveProperties((prev) => ({
          ...prev,
          setting: trimmedSetting,
        }));
        open?.({
          type: "success",
          message: "阀门设置值已更新。",
        });
      } catch (error) {
        console.error("Error updating valve setting:", error);
        open?.({
          type: "error",
          message: "阀门设置值更新失败。",
        });
      } finally {
        setIsValveSettingSaving(false);
      }
    },
    [
      open,
      selectedValveId,
      selectedValveType,
      valveStatus,
    ],
  );

  // 添加 useEffect 来查询计算属性
  useEffect(() => {
    if (highlightFeatures.length === 0 || !selectedDate || !showPropertyPanel) {
      setComputedProperties({});
      return;
    }

    const highlightFeature = highlightFeatures[0];
    const id = highlightFeature.getProperties().id;
    if (!id) {
      setComputedProperties({});
      return;
    }

    const queryComputedProperties = async () => {
      try {
        const properties = highlightFeature?.getProperties?.() || {};
        const type =
          properties.geometry?.getType?.() === "LineString" ? "link" : "node";
        // selectedDate 格式化为 YYYY-MM-DD
        let dateObj: Date;
        if (selectedDate instanceof Date) {
          dateObj = new Date(selectedDate);
        } else {
          dateObj = new Date(selectedDate);
        }
        const minutes = Number(currentTime) || 0;
        dateObj.setHours(Math.floor(minutes / 60), minutes % 60, 0, 0);
        // 转为 UTC ISO 字符串
        const querytime = dateObj.toISOString(); // 例如 "2025-09-16T16:30:00.000Z"
        let response;
        if (queryType === "scheme") {
          response = await apiFetch(
            // `${config.BACKEND_URL}/queryschemesimulationrecordsbyidtime/?scheme_name=${schemeName}&id=${id}&querytime=${querytime}&type=${type}`
            `${config.BACKEND_URL}/api/v1/timeseries/schemes/simulation-results?scheme_type=${schemeType}&scheme_name=${schemeName}&id=${id}&type=${type}&query_time=${querytime}`,
          );
        } else {
          response = await apiFetch(
            // `${config.BACKEND_URL}/querysimulationrecordsbyidtime/?id=${id}&querytime=${querytime}&type=${type}`
            `${config.BACKEND_URL}/api/v1/timeseries/realtime/simulation-results?id=${id}&type=${type}&query_time=${querytime}`,
          );
        }
        if (!response.ok) {
          throw new Error("API request failed");
        }
        const data = await response.json();
        if (!data.result || data.result.length === 0) {
          setComputedProperties({});
        } else {
          setComputedProperties(data.result[0] || {});
          // console.log("查询到的计算属性：", data.result[0]);
        }
      } catch (error) {
        console.error("Error querying computed properties:", error);
        setComputedProperties({});
      }
    };
    // 仅当 currentTime 有效时查询
    if (currentTime !== -1 && queryType) queryComputedProperties();
  }, [highlightFeatures, currentTime, selectedDate, queryType, schemeName, schemeType, showPropertyPanel]);

  const propertyPanelData = useMemo(
    () =>
      buildFeatureProperties(
        selectedFeature,
        computedProperties,
        canEditNetwork && selectedValveId
          ? {
              value: valveStatus,
              loading: isValveStatusLoading,
              saving: isValveStatusSaving,
              onSave: handleValveStatusSave,
            }
          : undefined,
        canEditNetwork && selectedValveId
          ? {
              value: valveProperties.setting,
              vType: selectedValveType,
              loading: isValvePropertiesLoading,
              saving: isValveSettingSaving,
              status: valveStatus,
              onSave: handleValveSettingSave,
            }
          : undefined,
      ),
    [
      selectedFeature,
      computedProperties,
      canEditNetwork,
      selectedValveId,
      valveStatus,
      valveProperties,
      selectedValveType,
      isValveStatusLoading,
      isValveStatusSaving,
      isValvePropertiesLoading,
      isValveSettingSaving,
      handleValveStatusSave,
      handleValveSettingSave,
    ],
  );

  if (!data) {
    return null;
  }

  return (
    <>
      <div className="absolute top-4 left-4 bg-white p-1 rounded-xl shadow-lg flex opacity-85 hover:opacity-100 transition-opacity">
        {!hiddenButtons?.includes("info") && (
          <ToolbarButton
            icon={<InfoOutlinedIcon />}
            name="查看属性"
            isActive={activeTools.includes("info")}
            onClick={() => handleToolClick("info")}
          />
        )}
        {!hiddenButtons?.includes("history") && (
          <ToolbarButton
            icon={<QueryStatsOutlinedIcon />}
            name="查询历史数据"
            isActive={activeTools.includes("history")}
            onClick={() => handleToolClick("history")}
          />
        )}
        {canEditNetwork && !hiddenButtons?.includes("draw") && (
          <ToolbarButton
            icon={<EditOutlinedIcon />}
            name="标记绘制"
            isActive={activeTools.includes("draw")}
            onClick={() => handleToolClick("draw")}
          />
        )}
        {!hiddenButtons?.includes("style") && (
          <ToolbarButton
            icon={<PaletteOutlinedIcon />}
            name="图层样式"
            isActive={activeTools.includes("style")}
            onClick={() => handleToolClick("style")}
          />
        )}
        {enableCompare && (
          <ToolbarButton
            icon={<CompareArrowsOutlinedIcon />}
            name={isCompareMode ? "关闭对比" : "双屏对比"}
            isActive={isCompareMode}
            onClick={() => toggleCompareMode?.()}
            disabled={!canToggleCompare}
          />
        )}
      </div>
      {showPropertyPanel && (
        <PropertyPanel
          {...propertyPanelData}
          onClose={() => {
            deactivateTool("info");
            setActiveTools((prev) => prev.filter((t) => t !== "info"));
          }}
        />
      )}
      {showDrawPanel && map && <DrawPanel />}
      <div style={{ display: showStyleEditor ? "block" : "none" }}>
        <StyleEditorPanel
          isReady={styleEditor.isReady}
          renderLayers={styleEditor.renderLayers}
          selectedRenderLayer={styleEditor.selectedRenderLayer}
          styleConfig={styleEditor.styleConfig}
          setStyleConfig={styleEditor.setStyleConfig}
          availableProperties={styleEditor.availableProperties}
          onLayerChange={styleEditor.handleLayerChange}
          onPropertyChange={styleEditor.handlePropertyChange}
          onClassificationMethodChange={styleEditor.handleClassificationMethodChange}
          onSegmentsChange={styleEditor.handleSegmentsChange}
          onCustomBreakChange={styleEditor.handleCustomBreakChange}
          onColorTypeChange={styleEditor.handleColorTypeChange}
          onApply={styleEditor.handleApply}
          onReset={styleEditor.handleReset}
          validationErrors={styleEditor.validationErrors}
          isDirty={styleEditor.isDirty}
          isApplying={styleEditor.isApplying}
        />
      </div>
      <ToolbarHistoryPanel
        showHistoryPanel={showHistoryPanel}
        chatPanelType={chatPanelType}
        chatPanelFeatureInfos={chatPanelFeatureInfos}
        chatPanelTimeRange={chatPanelTimeRange}
        highlightFeatures={highlightFeatures}
        HistoryPanel={HistoryPanel}
        schemeName={schemeName}
        queryType={queryType}
        onClose={() => {
          deactivateTool("history");
          setActiveTools((prev) => prev.filter((t) => t !== "history"));
        }}
      />

      {/* 图例显示 */}
      {activeLegendConfigs.length > 0 && (
        <div className="absolute bottom-40 right-4 drop-shadow-xl flex flex-row items-end max-w-screen-lg overflow-x-auto z-10">
          <div className="flex flex-row gap-3">
            {activeLegendConfigs.map((config, index) => (
              <StyleLegend key={`${config.layerId}-${index}`} {...config} />
            ))}
          </div>
        </div>
      )}
    </>
  );
};

export default Toolbar;
