import { useState } from "react";
import { Entity, PointGraphics, useCesium } from "resium";
import { useInterval } from "ahooks";

// 从南极到青藏高原
const dataAntarcticaToQTP = [
  { longitude: -110, latitude: -60, height: 0, time: 0 },
  { longitude: -110, latitude: -60, height: 1000000, time: 10 },
  { longitude: -30, latitude: -55, height: 1000000, time: 20 },
  { longitude: 30, latitude: -40, height: 1000000, time: 30 },
  { longitude: 65, latitude: -35, height: 1000000, time: 40 },
  { longitude: 95, latitude: -30, height: 1000000, time: 50 },
  { longitude: 95, latitude: -30, height: 0, time: 60 },
];

function Point() {
  const { viewer } = useCesium();

  const [delay, setDelay] = useState(1000);

  const start = viewer.clock.startTime;
  const stop = viewer.clock.stopTime;

  const pathMaterial = new Cesium.Color(4 / 255, 251 / 255, 253 / 255);

  useInterval(() => {
    if (viewer.clock?.shouldAnimate) setDelay(undefined);
  }, delay);

  /**
   * 计算飞行路径
   * 数据坐标
   * {SampledPositionProperty|*}
   */
  function createProperty(source) {
    let property = new Cesium.SampledPositionProperty();
    for (let i = 0; i < source.length; i++) {
      let time = Cesium.JulianDate.addSeconds(
        start,
        source[i].time,
        new Cesium.JulianDate()
      );
      let position = Cesium.Cartesian3.fromDegrees(
        source[i].longitude,
        source[i].latitude,
        source[i].height
      );
      // 添加位置，和时间对应
      property.addSample(time, position);
    }
    property.setInterpolationOptions({
      interpolationDegree: 1,
      interpolationAlgorithm: Cesium.LinearApproximation,
    });
    return property;
  }

  const property = createProperty(dataAntarcticaToQTP);

  return (
    <Entity
      id={"point"}
      position={property}
      availability={
        new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({
            start,
            stop,
          }),
        ])
      }
      orientation={new Cesium.VelocityOrientationProperty(property)}
      path={{
        resolution: 1,
        material: pathMaterial,
        // leadTime、trailTime 不设置 path全显示
        leadTime: 0, // 设置为0时 模型通过后显示path
        // trailTime: 0, // 设置为0时 模型通过后隐藏path
        width: 2,
      }}
    >
      <PointGraphics
        show={true}
        color={Cesium.Color.SKYBLUE}
        outlineColor={Cesium.Color.YELLOW}
        outlineWidth={3}
      />
    </Entity>
  );
}

export default Point;
