"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _layer = require("ol/layer");
var _source = require("ol/source");
var _Style = _interopRequireDefault(require("ol/style/Style"));
var _Stroke = _interopRequireDefault(require("ol/style/Stroke"));
var _transform = require("ol/transform");
var _createFeatureCollection = require("../feature-layer/createFeatureCollection");
var _sampleArrowsAlongLine = require("./sampleArrowsAlongLine");
var _arrow = _interopRequireDefault(require("../assets/arrow.png"));
var _excluded = ["data", "features", "key", "name", "map", "lineStyle", "arrowStyle", "flowSpeed", "flowCycleSeconds", "minZoomForFlow", "maxArrowsPerLine", "zIndex", "show", "layerControl", "legend"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
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 defaultLineStroke = {
  color: 'rgba(36, 145, 252, 0.95)',
  width: 3
};

/**
 * 未配置 flowCycleSeconds 时：周期(秒) = BASE_CYCLE_SEC / flowSpeed，flowSpeed 越大越快。
 */
var DEFAULT_BASE_CYCLE_SEC = 6;
var DEFAULT_FLOW_SPEED = 1;

/** 流动刷新间隔(ms)，整图 render 上限约 1000/此值 fps；略大更省性能 */
var DEFAULT_FLOW_RENDER_MS = 33;

/** 未传 src 时与 PathLineLayer 共用 arrow.png；src 为 null / '' 则仅用 Canvas 描边箭头 */
function resolveArrowBitmapSrc(arrowStyle) {
  if (!arrowStyle) {
    return _arrow["default"];
  }
  var s = arrowStyle.src;
  if (s === null || s === '') {
    return null;
  }
  if (s === undefined) {
    return _arrow["default"];
  }
  return s;
}

/** Canvas 描边「>」形，圆角端点与连接，形态对齐 components/assets/arrow.png */
function drawChevronArrow(ctx, color, headLen, headWidth, lineW, strokeWidthOpt) {
  var strokeW = strokeWidthOpt != null ? strokeWidthOpt : lineW >= 1.5 ? lineW : Math.max(2.25, headWidth * 0.52);
  var tipX = headLen * 0.88;
  var backX = -headLen * 0.38;
  var wingY = headWidth * 0.52;
  ctx.strokeStyle = color;
  ctx.lineWidth = strokeW;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  ctx.beginPath();
  ctx.moveTo(backX, -wingY);
  ctx.lineTo(tipX, 0);
  ctx.lineTo(backX, wingY);
  ctx.stroke();
}

/**
 * 轨迹箭头流动图层（组合模式，对齐 FlyLineLayer）：
 * 内部为标准 ol VectorLayer，避免「继承 VectorLayer」在部分环境下与 OL 渲染路径不一致；
 * OL 在 replay 为空时会跳过 postRender，普通矢量线图层与 FlyLine 一致可稳定触发 postrender。
 */
var ArrowFlowLayer = exports["default"] = /*#__PURE__*/function () {
  function ArrowFlowLayer(options) {
    var _ref, _arrowStyle$spacingPx;
    _classCallCheck(this, ArrowFlowLayer);
    var data = options.data,
      features = options.features,
      key = options.key,
      name = options.name,
      map = options.map,
      _options$lineStyle = options.lineStyle,
      lineStyle = _options$lineStyle === void 0 ? {} : _options$lineStyle,
      _options$arrowStyle = options.arrowStyle,
      arrowStyle = _options$arrowStyle === void 0 ? {} : _options$arrowStyle,
      flowSpeedOption = options.flowSpeed,
      flowCycleSecondsOption = options.flowCycleSeconds,
      minZoomForFlowOption = options.minZoomForFlow,
      _options$maxArrowsPer = options.maxArrowsPerLine,
      maxArrowsPerLine = _options$maxArrowsPer === void 0 ? 500 : _options$maxArrowsPer,
      zIndex = options.zIndex,
      _options$show = options.show,
      show = _options$show === void 0 ? true : _options$show,
      _options$layerControl = options.layerControl,
      layerControl = _options$layerControl === void 0 ? true : _options$layerControl,
      legend = options.legend,
      rest = _objectWithoutProperties(options, _excluded);
    var source = new _source.Vector(features ? {
      features: features
    } : {});
    this.vectorLayer = new _layer.Vector(_objectSpread(_objectSpread({}, rest), {}, {
      source: source,
      style: new _Style["default"]({
        stroke: new _Stroke["default"](_objectSpread(_objectSpread({}, defaultLineStroke), lineStyle))
      }),
      zIndex: zIndex,
      updateWhileAnimating: true,
      updateWhileInteracting: true
    }));
    this.vectorLayer.key = key;
    this.vectorLayer.name = name;
    this.vectorLayer.layerControl = layerControl;
    this.vectorLayer.legend = legend;
    this.vectorLayer.show = show;
    this.key = key;
    this.name = name;
    this.map = map;
    this.layerControl = layerControl;
    this.legend = legend;
    this.show = show;
    this._lineStyleOptions = lineStyle;
    this._arrowStyle = arrowStyle;
    this.maxArrowsPerLine = maxArrowsPerLine;
    this.spacingPx = (_ref = (_arrowStyle$spacingPx = arrowStyle.spacingPx) !== null && _arrowStyle$spacingPx !== void 0 ? _arrowStyle$spacingPx : arrowStyle.spacing) !== null && _ref !== void 0 ? _ref : 80;
    this.flowSpeed = arrowStyle.flowSpeed != null ? arrowStyle.flowSpeed : flowSpeedOption != null ? flowSpeedOption : DEFAULT_FLOW_SPEED;
    this._flowPerfOrigin = null;
    this.flowCycleSeconds = arrowStyle.flowCycleSeconds != null ? arrowStyle.flowCycleSeconds : flowCycleSecondsOption != null ? flowCycleSecondsOption : null;
    this.flowRenderMinIntervalMs = arrowStyle.flowRenderMinIntervalMs != null ? arrowStyle.flowRenderMinIntervalMs : DEFAULT_FLOW_RENDER_MS;
    this.minZoomForFlow = arrowStyle.minZoomForFlow != null ? arrowStyle.minZoomForFlow : minZoomForFlowOption != null ? minZoomForFlowOption : null;
    this._flowDriverId = null;
    this._onViewResolutionChange = this._syncFlowDriverToZoom.bind(this);
    if (this.map) {
      var view = this.map.getView();
      if (view) {
        view.on('change:resolution', this._onViewResolutionChange);
      }
    }
    this._arrowImage = null;
    this._arrowImageSrc = null;
    this._onPostRender = this.onPostRender.bind(this);
    this.vectorLayer.on('postrender', this._onPostRender);
    this._loadArrowImageFromStyle(arrowStyle);
    if (data) {
      this.loadData(data);
    }
    this.vectorLayer.setVisible(show);
    this._syncFlowDriverToZoom();
  }

  /** 当前缩放是否达到展示流动箭头的层级（未配置阈值则始终为 true） */
  return _createClass(ArrowFlowLayer, [{
    key: "_flowZoomSufficient",
    value: function _flowZoomSufficient() {
      if (this.minZoomForFlow == null) {
        return true;
      }
      var view = this.map && this.map.getView();
      if (!view) {
        return true;
      }
      var z = view.getZoom();
      if (z == null || Number.isNaN(z)) {
        return true;
      }
      return z >= this.minZoomForFlow;
    }
  }, {
    key: "_shouldRunFlowDriver",
    value: function _shouldRunFlowDriver() {
      return this.show && this.vectorLayer.getVisible() && this._flowZoomSufficient();
    }
  }, {
    key: "_syncFlowDriverToZoom",
    value: function _syncFlowDriverToZoom() {
      if (this._shouldRunFlowDriver()) {
        this._startFlowDriver();
      } else {
        this._stopFlowDriver();
        if (this.map && this.show && this.vectorLayer.getVisible()) {
          this.map.render();
        }
      }
    }
  }, {
    key: "_startFlowDriver",
    value: function _startFlowDriver() {
      var _this = this;
      if (this._flowDriverId != null || !this.map) {
        return;
      }
      if (!this._shouldRunFlowDriver()) {
        return;
      }
      if (this.vectorLayer.getVisible()) {
        this.map.render();
      }
      this._flowDriverId = setInterval(function () {
        if (!_this._shouldRunFlowDriver()) {
          _this._stopFlowDriver();
          if (_this.map && _this.show && _this.vectorLayer.getVisible()) {
            _this.map.render();
          }
          return;
        }
        _this.map.render();
      }, this.flowRenderMinIntervalMs);
    }
  }, {
    key: "_stopFlowDriver",
    value: function _stopFlowDriver() {
      if (this._flowDriverId != null) {
        clearInterval(this._flowDriverId);
        this._flowDriverId = null;
      }
    }
  }, {
    key: "_restartFlowDriver",
    value: function _restartFlowDriver() {
      this._stopFlowDriver();
      this._syncFlowDriverToZoom();
    }
  }, {
    key: "getSource",
    value: function getSource() {
      return this.vectorLayer.getSource();
    }
  }, {
    key: "setVisible",
    value: function setVisible(value) {
      this.vectorLayer.setVisible(value);
    }
  }, {
    key: "getVisible",
    value: function getVisible() {
      return this.vectorLayer.getVisible();
    }
  }, {
    key: "_loadArrowImageFromStyle",
    value: function _loadArrowImageFromStyle(arrowStyle) {
      var _this2 = this;
      var src = resolveArrowBitmapSrc(arrowStyle || {});
      if (!src) {
        this._arrowImage = null;
        this._arrowImageSrc = null;
        return;
      }
      if (src === this._arrowImageSrc) {
        return;
      }
      this._arrowImageSrc = src;
      this._arrowImage = null;
      var img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = function () {
        _this2._arrowImage = img;
        if (_this2.map) {
          _this2.map.render();
        }
      };
      img.onerror = function () {
        _this2._arrowImage = null;
      };
      img.src = src;
    }
  }, {
    key: "setShow",
    value: function setShow(value) {
      this.show = value;
      this.vectorLayer.show = value;
      this.vectorLayer.setVisible(value);
      if (!value) {
        this._flowPerfOrigin = null;
        this._stopFlowDriver();
      } else {
        this._syncFlowDriverToZoom();
      }
    }
  }, {
    key: "setLineStyle",
    value: function setLineStyle(lineStyle) {
      this._lineStyleOptions = lineStyle || {};
      this.vectorLayer.setStyle(new _Style["default"]({
        stroke: new _Stroke["default"](_objectSpread(_objectSpread({}, defaultLineStroke), this._lineStyleOptions))
      }));
    }
  }, {
    key: "setArrowStyle",
    value: function setArrowStyle(arrowStyle) {
      this._arrowStyle = arrowStyle || {};
      if (arrowStyle) {
        if (arrowStyle.spacingPx != null || arrowStyle.spacing != null) {
          var _ref2, _arrowStyle$spacingPx2;
          this.spacingPx = (_ref2 = (_arrowStyle$spacingPx2 = arrowStyle.spacingPx) !== null && _arrowStyle$spacingPx2 !== void 0 ? _arrowStyle$spacingPx2 : arrowStyle.spacing) !== null && _ref2 !== void 0 ? _ref2 : this.spacingPx;
        }
        if (arrowStyle.flowSpeed != null) {
          this.flowSpeed = arrowStyle.flowSpeed;
        }
        if (arrowStyle.flowCycleSeconds !== undefined) {
          this.flowCycleSeconds = arrowStyle.flowCycleSeconds;
        }
        if (arrowStyle.flowRenderMinIntervalMs != null) {
          this.flowRenderMinIntervalMs = arrowStyle.flowRenderMinIntervalMs;
          this._restartFlowDriver();
        }
        if (arrowStyle.minZoomForFlow !== undefined) {
          this.minZoomForFlow = arrowStyle.minZoomForFlow;
          this._syncFlowDriverToZoom();
        }
      }
      this._loadArrowImageFromStyle(arrowStyle || {});
    }
  }, {
    key: "loadData",
    value: function loadData(data) {
      this.getSource().clear();
      var fs = (0, _createFeatureCollection.createGeoJson)(data);
      if (fs && fs.length) {
        this.getSource().addFeatures(fs);
      }
    }
  }, {
    key: "loadFeatures",
    value: function loadFeatures(featureList) {
      this.getSource().clear();
      if (featureList && featureList.length) {
        this.getSource().addFeatures(featureList);
      }
    }
  }, {
    key: "onPostRender",
    value: function onPostRender(event) {
      var _as$headLength, _as$headWidth, _as$lineWidth;
      var ctx = event.context;
      if (!ctx || typeof ctx.save !== 'function') {
        return;
      }
      if (!this.vectorLayer.getVisible()) {
        return;
      }
      if (!this._flowZoomSufficient()) {
        return;
      }
      var frameState = event.frameState;
      if (!frameState || !frameState.viewState) {
        return;
      }
      var resolution = frameState.viewState.resolution;
      var extent = frameState.extent;
      var stepWorld = this.spacingPx * resolution;
      if (stepWorld <= 0) {
        return;
      }
      if (this._flowPerfOrigin == null) {
        this._flowPerfOrigin = performance.now();
      }
      var elapsedMs = performance.now() - this._flowPerfOrigin;
      var cycleSec;
      if (this.flowCycleSeconds != null && this.flowCycleSeconds > 0) {
        cycleSec = this.flowCycleSeconds;
      } else {
        cycleSec = DEFAULT_BASE_CYCLE_SEC / Math.max(0.05, this.flowSpeed);
      }
      var phase = elapsedMs / 1000 % cycleSec / cycleSec * stepWorld;
      var transform = (0, _transform.multiply)(event.inversePixelTransform.slice(), frameState.coordinateToPixelTransform.slice());
      var as = this._arrowStyle || {};
      var color = as.color || '#ffffff';
      var headLen = (_as$headLength = as.headLength) !== null && _as$headLength !== void 0 ? _as$headLength : 10;
      var headWidth = (_as$headWidth = as.headWidth) !== null && _as$headWidth !== void 0 ? _as$headWidth : 7;
      var lineW = (_as$lineWidth = as.lineWidth) !== null && _as$lineWidth !== void 0 ? _as$lineWidth : 1;
      var strokeWidth = as.strokeWidth;
      var opacity = as.opacity != null ? as.opacity : 1;
      var bitmapSrc = resolveArrowBitmapSrc(as);
      var imgScale = as.scale != null ? as.scale : 1;
      var imgWidth = as.imgWidth;
      var imgHeight = as.imgHeight;
      ctx.save();
      ctx.globalAlpha = opacity;
      var features = this.getSource().getFeatures();
      for (var fi = 0; fi < features.length; fi++) {
        var geom = features[fi].getGeometry();
        var lines = (0, _sampleArrowsAlongLine.flattenLineStrings)(geom);
        for (var li = 0; li < lines.length; li++) {
          var line = lines[li];
          var samples = (0, _sampleArrowsAlongLine.sampleArrowsForLineString)(line, extent, {
            stepWorld: stepWorld,
            phase: phase,
            maxArrows: this.maxArrowsPerLine
          });
          for (var si = 0; si < samples.length; si++) {
            var s = samples[si];
            var angle = (0, _sampleArrowsAlongLine.getPixelAngle)(transform, s.c0, s.c1);
            var pt = s.coord.slice();
            (0, _transform.apply)(transform, pt);
            var x = pt[0];
            var y = pt[1];
            if (bitmapSrc && this._arrowImage && this._arrowImage.complete) {
              var w = (imgWidth || this._arrowImage.width) * imgScale;
              var h = (imgHeight || this._arrowImage.height) * imgScale;
              ctx.save();
              ctx.translate(x, y);
              ctx.rotate(angle);
              ctx.drawImage(this._arrowImage, -w / 2, -h / 2, w, h);
              ctx.restore();
            } else if (!bitmapSrc) {
              ctx.save();
              ctx.translate(x, y);
              ctx.rotate(angle);
              drawChevronArrow(ctx, color, headLen, headWidth, lineW, strokeWidth);
              ctx.restore();
            }
          }
        }
      }
      ctx.restore();
      // 不在此处 map.render()：会与定时器叠加重绘整图。由 _startFlowDriver 按 flowRenderMinIntervalMs 触发 render。
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this._stopFlowDriver();
      this._flowPerfOrigin = null;
      if (this.map) {
        var view = this.map.getView();
        if (view) {
          view.un('change:resolution', this._onViewResolutionChange);
        }
      }
      this.vectorLayer.un('postrender', this._onPostRender);
    }
  }]);
}();
//# sourceMappingURL=ArrowFlowLayer.js.map
