"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _style2 = require("ol/style");
var _interaction = require("ol/interaction");
var _geom = require("ol/geom");
var _source = require("ol/source");
var _layer = require("ol/layer");
var _format = require("ol/format");
var _ol = require("ol");
var _condition = require("ol/events/condition");
var _turf = require("@turf/turf");
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var createBox = _interaction.Draw.createBox;
var format = new _format.GeoJSON();
var getCoordinateAndType = function getCoordinateAndType(geometry) {
  var coordinates, type;
  if (geometry instanceof _geom.Point) {
    coordinates = [geometry.getCoordinates()];
  } else if (geometry instanceof _geom.Polygon) {
    coordinates = geometry.getCoordinates()[0];
  } else if (geometry instanceof _geom.LineString) {
    coordinates = geometry.getCoordinates();
  } else if (geometry instanceof _geom.Circle) {
    coordinates = geometry.flatCoordinates;
    type = 'circle';
  }
  return {
    coordinates: coordinates,
    type: type
  };
};
var getTopRightCorner = function getTopRightCorner(coordinates, type) {
  var topRightCorner = [0, 0];
  if (type === 'circle') {
    topRightCorner = [coordinates === null || coordinates === void 0 ? void 0 : coordinates[0], coordinates === null || coordinates === void 0 ? void 0 : coordinates[1]];
  } else {
    for (var i = 0; i < coordinates.length; i++) {
      var coordinate = coordinates[i];
      if (coordinate[0] > topRightCorner[0] || coordinate[0] === topRightCorner[0] && coordinate[1] < topRightCorner[1]) {
        topRightCorner = coordinate;
      }
    }
  }
  return topRightCorner;
};
var CANCEL_TEXT_FEATURE_ID = 'cancelTextFeatureKey';
var _default = /*#__PURE__*/function () {
  function _default(options, callback) {
    var _this = this;
    _classCallCheck(this, _default);
    _defineProperty(this, "drawInit", function () {
      _this.map.removeInteraction(_this.drawTool);
      _this.addInteractions();
    });
    _defineProperty(this, "modifyInit", function () {
      var t = _this;
      var source = new _source.Vector();
      _this.modifySource = source;

      // 绘制完成的样式
      var _style = new _style2.Style({
        geometry: function geometry(feature) {
          var modifyGeometry = feature.get('modifyGeometry');
          return modifyGeometry ? modifyGeometry.geometry : feature.getGeometry();
        },
        fill: new _style2.Fill({
          color: 'rgba(0,128,255, 0.3)'
        }),
        stroke: new _style2.Stroke({
          color: 'rgba(0,128,255, 0.3)',
          width: 2
        })
      });
      var vector = new _layer.Vector({
        source: _this.modifySource,
        zIndex: 3,
        style: function style(feature) {
          var styles = [_style];
          var modifyGeometry = feature.get('modifyGeometry');
          var geometry = modifyGeometry ? modifyGeometry.geometry : feature.getGeometry();
          var topRightCorner = getTopRightCorner(geometry.getCoordinates()[0]);
          if (topRightCorner) {
            t.addCancelTextLayer(topRightCorner);
            var distance = feature.get('distance');
            t.distance = distance;
            var text = Number(distance) < 1 ? Number(distance * 1000).toFixed(0) + '米' : Number(distance).toFixed(2) + '公里';
            var drawFeature = t.source.getFeatures()[0].getGeometry();
            var _getCoordinateAndType = getCoordinateAndType(drawFeature),
              coordinates = _getCoordinateAndType.coordinates,
              type = _getCoordinateAndType.type;
            var topRightCorner_modify = getTopRightCorner(coordinates, type);
            // 待带修改的样式
            styles.push(new _style2.Style({
              geometry: new _geom.LineString([topRightCorner, topRightCorner_modify]),
              stroke: new _style2.Stroke({
                color: '#0084FF',
                width: 2
              })
            }));
            styles.push(new _style2.Style({
              geometry: new _geom.Point(topRightCorner),
              // 修改了点位的样式
              image: new _style2.Icon({
                src: require('../assets/kz.png')
              }),
              // image: new CircleStyle({
              //     radius: 6,
              //     fill: new Fill({
              //         color: '#0080FF',
              //     }),
              //     stroke: new Stroke({
              //         color: '#FFF',
              //         width: 2,
              //     }),
              // }),
              text: new _style2.Text({
                text: text,
                font: '12px Calibri,sans-serif',
                fill: new _style2.Fill({
                  color: '#FFF'
                }),
                backgroundFill: new _style2.Fill({
                  color: '#0080FF'
                }),
                backgroundStroke: new _style2.Stroke({
                  color: '#0080FF',
                  width: 1
                }),
                padding: [3, 2, 2, 4],
                justify: 'right',
                textBaseline: 'middle',
                offsetX: 40
              })
            }));
          }
          return styles;
        }
      });
      _this.modifyLayer = vector;
      _this.map.addLayer(vector);
      var defaultStyle = new _interaction.Modify({
        source: _this.modifySource
      }).getOverlay().getStyleFunction();
      var modify = new _interaction.Modify({
        source: _this.modifySource,
        maxDistance: _this.maxDistance,
        condition: function condition(event) {
          return (0, _condition.primaryAction)(event) && !(0, _condition.platformModifierKeyOnly)(event);
        },
        deleteCondition: _condition.never,
        insertVertexCondition: _condition.never,
        style: function style(feature) {
          feature.get('features').forEach(function (modifyFeature) {
            var modifyGeometry = modifyFeature.get('modifyGeometry');
            if (modifyGeometry) {
              var point = feature.getGeometry().getCoordinates();
              var geometry = t.source.getFeatures()[0].getGeometry();
              var _getCoordinateAndType2 = getCoordinateAndType(geometry),
                coordinates = _getCoordinateAndType2.coordinates,
                type = _getCoordinateAndType2.type;
              var topRightCorner = getTopRightCorner(coordinates, type);
              var from = (0, _turf.point)(point);
              var to = (0, _turf.point)(topRightCorner);
              var distance = (0, _turf.distance)(from, to, {
                units: 'kilometers'
              });

              // 限制拖动长度
              if (t.maxDistance && distance && distance * 1000 > t.maxDistance) {
                modifyFeature.setProperties({
                  distance: t.maxDistance / 1000
                });
                return defaultStyle(feature);
              }
              modifyFeature.setProperties({
                distance: distance
              });
              var bufferFeature = t.getBufferFeature(t.source.getFeatures()[0], distance);
              modifyGeometry.geometry = bufferFeature.getGeometry();
            }
          });
          return defaultStyle(feature);
        }
      });
      modify.on('modifystart', function (event) {
        event.features.forEach(function (feature) {
          feature.set('modifyGeometry', {
            geometry: feature.getGeometry().clone()
          }, true);
        });
      });
      modify.on('modifyend', function (event) {
        event.features.forEach(function (feature) {
          var modifyGeometry = feature.get('modifyGeometry');
          if (modifyGeometry) {
            feature.setGeometry(modifyGeometry.geometry);
            feature.unset('modifyGeometry', true);
            t.drawFeature = feature;
            var _feature = feature === null || feature === void 0 ? void 0 : feature.clone();
            t.callback(_feature, t.distance * 1000);
          }
          t.isFit && t.fitView(feature);
        });
      });
      _this.map.addInteraction(modify);
      _this.modifyTool = modify;
    });
    _defineProperty(this, "addInteractions", function () {
      var t = _this;
      var draw = new _interaction.Draw(_objectSpread({
        source: _this.source,
        type: _this.drawType
      }, _this.drawType === 'DragBox' ? {
        type: 'Circle',
        // 用于在绘制过程中创建或修改几何对象。这个函数允许开发者自定义绘制逻辑，以满足特定的需求。如果未提供此函数，则使用默认的几何创建逻辑
        geometryFunction: createBox()
      } : {}));
      draw.on('drawstart', function () {
        t.onClear();
      });
      draw.on('drawend', function (event) {
        var distance = 500 / 1000;
        var feature = t.getBufferFeature(event.feature, distance);
        feature.setProperties({
          distance: distance
        });
        t.modifySource.addFeature(feature);
        t.drawFeature = feature;
        var _feature = feature === null || feature === void 0 ? void 0 : feature.clone();
        t.callback(_feature, distance * 1000);
        t.isFit && t.fitView(feature);
      });
      _this.map.addInteraction(draw);
      _this.drawTool = draw;
    });
    _defineProperty(this, "getBufferFeature", function (feature, distance) {
      var coordinates = feature.getGeometry().getCoordinates();
      var g = feature.getGeometry();
      var geometry;
      if (g instanceof _geom.Point) {
        geometry = (0, _turf.point)(coordinates);
      } else if (g instanceof _geom.Polygon) {
        geometry = (0, _turf.polygon)(coordinates);
      } else if (g instanceof _geom.LineString) {
        geometry = (0, _turf.lineString)(coordinates);
      } else if (g instanceof _geom.Circle) {
        var center = g === null || g === void 0 ? void 0 : g.getCenter();
        var radius = g === null || g === void 0 ? void 0 : g.getRadius();
        _this.distance = radius;
        geometry = (0, _turf.circle)(center, radius);
      }
      var buffered = (0, _turf.buffer)(geometry, distance, {
        units: 'kilometers'
      });
      return format.readFeature(buffered);
    });
    _defineProperty(this, "fitView", function (feature) {
      _this.map.getView().fit(feature.getGeometry().getExtent(), {
        padding: [100, 400, 100, 400],
        maxZoom: 18,
        duration: 500
      });
    });
    _defineProperty(this, "onClear", function () {
      _this.source.clear();
      _this.modifySource.clear();
    });
    var _options$isFit = options.isFit,
      isFit = _options$isFit === void 0 ? true : _options$isFit;
    this.map = options.map;
    this.cancelTextLayer = null;
    this.drawTool = null;
    this.modifyTool = null;
    this.drawFeature = null;
    this.distance = 500;
    this.showCancel = options.showCancel;
    this.maxDistance = options.maxDistance;
    this.drawType = options.drawType;
    this.callback = callback;
    this.isFit = isFit;
    this.source = new _source.Vector();
    this.layer = new _layer.Vector({
      source: this.source,
      zIndex: 4,
      style: new _style2.Style({
        fill: new _style2.Fill({
          color: 'rgba(0,128,255, 0.7)'
        }),
        stroke: new _style2.Stroke({
          color: 'rgba(0,128,255, 0.7)',
          width: 2
        }),
        image: new _style2.Circle({
          radius: 6,
          fill: new _style2.Fill({
            // color: '#ffcc33',
            color: '#1890FF'
          }),
          stroke: new _style2.Stroke({
            color: '#FFF',
            width: 2
          })
        })
      })
    });
    this.map.addLayer(this.layer);
    this.modifySource = null;
    this.modifyLayer = null;
    this.modifyInit();
  }
  _createClass(_default, [{
    key: "removeCancelTextLayer",
    value: function removeCancelTextLayer() {
      if (this.cancelTextLayer) {
        this.map.removeLayer(this.cancelTextLayer);
        this.cancelTextLayer = null;
      }
    }
  }, {
    key: "addCancelTextLayer",
    value: function addCancelTextLayer(topRightCorner) {
      var _this2 = this;
      if (!this.showCancel) {
        return;
      }
      this.removeCancelTextLayer();

      // 创建文本 Feature
      var cancelTextFeature = new _ol.Feature({
        geometry: new _geom.Point(topRightCorner),
        name: '取消框选'
      });
      cancelTextFeature.setId(CANCEL_TEXT_FEATURE_ID);
      cancelTextFeature.onClick = function () {
        _this2.onClear();
        _this2.drawInit();
        _this2.removeCancelTextLayer();
      };
      var style = new _style2.Style({
        geometry: new _geom.Point(topRightCorner),
        text: new _style2.Text({
          text: '取消框选',
          font: '12px Calibri,sans-serif',
          fill: new _style2.Fill({
            color: '#0080FF'
          }),
          backgroundFill: new _style2.Fill({
            color: '#FFF'
          }),
          backgroundStroke: new _style2.Stroke({
            color: '#FFF',
            width: 1
          }),
          padding: [3, 2, 2, 4],
          justify: 'right',
          offsetX: 40,
          offsetY: 24
        })
      });
      cancelTextFeature.setStyle(style);
      this.cancelTextLayer = new _layer.Vector({
        source: new _source.Vector({
          features: [cancelTextFeature]
        })
      });
      this.map.addLayer(this.cancelTextLayer);
    }
  }, {
    key: "removeDrawTool",
    value: function removeDrawTool() {
      this.map.removeInteraction(this.drawTool);
      this.map.removeInteraction(this.modifyTool);
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this.map.removeLayer(this.layer);
      this.map.removeLayer(this.modifyLayer);
      this.removeCancelTextLayer();
      this.removeDrawTool();
      this.drawTool && this.drawTool.setActive(false);
      this.map.hideTip();
    }
  }]);
  return _default;
}();
exports["default"] = _default;
//# sourceMappingURL=BufferDraw.js.map
