"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CesiumHeatmap = void 0;
var _cesium = require("cesium");
var _heatmap = _interopRequireDefault(require("./heatmap.js"));
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 _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; }
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 _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 _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
function set(e, r, t, o) { return set = "undefined" != typeof Reflect && Reflect.set ? Reflect.set : function (e, r, t, o) { var f, i = _superPropBase(e, r); if (i) { if ((f = Object.getOwnPropertyDescriptor(i, r)).set) return f.set.call(o, t), !0; if (!f.writable) return !1; } if (f = Object.getOwnPropertyDescriptor(o, r)) { if (!f.writable) return !1; f.value = t, Object.defineProperty(o, r, f); } else _defineProperty(o, r, t); return !0; }, set(e, r, t, o); }
function _set(e, r, t, o, f) { if (!set(e, r, t, o || e) && f) throw new TypeError("failed to set property"); return t; }
function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
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 _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); }
//只能使用2.0.0版本，高版本热度图有出不来的情况，并且2.0.0 npm包有问题，只能通过修改使用这个js

var Max = function Max(arr) {
  var len = arr.length;
  var max = -Infinity;
  while (len--) {
    max = arr[len] > max ? arr[len] : max;
  }
  return max;
};
var Min = function Min(arr) {
  var len = arr.length;
  var min = Infinity;
  while (len--) {
    min = arr[len] < min ? arr[len] : min;
  }
  return min;
};

/**
 * 热度图
 */
