import { adu } from "./drawUtils.js";

// 线-标绘工具类
class PointDrawer {
  constructor(arg) {
    this.viewer = arg.viewer;

    this.id = arg.id; // id
    this.opts = arg.opts; //标注属性

    this.afterDraw = arg.afterDraw; //标注完成

    this.points = []; //标注结果
    this.entity = null; //标注
    this.tempPoints = []; //临时点
  }
  // 开始
  start() {
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    // 单击-标注
    this.handler.setInputAction((e) => {
      const pos = adu.getPos(e.position, this.viewer); //点坐标
      if (!pos) {
        return;
      }
      //第一个点，标注临时点
      this.tempPoints.push(
        adu.addPoint(
          {
            outlineWidth: 2,
            ...pos,
          },
          this.viewer
        )
      );

      this.points.push(pos); //添加点
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动-绘制
    this.handler.setInputAction((e) => {
      //没有点，直接返回
      if (this.points.length < 1) {
        return;
      }

      const pos = adu.getPos(e.endPosition, this.viewer); //当前坐标
      if (!pos) {
        return;
      }

      //如果没有标注，添加标注
      if (!this.entity) {
        this.entity = adu.addLine(
          {
            id: this.id,
            ...this.opts,
            points: [...this.points, ...[pos]],
          },
          this.viewer
        );
      } else {
        this.updateEntity([...adu.points2Arr(this.points), pos.lng, pos.lat]); //更新标绘
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //右键-结束
    this.handler.setInputAction(() => {
      //移除临时点
      this.removeTemp();

      //如果不足两点，移除
      if (this.points.length < 2) {
        adu.remove(this.entity, this.viewer); //移除线
        this.reset(); //重置
        return;
      }

      this.updateEntity(adu.points2Arr(this.points)); //更新标绘

      //标注完成回调
      if (this.afterDraw) {
        this.afterDraw(this.points, this.entity);
      }

      this.reset(); //重置
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
  //重置
  reset(arg) {
    if (arg) {
      this.id = arg.id;
      this.opts = arg.opts; //标注属性
    }

    this.points = [];
    this.entity = null;
    this.tempPoints = [];
  }
  //更新对象
  updateEntity(positions) {
    this.entity.polyline.positions = new Cesium.CallbackProperty(() => {
      return Cesium.Cartesian3.fromDegreesArray(positions);
    }, false);
  }
  // 销毁鼠标事件
  destroy() {
    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
  }
  //移除临时标注
  removeTemp() {
    if (this.tempPoints) {
      this.tempPoints.forEach((item) => {
        adu.remove(item, this.viewer);
      });
      this.tempPoints = [];
    }
  }
}

export default PointDrawer;
