import React, {
   useMemo,
   useEffect,
   useRef,
   useState,
   useCallback,
} from "react";
import { Typography, Badge, Button, Space,InputNumber } from "antd";
import { DownloadOutlined } from "@ant-design/icons";
import {
   Chart as ChartJS,
   CategoryScale,
   LinearScale,
   PointElement,
   LineElement,
   Title as ChartTitle,
   Tooltip,
   Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";

// 注册Chart.js组件
ChartJS.register(
   CategoryScale,
   LinearScale,
   PointElement,
   LineElement,
   ChartTitle,
   Tooltip,
   Legend
);

const { Title } = Typography;

const RealtimeCharts = ({ tableData, lastUpdateTime, onDataExport,exportCount = 200, setExportCount }) => {
   const xChartRef = useRef(null);
   const yChartRef = useRef(null);

   // 添加标靶显示状态控制
   const [visibleTargets, setVisibleTargets] = useState({});

   // 添加数据验证
   if (!Array.isArray(tableData)) {
      return <div>数据格式错误</div>;
   }

   // 固定的设备颜色映射，确保颜色一致性 - 使用数组下标作为颜色选取依据
   const getDeviceColor = (index) => {
      // 预定义5种颜色，足够应对最多5条线的需求
      const colors = [
         "#52c41a", // 绿色
         "#faad14", // 橙色
         "#f5222d", // 红色
         "#722ed1", // 紫色
         "#13c2c2", // 青色
      ];

      // 直接使用传入的数组下标
      return colors[index % colors.length];
   };

   // 数据采样函数 - 每秒采样一次，最多保留25个数据点
   const sampleData = (data) => {
      if (!data || data.length === 0) {
         return {
            labels: [],
            deviceIds: [],
            timeGroups: {},
            sortedTimes: [],
         };
      }

      try {
         // 按时间分组数据
         const timeGroups = {};
         data.forEach((item) => {
            if (!item || !item.updateTime) return;

            const timeKey = Math.floor(
               new Date(item.updateTime).getTime() / 1000
            ); // 按秒分组
            if (!timeGroups[timeKey]) {
               timeGroups[timeKey] = [];
            }
            timeGroups[timeKey].push(item);
         });

         // 取最新的25秒数据
         const sortedTimes = Object.keys(timeGroups)
            .sort((a, b) => Number(b) - Number(a))
            .slice(0, 25)
            .reverse();

         // 获取所有设备ID
         const deviceIds = [
            ...new Set(data.map((item) => item?.deviceId).filter(Boolean)),
         ].sort();

         // 生成时间标签
         const labels = sortedTimes.map((timeKey) => {
            return new Date(Number(timeKey) * 1000).toLocaleTimeString(
               "zh-CN",
               {
                  hour: "2-digit",
                  minute: "2-digit",
                  second: "2-digit",
               }
            );
         });

         return { labels, deviceIds, timeGroups, sortedTimes };
      } catch (error) {
         console.error(`${new Date().toLocaleString()} - 数据采样出错:`, error);
         return {
            labels: [],
            deviceIds: [],
            timeGroups: {},
            sortedTimes: [],
         };
      }
   };

   // 初始化可见目标状态
   const { deviceIds } = sampleData(tableData);

   // 获取 deviceId 到 desc 的映射
   const deviceDescMap = useMemo(() => {
      const map = {};
      tableData.forEach((item) => {
         if (item.deviceId && item.desc) {
            map[item.deviceId] = item.desc;
         }
      });
      return map;
   }, [tableData]);

   useEffect(() => {
      if (deviceIds.length > 0) {
         const initialVisible = {};
         deviceIds.forEach((deviceId) => {
            initialVisible[deviceId] = true; // 默认所有标靶都显示
         });
         setVisibleTargets((prev) => ({ ...initialVisible, ...prev }));
      }
   }, [deviceIds.join(",")]);

   // 切换标靶显示状态的函数
   const toggleTargetVisibility = useCallback((deviceId) => {
      setVisibleTargets((prev) => ({
         ...prev,
         [deviceId]: !prev[deviceId],
      }));

      // 同时控制两个图表的显示状态
      const xChart = xChartRef.current;
      const yChart = yChartRef.current;

      if (xChart && yChart) {
         const xDatasetIndex = xChart.data.datasets.findIndex(
            (dataset) => dataset.label === deviceId
         );
         const yDatasetIndex = yChart.data.datasets.findIndex(
            (dataset) => dataset.label === deviceId
         );

         if (xDatasetIndex !== -1 && yDatasetIndex !== -1) {
            const isVisible = xChart.isDatasetVisible(xDatasetIndex);

            // 切换显示状态
            xChart.setDatasetVisibility(xDatasetIndex, !isVisible);
            yChart.setDatasetVisibility(yDatasetIndex, !isVisible);

            // 更新图表
            xChart.update();
            yChart.update();
         }
      }
   }, []);

   // 全部显示/隐藏的函数
   const toggleAllTargets = useCallback(
      (visible) => {
         const newVisibleTargets = {};
         deviceIds.forEach((deviceId) => {
            newVisibleTargets[deviceId] = visible;
         });
         setVisibleTargets(newVisibleTargets);

         // 同时控制两个图表
         const xChart = xChartRef.current;
         const yChart = yChartRef.current;

         if (xChart && yChart) {
            xChart.data.datasets.forEach((_, index) => {
               xChart.setDatasetVisibility(index, visible);
            });
            yChart.data.datasets.forEach((_, index) => {
               yChart.setDatasetVisibility(index, visible);
            });

            xChart.update();
            yChart.update();
         }
      },
      [deviceIds]
   );

   // 准备X轴图表数据
   const xChartData = useMemo(() => {
      try {
         const { labels, deviceIds, timeGroups, sortedTimes } =
            sampleData(tableData);

         if (!deviceIds || deviceIds.length === 0) {
            return { labels: [], datasets: [] };
         }

         const datasets = deviceIds.map((deviceId, index) => {
            const data = sortedTimes.map((timeKey) => {
               const timeData = timeGroups[timeKey] || [];
               const deviceData = timeData.find(
                  (item) => item.deviceId === deviceId
               );
               return deviceData && deviceData.xValue !== undefined
                  ? parseFloat(deviceData.xValue)
                  : null;
            });

            const deviceDesc = deviceDescMap[deviceId] || deviceId;
            return {
               label: deviceId,
               data: data,
               borderColor: getDeviceColor(index),
               backgroundColor: getDeviceColor(index) + "20",
               borderWidth: 2,
               pointRadius: 3,
               pointHoverRadius: 5,
               tension: 0,
               connectNulls: false,
               hidden: !visibleTargets[deviceId], // 根据状态控制显示
            };
         });

         return { labels, datasets };
      } catch (error) {
         console.error(
            `${new Date().toLocaleString()} - 准备X轴图表数据出错:`,
            error
         );
         return { labels: [], datasets: [] };
      }
   }, [tableData, visibleTargets]);

   // 准备Y轴图表数据
   const yChartData = useMemo(() => {
      try {
         const { labels, deviceIds, timeGroups, sortedTimes } =
            sampleData(tableData);

         if (!deviceIds || deviceIds.length === 0) {
            return { labels: [], datasets: [] };
         }

         const datasets = deviceIds.map((deviceId, index) => {
            const data = sortedTimes.map((timeKey) => {
               const timeData = timeGroups[timeKey] || [];
               const deviceData = timeData.find(
                  (item) => item.deviceId === deviceId
               );
               return deviceData && deviceData.yValue !== undefined
                  ? parseFloat(deviceData.yValue)
                  : null;
            });

            const deviceDesc = deviceDescMap[deviceId] || deviceId;
            return {
               label: deviceId,
               data: data,
               borderColor: getDeviceColor(index),
               backgroundColor: getDeviceColor(index) + "20",
               borderWidth: 2,
               pointRadius: 3,
               pointHoverRadius: 5,
               tension: 0,
               connectNulls: false,
               hidden: !visibleTargets[deviceId], // 根据状态控制显示
            };
         });

         return { labels, datasets };
      } catch (error) {
         console.error(
            `${new Date().toLocaleString()} - 准备Y轴图表数据出错:`,
            error
         );
         return { labels: [], datasets: [] };
      }
   }, [tableData, visibleTargets]);

   // Chart.js配置选项 - 移到组件内部以访问 deviceDescMap
   const chartOptions = useMemo(
      () => ({
         responsive: true,
         maintainAspectRatio: false,
         interaction: {
            mode: "index",
            intersect: false,
         },
         plugins: {
            legend: {
               display: false, // 隐藏默认图例，使用自定义控制器
            },
            tooltip: {
               filter: function (tooltipItem) {
                  return tooltipItem.parsed.y !== null;
               },
               callbacks: {
                  title: function (context) {
                     return context[0].label; // 显示时间
                  },
                  label: function (context) {
                     const deviceId = context.dataset.label;
                     const deviceDesc = deviceDescMap[deviceId] || deviceId;
                     const value = context.parsed.y;
                     return `${deviceDesc}: ${value}`;
                  },
               },
            },
         },
         scales: {
            x: {
               display: true,
               title: {
                  display: true,
                  text: "时间",
               },
               ticks: {
                  maxRotation: 45,
                  minRotation: 0,
                  font: {
                     size: 10,
                  },
               },
            },
            y: {
               display: true,
               title: {
                  display: true,
                  font: {
                     size: 12,
                  },
               },
               ticks: {
                  font: {
                     size: 10,
                  },
               },
            },
         },
         elements: {
            point: {
               radius: 3,
               hoverRadius: 5,
            },
            line: {
               tension: 0,
            },
         },
      }),
      [deviceDescMap]
   );

   // X轴图表配置
   const xChartOptions = useMemo(
      () => ({
         ...chartOptions,
         plugins: {
            ...chartOptions.plugins,
            title: {
               display: true,
               text: "X轴位移数据",
               font: {
                  size: 16,
               },
            },
         },
         scales: {
            ...chartOptions.scales,
            y: {
               ...chartOptions.scales.y,
               title: {
                  ...chartOptions.scales.y.title,
                  text: "X值(mm)",
               },
            },
         },
      }),
      [chartOptions]
   );

   // Y轴图表配置
   const yChartOptions = useMemo(
      () => ({
         ...chartOptions,
         plugins: {
            ...chartOptions.plugins,
            title: {
               display: true,
               text: "Y轴位移数据",
               font: {
                  size: 16,
               },
            },
         },
         scales: {
            ...chartOptions.scales,
            y: {
               ...chartOptions.scales.y,
               title: {
                  ...chartOptions.scales.y.title,
                  text: "Y值(mm)",
               },
            },
         },
      }),
      [chartOptions]
   );

   // 如果没有数据，显示空状态
   if (!tableData || tableData.length === 0) {
      return (
         <div
            style={{
               flex: 2,
               padding: "16px",
               display: "flex",
               flexDirection: "column",
            }}
         >
            <Title level={4} style={{ marginBottom: "16px" }}>
               实时数据图
               <Badge
                  status="default"
                  text="等待数据..."
                  style={{ marginLeft: "16px", fontSize: "12px" }}
               />
            </Title>
            <div
               style={{
                  flex: 1,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  minHeight: "500px",
               }}
            >
               <div style={{ textAlign: "center", color: "#999" }}>
                  <p>等待实时数据...</p>
               </div>
            </div>
         </div>
      );
   }

   return (
      <div
         style={{
            flex: 2,
            padding: "16px",
            display: "flex",
            flexDirection: "column",
         }}
      >
         <Title
            level={4}
            style={{
               marginBottom: "16px",
               display: "flex",
               alignItems: "center",
            }}
         >
            实时数据图
            <Badge
               status="processing"
               text={`实时更新 - 最后更新: ${lastUpdateTime.toLocaleTimeString()}`}
               style={{ marginLeft: "16px", fontSize: "12px" }}
            />
            <Badge
               status="success"
               text={`图表数据采样频率:1Hz`}
               style={{ marginLeft: "16px", fontSize: "12px" }}
            />
            <Badge
               status="default"
               text={`导出数据条数配置`}
               style={{ marginLeft: "16px", fontSize: "12px" }}
            />
            <InputNumber
               min={1}
               max={1000}
               value={exportCount}
               onChange={setExportCount}
               style={{ marginLeft: 16, width: 80 }}
               step={1}
            />
            <Button
               style={{ marginLeft: 8 }}
               icon={<DownloadOutlined />}
               onClick={() => onDataExport(exportCount)}
            >
               导出
            </Button>
         </Title>

         {/* 统一的图例控制器 */}
         <div
            style={{
               marginBottom: "16px",
               padding: "12px",
               backgroundColor: "#fafafa",
               borderRadius: "6px",
            }}
         >
            <div
               style={{
                  marginBottom: "8px",
                  fontSize: "14px",
                  fontWeight: "500",
               }}
            >
               显示控制
            </div>
            <Space wrap>
               <Button
                  size="small"
                  onClick={() => toggleAllTargets(true)}
                  type="primary"
               >
                  全部显示
               </Button>
               <Button size="small" onClick={() => toggleAllTargets(false)}>
                  全部隐藏
               </Button>
               {deviceIds.map((deviceId, index) => (
                  <Button
                     key={deviceId}
                     size="small"
                     type={visibleTargets[deviceId] ? "primary" : "default"}
                     style={{
                        borderColor: getDeviceColor(index),
                        color: visibleTargets[deviceId]
                           ? "#fff"
                           : getDeviceColor(index),
                        backgroundColor: visibleTargets[deviceId]
                           ? getDeviceColor(index)
                           : "#fff",
                     }}
                     onClick={() => toggleTargetVisibility(deviceId)}
                  >
                     {deviceDescMap[deviceId] || deviceId}
                  </Button>
               ))}
            </Space>
         </div>

         <div
            style={{
               flex: 1,
               display: "flex",
               flexDirection: "column",
               gap: "20px",
               minHeight: "500px",
            }}
         >
            {/* X轴折线图 */}
            <div
               style={{
                  flex: 1,
                  backgroundColor: "white",
                  borderRadius: "8px",
                  border: "1px solid #e8e8e8",
                  minHeight: "280px",
                  padding: "16px",
               }}
            >
               <Line
                  ref={xChartRef}
                  data={xChartData}
                  options={xChartOptions}
               />
            </div>

            {/* Y轴折线图 */}
            <div
               style={{
                  flex: 1,
                  backgroundColor: "white",
                  borderRadius: "8px",
                  border: "1px solid #e8e8e8",
                  minHeight: "280px",
                  padding: "16px",
               }}
            >
               <Line
                  ref={yChartRef}
                  data={yChartData}
                  options={yChartOptions}
               />
            </div>
         </div>
      </div>
   );
};

export default RealtimeCharts;
