import { useState } from "react";
import { Entity, PointGraphics, useCesium } from "resium";
import { useInterval } from "ahooks";
import {
  Cartesian3,
  Color,
  JulianDate,
  LagrangePolynomialApproximation,
  PolylineDashMaterialProperty,
  SampledPositionProperty,
  TimeInterval,
  TimeIntervalCollection,
  VelocityOrientationProperty,
} from "cesium";

const data = [
  { longitude: -29, latitude: -33, height: 0, time: 0 },
  { longitude: -29, latitude: -33, height: 1000000, time: 2 },
  { longitude: 18, latitude: -50, height: 1000000, time: 6 },
  { longitude: 80, latitude: -50, height: 1000000, time: 10 },
  { longitude: 157, latitude: -35, height: 1000000, time: 14 },
  { longitude: 178, latitude: -50, height: 1000000, time: 18 },
  { longitude: -130, latitude: -65, height: 1000000, time: 22 },
];

function Point() {
  const { viewer } = useCesium();
  const [delay, setDelay] = useState(1000);

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

  const pathMaterial = new PolylineDashMaterialProperty({
    dashLength: 20,
    color: new Color(4 / 255, 251 / 255, 253 / 255),
  });

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

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

    return property;
  }

  const property = createProperty(data);

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

export default Point;
