"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _antd = require("antd");
var _cesium = require("../_util/cesium");
var _useProps2 = _interopRequireDefault(require("../use-props"));
var _cesium2 = require("cesium");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var SceneRoam = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _props$data = props.data,
    data = _props$data === void 0 ? [] : _props$data,
    perspective = props.perspective,
    model = props.model;
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var drawLayer = (0, _react.useRef)(null);
  var currentLine = (0, _react.useRef)([]);
  var trackedEntity = (0, _react.useRef)();
  var isPlaying = (0, _react.useRef)(false);
  var currentPerspective = (0, _react.useRef)(perspective || 'third');
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      handleChange: handleChange,
      removePreRenderHandler: removePreRenderHandler,
      handleControl: handleControl,
      startHandler: startHandler,
      pauseHandler: pauseHandler,
      stopHandler: stopHandler,
      clearData: clearData,
      drawLine: drawLine
    };
  });
  var handleChange = function handleChange(value) {
    currentPerspective.current = value;
    removePreRenderHandler();
    switch (value) {
      case 'first':
        setView();
        if (trackedEntity.current) map.trackedEntity = trackedEntity.current;
        break;
      case 'third':
        removePreRenderHandler();
        if (trackedEntity.current) map.trackedEntity = trackedEntity.current;
        break;
      case 'free':
        map.trackedEntity = undefined;
    }
  };

  // 移除 preRender 事件监听
  var removePreRenderHandler = function removePreRenderHandler() {
    map.scene.preRender.removeEventListener(renderListener);
  };
  var handleControl = function handleControl(type) {
    if (!currentLine.current.length && (type === 'start' || type === 'stop')) {
      _antd.message.info('请先绘制路线');
      return;
    }
    switch (type) {
      case 'start':
        startHandler();
        break;
      case 'pause':
        pauseHandler();
        break;
      case 'stop':
        stopHandler();
        break;
      default:
        clearData();
    }
  };

  // 开始逻辑
  var startHandler = function startHandler() {
    if (!drawLayer.current) return;
    drawLayer.current.entities.removeAll();
    map.clock.shouldAnimate = true;
    if (!isPlaying.current) {
      // 生成开始时间以及结束时间
      var start = _cesium2.JulianDate.now();
      var stop = _cesium2.JulianDate.addSeconds(start, currentLine.current.length - 1, new _cesium2.JulianDate());
      map.clock.startTime = start.clone();
      map.clock.stopTime = stop.clone();
      map.clock.currentTime = start.clone();
      map.clock.clockRange = _cesium2.ClockRange.UNBOUNDED;
      map.clock.multiplier = 0.3;
      var position = computeCirclularFlight(start);
      trackedEntity.current = drawLayer.current.entities.add({
        availability: new _cesium2.TimeIntervalCollection([new _cesium2.TimeInterval({
          start: start,
          stop: stop
        })]),
        position: position,
        orientation: new _cesium2.VelocityOrientationProperty(position),
        model: _objectSpread({
          uri: '/models/drone.glb',
          scale: 0.3
        }, model),
        path: {
          resolution: 1,
          material: new _cesium2.PolylineGlowMaterialProperty({
            glowPower: 0.1,
            color: _cesium2.Color.GREEN
          }),
          width: 16
        }
      });
      map.scene.postRender.addEventListener(isOver);
      isPlaying.current = false;
    } else {
      map.clock.multiplier = 0.3;
    }
    // 设置视角
    handleChange(currentPerspective.current);
  };
  var renderListener = (0, _react.useCallback)(function () {
    var matrix3Scratch = new _cesium2.Matrix3();
    var scratch = new _cesium2.Matrix4();
    if (map.trackedEntity) {
      var getModelMatrix = function getModelMatrix(entity, time, result) {
        var position = _cesium2.Property.getValueOrUndefined(entity.position, time, new _cesium2.Cartesian3());
        if (!(0, _cesium2.defined)(position)) {
          return undefined;
        }
        var orientation = _cesium2.Property.getValueOrUndefined(entity.orientation, time, new _cesium2.Quaternion());
        if (!(0, _cesium2.defined)(orientation)) {
          result = _cesium2.Transforms.eastNorthUpToFixedFrame(position, undefined, result);
        } else {
          result = _cesium2.Matrix4.fromRotationTranslation(_cesium2.Matrix3.fromQuaternion(orientation, matrix3Scratch), position, result);
        }
        return result;
      };
      getModelMatrix(map.trackedEntity, map.clock.currentTime, scratch);
      var transformX = 90; //距离运动点的距离（后方）
      var transformZ = 55; //距离运动点的高度（上方）
      var transformY = 0; //距离运动点的高度（侧方）
      map.scene.camera.lookAtTransform(scratch, new _cesium2.Cartesian3(-transformX, transformY, transformZ));
    }
  }, []);
  var setView = function setView() {
    removePreRenderHandler();
    //视角变换
    map.scene.preRender.addEventListener(renderListener);
  };
  var isOver = function isOver() {
    if (!trackedEntity.current) return;
    var positionProperty = trackedEntity.current.position;
    if (!positionProperty) return;
    // 得到实体对象的地理坐标位置
    var position = positionProperty.getValue(map.clock.currentTime);
    if (position && _cesium2.Cartesian3.distance(position, currentLine.current[currentLine.current.length - 1]) < 1) {
      // 播放停止
      isPlaying.current = false;
      startHandler();
      map.clock.shouldAnimate = false;
      map.clock.multiplier = 0;
      map.scene.postRender.removeEventListener(isOver);
    }
  };

  // 生成高度
  var computeCirclularFlight = function computeCirclularFlight(start) {
    if (!currentLine.current.length) {
      _antd.message.info('请先绘制路线');
      return;
    }
    var property = new _cesium2.SampledPositionProperty();
    //设置插入选项
    property.setInterpolationOptions({
      interpolationDegree: 1,
      interpolationAlgorithm: _cesium2.LagrangePolynomialApproximation
    });
    for (var i = 0; i < currentLine.current.length; i++) {
      var time = _cesium2.JulianDate.addSeconds(start, i, new _cesium2.JulianDate());
      var position = currentLine.current[i];
      property.addSample(time, position);
    }
    return property;
  };

  // 暂停逻辑
  var pauseHandler = function pauseHandler() {
    map.clock.multiplier = 0;
    isPlaying.current = true;
  };

  // 结束逻辑
  var stopHandler = function stopHandler() {
    if (!drawLayer.current) return;
    isPlaying.current = false;
    startHandler();
    map.clock.shouldAnimate = false;
    map.clock.multiplier = 0;
    map.scene.postRender.removeEventListener(isOver);
  };

  // 清除逻辑
  var clearData = function clearData() {
    if (currentLine.current) {
      currentLine.current = [];
    }
    if (drawLayer.current) drawLayer.current.entities.removeAll();
    // 清除追踪实体
    if (trackedEntity.current) trackedEntity.current = null;
  };

  // 绘制线
  var drawLine = function drawLine(clampToGround) {
    clearData();
    var handler = new _cesium2.ScreenSpaceEventHandler(map.scene.canvas);
    var position = [];
    if (handler) {
      handler.setInputAction(function (movement) {
        // 将屏幕坐标转换为笛卡尔坐标
        var cartesian = (0, _cesium.getCartesian3FromXY)(map, movement.position);
        if (cartesian && cartesian.x) {
          if (position.length === 0) {
            position.push(cartesian.clone());
          }
          position.push(cartesian);
        }
      }, _cesium2.ScreenSpaceEventType.LEFT_CLICK);
      handler.setInputAction(function (movement) {
        var catesian = (0, _cesium.getCartesian3FromXY)(map, movement.endPosition);
        if (position.length >= 2) {
          if (catesian && catesian.x) {
            position.pop();
            position.push(catesian);
          }
        }
      }, _cesium2.ScreenSpaceEventType.MOUSE_MOVE);
      handler.setInputAction(function () {
        if (handler) {
          handler.destroy();
        }
        currentLine.current = position;
      }, _cesium2.ScreenSpaceEventType.RIGHT_CLICK);
      var lineEntity = new _cesium2.Entity({
        id: 'trackLine',
        polyline: {
          positions: new _cesium2.CallbackProperty(function () {
            return position;
          }, false),
          width: 5,
          material: _cesium2.Color.BLUE.withAlpha(0.5),
          clampToGround: clampToGround
        }
      });
      if (drawLayer.current) {
        drawLayer.current.entities.add(lineEntity);
      }
    }
  };
  (0, _react.useEffect)(function () {
    drawLayer.current = new _cesium2.CustomDataSource('measureLayer');
    drawLayer.current.unclickable = true;
    drawLayer.current.cancelBubble = true;
    map.dataSources.add(drawLayer.current);
    // 默认加载为 第一视角
    if (perspective === 'first') {
      setView();
    }
    if (data !== null && data !== void 0 && data.length) {
      currentLine.current = data.map(function (item) {
        return _cesium2.Cartesian3.fromDegrees(item[0], item[1], item[2] || 10);
      });
      var lineEntity = new _cesium2.Entity({
        id: 'trackLine',
        polyline: {
          positions: currentLine.current,
          width: 5,
          material: _cesium2.Color.BLUE.withAlpha(0.5),
          clampToGround: true
        }
      });
      if (drawLayer.current) {
        drawLayer.current.entities.add(lineEntity);
      }
    }
    return function () {
      if (drawLayer.current) {
        map.dataSources.remove(drawLayer.current, true);
      }
      removePreRenderHandler();
      map.scene.postRender.removeEventListener(isOver);
    };
    // eslint-disable-next-line
  }, []);
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
});
SceneRoam.propTypes = {
  data: _propTypes["default"].array,
  perspective: _propTypes["default"].string,
  model: _propTypes["default"].object
};
var _default = exports["default"] = SceneRoam;
//# sourceMappingURL=index.js.map
