import React, { useEffect, useState } from "react";
import { Tag } from "antd";

export default function EncoderDisplay({ config }) {
  const [encoderData, setEncoderData] = useState({
    rpm: 0,
    speed: "0 km/h",
    direction: "停止"
  });

  useEffect(() => {
    // 创建 WebSocket 连接
    const wsUrl = `${window.location.protocol === 'https:' ? 'wss://' : 'ws://'}${window.location.host}/encoder`;
    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
      console.log('Encoder WebSocket 连接已打开');
      // 请求当前状态
      ws.send(JSON.stringify({ action: "get-status" }));
    };

    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        if (message.type === "encoder-data") {
          const { rpm, speed, direction } = message.payload;
          setEncoderData({
            rpm: rpm || 0,
            speed: speed || "0 km/h",
            direction: direction || "停止"
          });
        }
      } catch (error) {
        console.error("解析编码器消息失败:", error);
      }
    };

    ws.onerror = (error) => {
      console.error("Encoder WebSocket 错误:", error);
    };

    ws.onclose = () => {
      console.log('Encoder WebSocket 连接已关闭');
    };

    // 组件卸载时关闭连接
    return () => {
      ws.close();
    };
  }, []);

  if (!config.enabled) {
    return null;
  }

  return (
    <div className="encoder-display">
      {config.showRpm && (
        <Tag color="blue">
          {config.rpmLabel || "转速"}: {encoderData.rpm.toFixed(2)}rpm
        </Tag>
      )}
      <Tag color="green">
        {config.speedLabel || "车速"}: {encoderData.speed}
      </Tag>
      {config.showDirection && (
        <Tag color="orange">
          {config.directionLabel || "方向"}: {encoderData.direction}
        </Tag>
      )}
    </div>
  );
}