var CesiumHeatmap = exports.CesiumHeatmap = /*#__PURE__*/function () {
  function CesiumHeatmap(viewer, options) {
    var _this$initOptions;
    _classCallCheck(this, CesiumHeatmap);
    _defineProperty(this, "viewer", void 0);
    _defineProperty(this, "element", void 0);
    _defineProperty(this, "initOptions", void 0);
    _defineProperty(this, "heatmapOptions", void 0);
    _defineProperty(this, "heatmapDataOptions", void 0);
    _defineProperty(this, "provider", void 0);
    _defineProperty(this, "heatmap", void 0);
    _defineProperty(this, "cameraMoveEnd", void 0);
    _defineProperty(this, "bounds", [0, 0, 0, 0]);
    _defineProperty(this, "lastCameraHeight", 0);
    this.viewer = viewer;
    var key = options.key,
      name = options.name,
      layerControl = options.layerControl,
      show = options.show,
      _options$initRadius = options.initRadius,
      initRadius = _options$initRadius === void 0 ? 10 : _options$initRadius;
    this.initOptions = _objectSpread({}, options);
    // 图层标识
    this.key = key;
    // this.initRadius = initRadius;

    // 图层名称
    this.name = name;
    this.layerControl = layerControl;
    _set(_getPrototypeOf(CesiumHeatmap.prototype), "show", show, this, true);
    if ((_this$initOptions = this.initOptions) !== null && _this$initOptions !== void 0 && (_this$initOptions = _this$initOptions.points) !== null && _this$initOptions !== void 0 && _this$initOptions.length) {
      var _this$initOptions2, _this$heatmapOptions;
      var bounds = this.getBounds(this.initOptions.points);
      this.bounds = bounds;
      var _this$createContainer = this.createContainer(bounds),
        container = _this$createContainer.container,
        width = _this$createContainer.width,
        height = _this$createContainer.height;
      this.element = container;
      var datas = [];
      var values = [];
      for (var i in this.initOptions.points) {
        var point = this.initOptions.points[i];
        var x = (point.x - bounds[0]) / (bounds[2] - bounds[0]) * width; //屏幕坐标x
        var y = (bounds[3] - point.y) / (bounds[3] - bounds[1]) * height; //屏幕坐标y
        var dataPoint = {
          x: x,
          y: y,
          value: point.value
        };
        if (typeof point.value === 'number') values.push(point.value);
        datas.push(dataPoint);
      }

      //数据的最大值和最小值
      var _min = values.length > 100000 ? Min(values) : Math.min.apply(Math, values);
      var _max = values.length > 100000 ? Max(values) : Math.max.apply(Math, values);
      if ((_this$initOptions2 = this.initOptions) !== null && _this$initOptions2 !== void 0 && _this$initOptions2.heatmapDataOptions) {
        var _this$initOptions$hea = this.initOptions.heatmapDataOptions,
          min = _this$initOptions$hea.min,
          max = _this$initOptions$hea.max;
        if (typeof min === 'number') {
          _min = min;
        }
        if (typeof max === 'number') {
          _max = max;
        }
      }
      this.heatmapDataOptions = {
        min: _min,
        max: _max
      };
      var data = {
        max: _max,
        min: _min,
        data: datas
      };
      var defaultOptions = {
        maxOpacity: 0.9,
        // radius: minRadius,
        // minimum opacity. any value > 0 will produce
        // no transparent gradient transition
        minOpacity: 0.1,
        gradient: {
          // enter n keys between 0 and 1 here
          // for gradient color customization
          '.3': 'blue',
          '.5': 'green',
          '.7': 'yellow',
          '.95': 'red'
        }
      };
      var _options = this.initOptions.heatmapOptions ? _objectSpread(_objectSpread({}, defaultOptions), this.initOptions.heatmapOptions) : defaultOptions;
      this.heatmapOptions = _objectSpread({}, _options);
      //初始化半径
      if ((_this$heatmapOptions = this.heatmapOptions) !== null && _this$heatmapOptions !== void 0 && _this$heatmapOptions.radius) {
        this.initRadius = this.heatmapOptions.radius || 10;
      }
      var optionsData = _objectSpread(_objectSpread({}, _options), {}, {
        container: container
      });
      if (options.initRadius) {
        optionsData.radius = options.initRadius;
      }
      this.heatmap = _heatmap["default"].create(optionsData);
      this.heatmap.setData(data);
      this.createLayer();
      if (!this.initOptions.noLisenerCamera) {
        this.addLisener();
      }
      if (this.initOptions.zoomToLayer && bounds) {
        this.viewer.camera.flyTo({
          destination: _cesium.Rectangle.fromDegrees.apply(_cesium.Rectangle, _toConsumableArray(bounds))
        });
      }
    }
  }

  // 重写父类的属性访问器
  return _createClass(CesiumHeatmap, [{
    key: "show",
    get: function get() {
      return _get(_getPrototypeOf(CesiumHeatmap.prototype), "show", this);
    },
    set: function set(value) {
      this.setVisible(value);
    }

    // 获取地图
  }, {
    key: "getMap",
    value: function getMap() {
      return this.viewer;
    }

    // 设置图层显示隐藏
  }, {
    key: "setVisible",
    value: function setVisible(visible) {
      _set(_getPrototypeOf(CesiumHeatmap.prototype), "show", visible, this, true);
      this.provider.show = visible; // 将属性传递给父类

      var map = this.getMap && this.getMap();
      if (map) {
        map.layers.emit('visible', this, visible);
      }
    }

    /**
     * 设置数据的最大最小值
     * @param dataOption
     */
  }, {
    key: "updateHeatMapMaxMin",
    value: function updateHeatMapMaxMin(dataOption) {
      var min = dataOption.min,
        max = dataOption.max;
      if (this.heatmap) {
        if (typeof min === 'number') {
          this.heatmap.setDataMin(min);
          if (this.heatmapDataOptions) this.heatmapDataOptions.min = min;
        }
        if (typeof max === 'number') {
          this.heatmap.setDataMax(max);
          if (this.heatmapDataOptions) this.heatmapDataOptions.max = max;
        }
      }
      this.updateLayer();
    }

    /**
     * 更新热度图配置
     * @param options
     */
  }, {
    key: "updateHeatmap",
    value: function updateHeatmap(options) {
      var heatmapOptions = this.heatmapOptions;
      this.heatmap.configure(_objectSpread(_objectSpread({}, heatmapOptions), options));
      this.updateLayer();
    }

    /**
     * 更新半径
     * @param radius
     */
  }, {
    key: "updateRadius",
    value: function updateRadius(radius) {
      var _this$initOptions3;
      var heatmapOptions = this.heatmapOptions;
      var currentData = this.heatmap.getData();
      if (currentData !== null && currentData !== void 0 && currentData.data) {
        for (var i in currentData.data) {
          var data = currentData.data[i];
          data.radius = radius;
        }
      }
      this.heatmap.setData(currentData);
      this.heatmapOptions = _objectSpread(_objectSpread({}, heatmapOptions), {
        radius: radius
      });
      this.updateLayer();
      if ((_this$initOptions3 = this.initOptions) !== null && _this$initOptions3 !== void 0 && _this$initOptions3.onRadiusChange) {
        this.initOptions.onRadiusChange(radius);
      }
    }

    /**
     * 移除
     */
  }, {
    key: "remove",
    value: function remove() {
      if (this.element) {
        document.body.removeChild(this.element);
        this.element = undefined;
        if (this.provider instanceof _cesium.ImageryLayer) {
          if (this.provider) this.viewer.imageryLayers.remove(this.provider);
          this.createSingleTileImageryLayer();
        } else if (this.provider instanceof _cesium.Primitive) {
          this.viewer.scene.primitives.remove(this.provider);
        } else if (this.provider instanceof _cesium.CustomDataSource) {
          this.viewer.dataSources.remove(this.provider);
        } else if (this.provider instanceof _cesium.Entity) {
          this.viewer.entities.remove(this.provider);
        }
        if (this.cameraMoveEnd) {
          this.viewer.camera.moveEnd.removeEventListener(this.cameraMoveEnd);
          this.cameraMoveEnd = undefined;
        }
      }
    }
  }, {
    key: "createLayer",
    value: function createLayer() {
      var _this = this;
      if (this.initOptions.renderType === 'primitive') {
        this.createPrimitive();
      } else if (this.initOptions.renderType === 'imagery') {
        this.createSingleTileImageryLayer();
      } else {
        this.createEntity();
      }
      this.provider.key = this.key;
      this.provider.name = this.name;
      this.provider.show = this.show;
      this.provider.setVisible = function (visible) {
        _this.setVisible(visible);
      };
    }
  }, {
    key: "createPrimitive",
    value: function createPrimitive() {
      var url = this.heatmap.getDataURL();
      this.provider = this.viewer.scene.primitives.add(new _cesium.Primitive({
        geometryInstances: new _cesium.GeometryInstance({
          geometry: new _cesium.RectangleGeometry({
            rectangle: _cesium.Rectangle.fromDegrees.apply(_cesium.Rectangle, _toConsumableArray(this.bounds)),
            vertexFormat: _cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
          })
        }),
        appearance: new _cesium.EllipsoidSurfaceAppearance({
          aboveGround: false
        }),
        show: this.show
      }));
      if (this.provider) {
        this.provider.appearance.material = new _cesium.Material({
          fabric: {
            type: 'Image',
            uniforms: {
              image: url
            }
          }
        });
      }
    }
  }, {
    key: "createSingleTileImageryLayer",
    value: function createSingleTileImageryLayer() {
      var url = this.heatmap.getDataURL();
      this.provider = this.viewer.imageryLayers.addImageryProvider(new _cesium.SingleTileImageryProvider({
        url: url,
        rectangle: _cesium.Rectangle.fromDegrees.apply(_cesium.Rectangle, _toConsumableArray(this.bounds))
      }));
    }
  }, {
    key: "getImageMaterialProperty",
    value: function getImageMaterialProperty() {
      var url = this.heatmap.getDataURL();
      var material = new _cesium.ImageMaterialProperty({
        image: url
      });
      return material;
    }
  }, {
    key: "createEntity",
    value: function createEntity() {
      this.provider = new _cesium.CustomDataSource(this.name);
      this.provider.entities.add({
        show: true,
        rectangle: {
          coordinates: _cesium.Rectangle.fromDegrees.apply(_cesium.Rectangle, _toConsumableArray(this.bounds)),
          material: this.getImageMaterialProperty()
        }
      });
      this.viewer.dataSources.add(this.provider);
    }
  }, {
    key: "updateLayer",
    value: function updateLayer() {
      var src = this.heatmap.getDataURL();
      if (this.provider instanceof _cesium.ImageryLayer) {
        if (this.provider) this.viewer.imageryLayers.remove(this.provider);
        this.createSingleTileImageryLayer();
      } else if (this.provider instanceof _cesium.Primitive) {
        this.provider.appearance.material.uniforms.image = src;
      } else if (this.provider instanceof _cesium.Entity) {
        if (this.provider.rectangle) this.provider.rectangle.material = this.getImageMaterialProperty();
      } else if (this.provider instanceof _cesium.CustomDataSource) {
        this.viewer.dataSources.remove(this.provider);
        this.createEntity();
      }
    }

    /**
     * 添加相机的监听
     */
  }, {
    key: "addLisener",
    value: function addLisener() {
      var _this2 = this;
      var maxRadius = 100;
      var min = 6375000;
      var max = 10000000;
      this.cameraMoveEnd = function () {
        if (_this2.heatmapOptions && _this2.heatmap && _this2.heatmapDataOptions) {
          var _this2$initOptions;
          var h = _this2.viewer.camera.getMagnitude();
          var distance = _this2 !== null && _this2 !== void 0 && (_this2$initOptions = _this2.initOptions) !== null && _this2$initOptions !== void 0 && _this2$initOptions.cameraHeightDistance ? _this2.initOptions.cameraHeightDistance : 1000;
          if (Math.abs(h - _this2.lastCameraHeight) > distance) {
            _this2.lastCameraHeight = h;
            if (typeof min === 'number' && typeof max === 'number') {
              var radius = parseInt((_this2.initRadius + (maxRadius - _this2.initRadius) * (h - min) / (max - min)).toFixed(0));
              if (radius) {
                _this2.updateRadius(radius);
              }
            }
          }
        }
      };
      this.viewer.camera.moveEnd.addEventListener(this.cameraMoveEnd);
    }

    /**
     *
     * @param points
     * @param expand
     * @returns
     */
  }, {
    key: "getBounds",
    value: function getBounds(points) {
      if (points) {
        var lonMin = 180;
        var lonMax = -180;
        var latMin = 90;
        var latMax = -180;
        points.forEach(function (point) {
          var longitude = point.x,
            latitude = point.y;
          lonMin = longitude < lonMin ? longitude : lonMin;
          latMin = latitude < latMin ? latitude : latMin;
          lonMax = longitude > lonMax ? longitude : lonMax;
          latMax = latitude > latMax ? latitude : latMax;
        });
        var xRange = lonMax - lonMin ? lonMax - lonMin : 1;
        var yRange = latMax - latMin ? latMax - latMin : 1;
        return [lonMin - xRange / 10, latMin - yRange / 10, lonMax + xRange / 10, latMax + yRange / 10];
      }
      return [0, 0, 0, 0];
    }
  }, {
    key: "createContainer",
    value: function createContainer(bounds) {
      var container = document.createElement('div');
      var width = 1000;
      var height = parseInt((1000 / (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])).toFixed(0));
      container.setAttribute('style', "width:".concat(width, "px;height:").concat(height, "px;display:none;"));
      document.body.appendChild(container);
      return {
        container: container,
        width: width,
        height: height
      };
    }
  }]);
}();
//# sourceMappingURL=CesiumHeatmap.js.map
