"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _ol = require("ol");
var _layer = require("ol/layer");
var _source = require("ol/source");
var _interaction = require("ol/interaction");
var _Draw = require("ol/interaction/Draw");
var _sphere = require("ol/sphere");
var _Observable = require("ol/Observable");
var _style = require("ol/style");
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var source, vector, measureTooltip;
var measureTooltipElement, draw, sketch;
function Measure(props) {
  var map = props.map;
  var sourceProj = map.getView().getProjection();
  var doubleClickZoom = map.getInteractions().getArray().find(function (interaction) {
    return interaction instanceof _interaction.DoubleClickZoom;
  });
  source = new _source.Vector();
  function resetLayer() {
    vector && map.removeLayer(vector);
    vector = new _layer.Vector({
      source: source,
      style: new _style.Style({
        fill: new _style.Fill({
          color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new _style.Stroke({
          color: '#ffcc33',
          width: 3
        }),
        image: new _style.Circle({
          radius: 7,
          fill: new _style.Fill({
            color: '#ffcc33'
          })
        })
      })
    });
    map.addLayer(vector);
  }

  // 生成面积或长度tooltip
  function createMeasureTooltip() {
    if (measureTooltip) {
      map.removeOverlay(measureTooltip);
    }
    if (measureTooltipElement) {
      measureTooltipElement.parentNode.removeChild(measureTooltipElement);
    }
    measureTooltipElement = document.createElement('div');
    measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
    measureTooltip = new _ol.Overlay({
      element: measureTooltipElement,
      offset: [0, -15],
      positioning: 'bottom-center',
      stopEvent: false,
      insertFirst: false
    });
    map.addOverlay(measureTooltip);
  }

  // 获取面积
  function formatArea(polygon) {
    var area = (0, _sphere.getArea)(polygon, {
      projection: sourceProj
    });
    var output;
    if (area > 10000) {
      output = "".concat(Math.round(area / 1000000 * 100) / 100, " km<sup>2</sup>");
    } else {
      output = "".concat(Math.round(area * 100) / 100, " m<sup>2</sup>");
    }
    return output;
  }

  // 获取长度
  function formatLength(line) {
    var length = (0, _sphere.getLength)(line, {
      projection: sourceProj
    });
    var output;
    if (length > 100) {
      output = "".concat(Math.round(length / 1000 * 100) / 100, " km");
    } else {
      output = "".concat(Math.round(length * 100) / 100, " m");
    }
    return output;
  }

  // 测量
  function addInteraction() {
    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'point';
    draw = new _interaction.Draw({
      source: source,
      type: type,
      style: new _style.Style({
        fill: new _style.Fill({
          color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new _style.Stroke({
          color: 'rgba(0,0,0,0.5)',
          lineDash: [10, 10],
          width: 2
        }),
        image: new _style.Circle({
          radius: 5,
          stroke: new _style.Stroke({
            color: 'rgba(0,0,0,0.7)'
          }),
          fill: new _style.Fill({
            color: 'rgba(255,255,255,0.2)'
          })
        })
      })
    });
    map.addInteraction(draw);
    createMeasureTooltip();
    var listener;
    draw.on('drawstart', function (evt) {
      map.removeInteraction(doubleClickZoom);
      sketch = evt.feature;
      var tooltipCoord = evt.coordinate;
      listener = sketch.getGeometry().on('change', function (evt) {
        var geom = evt.target;
        var output;
        if (type === 'Polygon') {
          output = formatArea(geom);
          tooltipCoord = geom.getInteriorPoint().getCoordinates();
        } else if (type === 'LineString') {
          output = formatLength(geom);
          tooltipCoord = geom.getLastCoordinate();
        }
        measureTooltipElement.innerHTML = output;
        measureTooltip.setPosition(tooltipCoord);
      });
    });
    draw.on('drawend', function () {
      measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
      measureTooltip.setOffset([0, -7]);
      sketch = null;
      measureTooltipElement = null;
      (0, _Observable.unByKey)(listener);
      map.removeInteraction(draw);
      setTimeout(function () {
        map.addInteraction(doubleClickZoom);
      });
    });
  }

  // 框选 临时添加需优化
  function addFrameInteraction(callback) {
    draw = new _interaction.Draw({
      source: source,
      type: 'Circle',
      style: new _style.Style({
        fill: new _style.Fill({
          color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new _style.Stroke({
          color: 'rgba(0,0,0,0.5)',
          lineDash: [10, 10],
          width: 2
        }),
        image: new _style.Circle({
          radius: 5,
          stroke: new _style.Stroke({
            color: 'rgba(0,0,0,0.7)'
          }),
          fill: new _style.Fill({
            color: 'rgba(255,255,255,0.2)'
          })
        })
      }),
      geometryFunction: (0, _Draw.createBox)()
    });
    map.addInteraction(draw);
    draw.on('drawend', function (evt) {
      var polygon = evt.feature.getGeometry();
      setTimeout(function () {
        var features = [];
        var extent = polygon.getExtent();
        var layers = map.getLayers(); // 获取所有图层
        var allLayers = layers.getArray();
        allLayers.map(function (item) {
          var name = item.get('name');
          // 过滤地图及标注
          if (name !== 'baseMap') {
            var feature = item.getSource().getFeaturesInExtent(extent);
            if (feature && feature.length) {
              features = [].concat(_toConsumableArray(features), _toConsumableArray(feature));
            }
          }
        });
        features.length = features.length - 1;
        map.removeInteraction(draw);
        callback && callback(features);
      });
    });
  }

  // 测距
  function measureLen() {
    map.removeInteraction(draw);
    resetLayer();
    addInteraction('LineString');
  }

  // 测面
  function measureArea() {
    map.removeInteraction(draw);
    resetLayer();
    addInteraction('Polygon');
  }

  // 框选
  function frameSelect(callback) {
    map.removeInteraction(draw);
    resetLayer();
    addFrameInteraction(callback);
  }

  // 清除绘制
  function clear() {
    map.removeInteraction(draw);
    resetLayer();
  }
  return {
    measureArea: measureArea,
    measureLen: measureLen,
    frameSelect: frameSelect,
    clear: clear
  };
}
var _default = exports["default"] = Measure;
//# sourceMappingURL=measure.js.map
