import { CheckOutlined, DeleteOutlined } from "@ant-design/icons";
import { useMount } from "ahooks";
import { Input, message, Modal } from "antd";
import { useEffect, useRef, useState } from "react";
import CesiumMap from "zy-react-library/components/Map/CesiumMap";
import { dynamicLoadCss, dynamicLoadJs } from "zy-react-library/utils";

const ElectronicFenceModal = (props) => {
  const { position } = props;
  const [latitudeAndLongitudeSet, setLatitudeAndLongitudeSet] = useState("");
  const [isDrawing, setIsDrawing] = useState(true); // 是否正在绘制
  const [isCompleted, setIsCompleted] = useState(false); // 是否已完成绘制

  const mapContainerRef = useRef(null); // 存储地图容器引用
  const mapInstanceRef = useRef(null); // 存储地图实例
  const pointsRef = useRef([]); // 存储所有点击的点位
  const entitiesRef = useRef([]); // 存储所有绘制的实体(点位和线条)
  const handlerRef = useRef(null); // 存储鼠标点击事件处理器
  const isDrawingRef = useRef(isDrawing); // 使用ref存储isDrawing
  const isCompletedRef = useRef(isCompleted); // 使用ref存储isCompleted

  // 同步状态到ref
  useEffect(() => {
    isDrawingRef.current = isDrawing;
  }, [isDrawing]);

  useEffect(() => {
    isCompletedRef.current = isCompleted;
  }, [isCompleted]);

  // 从position字符串解析点位数组
  const parsePositionString = (positionStr) => {
    if (!positionStr)
      return [];
    return positionStr.split(";").map((coord) => {
      const [longitude, latitude] = coord.split(",");
      return { longitude: Number(longitude), latitude: Number(latitude) };
    });
  };

  // 将笛卡尔坐标转换为经纬度点位
  const convertCartesianToPoint = (cartesian) => {
    const cartographic = window.Cesium.Cartographic.fromCartesian(cartesian);
    const longitude = window.Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = window.Cesium.Math.toDegrees(cartographic.latitude);
    return { longitude, latitude };
  };

  // 在地图上添加点位
  const addPoint = (point) => {
    const viewer = mapInstanceRef.current;
    if (!viewer)
      return;

    pointsRef.current.push(point);

    const pointEntity = viewer.entities.add({
      position: window.Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude),
      point: {
        pixelSize: 10,
        color: window.Cesium.Color.RED,
        outlineColor: window.Cesium.Color.WHITE,
        outlineWidth: 2,
        verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,
        heightReference: window.Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        clampToGround: true,
      },
    });
    entitiesRef.current.push(pointEntity);
  };

  // 在两点之间绘制连线
  const drawLineBetweenPoints = (startPoint, endPoint) => {
    const viewer = mapInstanceRef.current;
    if (!viewer)
      return;

    const lineEntity = viewer.entities.add({
      polyline: {
        positions: window.Cesium.Cartesian3.fromDegreesArray([
          startPoint.longitude,
          startPoint.latitude,
          endPoint.longitude,
          endPoint.latitude,
        ]),
        width: 3,
        material: window.Cesium.Color.RED,
        verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,
        heightReference: window.Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        clampToGround: true,
      },
    });
    entitiesRef.current.push(lineEntity);
  };

  // 绘制多边形填充
  const drawPolygonFill = (points) => {
    const viewer = mapInstanceRef.current;
    if (!viewer)
      return;

    const positions = points.flatMap(point => [point.longitude, point.latitude]);
    const polygonEntity = viewer.entities.add({
      polygon: {
        hierarchy: window.Cesium.Cartesian3.fromDegreesArray(positions),
        material: window.Cesium.Color.RED.withAlpha(0.2),
      },
    });
    entitiesRef.current.push(polygonEntity);
  };

  // 更新经纬度显示
  const updateLatitudeAndLongitudeDisplay = () => {
    const points = pointsRef.current;
    if (points.length === 0) {
      setLatitudeAndLongitudeSet("");
      return;
    }

    const coordinateString = points
      .map(point => `${point.longitude},${point.latitude}`)
      .join(";");
    setLatitudeAndLongitudeSet(coordinateString);
  };

  // 清除绘制
  const handleClearDrawing = () => {
    const viewer = mapInstanceRef.current;
    if (!viewer)
      return;

    // 清除所有绘制的实体
    entitiesRef.current.forEach((entity) => {
      viewer.entities.remove(entity);
    });

    // 清空数组和状态
    pointsRef.current = [];
    entitiesRef.current = [];
    setLatitudeAndLongitudeSet("");
    setIsCompleted(false);
    setIsDrawing(true);
  };

  // 根据position绘制已存在的围栏
  const drawExistingFence = (positionStr) => {
    const viewer = mapInstanceRef.current;
    if (!viewer || !positionStr)
      return;

    const points = parsePositionString(positionStr);
    if (points.length === 0)
      return;

    // 绘制所有点位
    points.forEach(point => addPoint(point));

    // 绘制连线
    for (let i = 0; i < points.length - 1; i++) {
      drawLineBetweenPoints(points[i], points[i + 1]);
    }

    // 将最后一个点和第一个点相连
    drawLineBetweenPoints(points[points.length - 1], points[0]);

    // 绘制多边形填充
    drawPolygonFill(points);

    // 更新状态
    setIsCompleted(true);
    setIsDrawing(false);
    setLatitudeAndLongitudeSet(positionStr);
  };

  // 监听position变化
  useEffect(() => {
    if (position && mapInstanceRef.current) {
      // 清除现有绘制
      handleClearDrawing();
      // 绘制传入的围栏
      drawExistingFence(position);
    }
  }, [position]);

  // 处理地图点击事件
  const handleMapClick = (movement) => {
    const viewer = mapInstanceRef.current;
    if (!viewer || !isDrawingRef.current || isCompletedRef.current)
      return;

    // 获取点击位置的三维坐标
    const cartesian = viewer.camera.pickEllipsoid(
      movement.position,
      viewer.scene.globe.ellipsoid,
    );

    if (window.Cesium.defined(cartesian)) {
      const point = convertCartesianToPoint(cartesian);
      addPoint(point);
      if (pointsRef.current.length > 1) {
        drawLineBetweenPoints(pointsRef.current[pointsRef.current.length - 2], point);
      }
      updateLatitudeAndLongitudeDisplay();
    }
  };

  // 初始化地图
  const initMap = () => {
    if (mapContainerRef.current) {
      if (!mapInstanceRef.current) {
        const { init, flyTo } = new CesiumMap();
        const { viewer } = init();
        mapInstanceRef.current = viewer;
        flyTo({ longitude: window.mapLongitude, latitude: window.mapLatitude, height: 900000 });

        if (!props.disabled) {
          // 设置鼠标点击事件
          const handler = new window.Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
          handler.setInputAction(handleMapClick, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
          handlerRef.current = handler;
        }

        // 如果传入了position参数,则绘制已存在的围栏
        if (position) {
          drawExistingFence(position);
        }
      }
    }
  };

  // 加载Cesium地图
  const loadCesiumMap = async () => {
    if (!window.Cesium) {
      if (window?.base?.loadDynamicResource) {
        await window.base.loadDynamicResource({
          url: "https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Cesium.js",
          type: "script",
          attr: { type: "text/javascript" },
        });
        await window.base.loadDynamicResource({
          url: "https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Widgets/widgets.css",
          type: "link",
          attr: { rel: "stylesheet", type: "text/css" },
        });
        initMap();
      }
      else {
        await dynamicLoadJs("https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Cesium.js");
        await dynamicLoadCss("https://cesium.com/downloads/cesiumjs/releases/1.91/Build/Cesium/Widgets/widgets.css");
        initMap();
      }
    }
    else {
      initMap();
    }
  };

  // 完成绘制
  const handleCompleteDrawing = () => {
    // 如果已经完成绘制,提示需要先清除
    if (isCompleted) {
      message.warning("若已完成绘制,请先点击清除绘制按钮。");
      return;
    }

    if (pointsRef.current.length < 3) {
      // 至少需要3个点才能形成闭合区域
      message.warning("至少需要3个点才能完成绘制");
      return;
    }

    const points = pointsRef.current;
    const firstPoint = points[0];
    const lastPoint = points[points.length - 1];

    // 将最后一个点和第一个点相连
    drawLineBetweenPoints(lastPoint, firstPoint);

    // 绘制多边形填充
    drawPolygonFill(points);

    setIsCompleted(true);
    setIsDrawing(false);
  };

  useMount(() => {
    loadCesiumMap();
    return () => {
      if (mapInstanceRef.current) {
        try {
          mapInstanceRef.current.destroy();
          mapInstanceRef.current = null;
        }
        catch (e) {
          console.warn("Error destroying map on unmount:", e);
        }
        mapInstanceRef.current = null;
      }
    };
  });

  return (
    <Modal
      open
      title="电子围栏"
      maskClosable={false}
      onCancel={props?.onCancel}
      onOk={() => {
        if (!isCompleted) {
          message.warning("若已完成绘制，请先点击完成绘制按钮。");
          return;
        }
        props?.onOk(latitudeAndLongitudeSet);
      }}
      confirmLoading={props?.confirmLoading}
      width={800}
    >
      <div
        ref={mapContainerRef}
        id="map_container"
        style={{ width: "100%", height: "500px" }}
      />
      <div style={{ display: "flex", gap: 15, alignItems: "center", marginTop: 16 }}>
        {
          !props.disabled && (
            <>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  cursor: isDrawing && !isCompleted ? "pointer" : "not-allowed",
                  opacity: isDrawing && !isCompleted ? 1 : 0.5,
                }}
                onClick={handleCompleteDrawing}
              >
                <CheckOutlined style={{ fontSize: 16 }} />
                <span style={{ fontSize: 12, color: "#666" }}>完成绘制</span>
              </div>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  cursor: "pointer",
                }}
                onClick={handleClearDrawing}
              >
                <DeleteOutlined style={{ fontSize: 16 }} />
                <span style={{ fontSize: 12, color: "#666" }}>清除绘制</span>
              </div>
            </>
          )
        }
        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: "100px" }}>区域经纬度：</div>
          <Input value={latitudeAndLongitudeSet} readOnly />
        </div>
      </div>
    </Modal>
  );
};

export default ElectronicFenceModal;
