"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _cesium = require("cesium");
var _createFeatureCollection = require("./createFeatureCollection");
var _Label = _interopRequireDefault(require("../label/Label"));
var _Marker = _interopRequireDefault(require("../marker/Marker"));
var _Polyline = _interopRequireDefault(require("../polyline/Polyline"));
var _Polygon = _interopRequireDefault(require("../polygon/Polygon"));
var _renderer = require("../renderer");
var _isObject = _interopRequireDefault(require("../_util/isObject"));
var _isFunction = _interopRequireDefault(require("../_util/isFunction"));
var _layer = require("../_util/layer");
var _encryptParams = _interopRequireDefault(require("../_util/encryptParams"));
var _excluded = ["icon", "type"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": 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], t.indexOf(o) >= 0 || {}.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 (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }
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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
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 _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
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 _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); }
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); }
var P = {
  Label: _Label["default"],
  Point: _Marker["default"],
  Marker: _Marker["default"],
  Polyline: _Polyline["default"],
  Polygon: _Polygon["default"],
  LineString: _Polyline["default"],
  MultiLineString: _Polyline["default"]
};
var createFeature = function createFeature(v) {
  var _v$geometry = v.geometry,
    type = _v$geometry.type,
    coordinates = _v$geometry.coordinates;
  if (P[type]) {
    return new P[type]({
      geometry: coordinates,
      properties: v
    });
  }
};
var FeatureLayer = /*#__PURE__*/function (_CustomDataSource) {
  function FeatureLayer(opt_options) {
    var _this2;
    _classCallCheck(this, FeatureLayer);
    var options = opt_options || {};
    var url = options.url,
      params = options.params,
      data = options.data,
      key = options.key,
      name = options.name,
      labelField = options.labelField,
      template = options.template,
      autoRefresh = options.autoRefresh,
      method = options.method,
      renderMode = options.renderMode,
      style = options.style,
      markerStyle = options.markerStyle,
      _options$show = options.show,
      show = _options$show === void 0 ? true : _options$show,
      _options$layerControl = options.layerControl,
      layerControl = _options$layerControl === void 0 ? true : _options$layerControl,
      afterGetData = options.afterGetData,
      viewOnly = options.viewOnly,
      legend = options.legend,
      group = options.group,
      map = options.map,
      cluster = options.cluster,
      zIndex = options.zIndex,
      cancelPopup = options.cancelPopup,
      encrypt = options.encrypt,
      tipTemplate = options.tipTemplate;
    var defaultShow = show;
    if (group !== null && group !== void 0 && group.length) {
      defaultShow = false;
      if (!show) {
        group.map(function (f) {
          f.show = false;
        });
      } else {
        group.map(function (f) {
          var _f$show;
          f.show = (_f$show = f.show) !== null && _f$show !== void 0 ? _f$show : true;
          if (f.show) {
            defaultShow = true;
          }
        });
      }
    }
    _this2 = _callSuper(this, FeatureLayer, [options]);
    _set((_this2, _getPrototypeOf(FeatureLayer.prototype)), "show", show, _this2, true);

    // 接口地址
    _this2.url = url;

    // 接口地址请求类型
    _this2.method = method;

    // 接口查询参数
    _this2.params = params;

    // 图层标识
    _this2.key = key;

    // 图层名称
    _this2.name = name;

    // 渲染
    _this2.style = style;

    //marker样式
    _this2.markerStyle = markerStyle;

    // 标签字段
    _this2.labelField = labelField;

    // 自动刷新标识
    _this2.autoRefresh = autoRefresh;

    // 模版内容
    _this2.template = template;

    // 渲染模式
    _this2.renderMode = renderMode || 'marker';

    // 图例
    _this2.legend = legend;

    // 过滤
    _this2.group = group;

    // 地图
    _this2.map = map;

    // 图层控制
    _this2.layerControl = layerControl;

    // 聚合
    _this2.cluster = cluster;

    // 层级
    _this2.zIndex = zIndex;

    // 数据
    _this2.data = data;

    // 处理获取的数据
    _this2.afterGetData = afterGetData;

    // 是否初始化
    _this2.inited = false;

    // 取消气泡
    _this2.cancelPopup = cancelPopup;

    // 加密
    _this2.encrypt = encrypt;

    // 气泡模板
    _this2.tipTemplate = tipTemplate;

    // 仅展示
    _this2.viewOnly = viewOnly;

    // 默认是否展示
    if (defaultShow) {
      _this2.init();
    }
    return _this2;
  }

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

    // 初始化数据
  }, {
    key: "init",
    value: function init() {
      // 是否存在地址
      if (this.url) {
        // 执行
        this.loadUrlData(this.url, this.params, this.method);
      }

      // 直接加载数据
      if (this.data) {
        // 执行
        this.loadData(this.data);
      }
      this.inited = true;
    }

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

    // 根据条件获取图形数据
  }, {
    key: "getFeatureByFieldValue",
    value: function getFeatureByFieldValue(field, value) {
      return this.getFeatures().find(function (v) {
        var _v$properties;
        return String(v === null || v === void 0 || (_v$properties = v.properties) === null || _v$properties === void 0 || (_v$properties = _v$properties[field]) === null || _v$properties === void 0 ? void 0 : _v$properties._value) === String(value);
      });
    }

    // 获取当前图层的所有图形
  }, {
    key: "getFeatures",
    value: function getFeatures() {
      return this.entities.values;
    }

    // 根据条件获取图形数据，用于地图搜索
  }, {
    key: "getFeaturesBySearch",
    value: function getFeaturesBySearch(field, value) {
      return (0, _layer.getVectorFeatureInfoByText)(this, field, value);
    }

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

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

      // 判断是否完成过初始化，没有的话就加载一波数据
      if (!this.inited) {
        this.init();
      }
    }

    // 设置过滤条件
  }, {
    key: "setGroup",
    value: function setGroup(group) {
      var map = this.getMap && this.getMap();
      if (group !== null && group !== void 0 && group.length) {
        var features = this.getFeatures();
        if (features !== null && features !== void 0 && features.length) {
          features.map(function (feature) {
            var show = false;
            group.map(function (v) {
              if (!v.hasOwnProperty('show') || v.show) {
                var properties = map.getProperties(feature);
                if (v.filter(properties)) {
                  show = true;
                }
              }
            });
            feature.show = show;
          });
        }
        this.group = group;
        this.setVisibleByGroup();
      }
    }

    // 根据过滤条件组显示图层
  }, {
    key: "setVisibleByGroup",
    value: function setVisibleByGroup() {
      var group = this.group;
      if (group !== null && group !== void 0 && group.length) {
        var visible = false;
        group.map(function (v) {
          if (!v.hasOwnProperty('show') || v.show) {
            visible = true;
          }
        });
        this.setVisible(visible);
      }
    }

    // 设置渲染模式
  }, {
    key: "setRenderMode",
    value: function setRenderMode(renderMode) {
      this.hideClustering();

      // 展示聚合时设置样式为 marker 并且开启聚合监听
      if (renderMode === 'clustering') {
        this.renderMode = 'marker';
        this.setStyle();
        this.showClustering();
      } else {
        this.renderMode = renderMode;
        this.setStyle();
      }
    }

    // 自动刷新
  }, {
    key: "refresh",
    value: function refresh() {
      var params = this.params;
      if (this.encrypt) {
        params = (0, _encryptParams["default"])(params, this.encrypt);
      }
      (0, _createFeatureCollection.getDataByHttp)(this.url, params, this.method).then(function (res) {
        var _res$features;
        if (res !== null && res !== void 0 && (_res$features = res.features) !== null && _res$features !== void 0 && _res$features.length) {}
      });
    }

    // 加载数据
  }, {
    key: "loadData",
    value: function loadData(data) {
      this.entities.removeAll();
      var geoJsonData = (0, _createFeatureCollection.createFeatureCollection)(Array.isArray(data) ? data : [data]);
      this.render(geoJsonData);
    }

    // 加载接口数据
  }, {
    key: "loadUrlData",
    value: function loadUrlData(url, params, method) {
      var _this3 = this;
      var afterGetData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : this.afterGetData;
      this.entities.removeAll();
      if (this.encrypt) {
        params = (0, _encryptParams["default"])(params, this.encrypt);
      }
      (0, _createFeatureCollection.getDataByHttp)(url, params, method, afterGetData).then(function (res) {
        var _res$features2;
        if (res !== null && res !== void 0 && (_res$features2 = res.features) !== null && _res$features2 !== void 0 && _res$features2.length) {
          _this3.render(res);
        }
      });
    }

    // 加载图形数据
  }, {
    key: "loadFeatures",
    value: function loadFeatures(features) {
      this.entities.removeAll();
      this.entities.addFeatures(features);
    }

    // 渲染
  }, {
    key: "render",
    value: function render(geoJsonData) {
      this.geoJsonData = geoJsonData;
      if (geoJsonData) {
        if (this.renderMode === 'marker') {
          this.setStyle();
        } else {
          this.setRenderMode(this.renderMode);
        }
      }
    }

    // 设置样式
  }, {
    key: "setStyle",
    value: function setStyle() {
      var _this4 = this;
      if (this.renderMode === 'point') {
        this.entities.values.map(function (entity) {
          (0, _renderer.setRenderer)(entity, {
            type: 'Marker',
            style: _objectSpread({
              type: 'PointIcon',
              size: 15
            }, (0, _isObject["default"])(_this4.markerStyle) ? _this4.markerStyle : {})
          });
        });
      } else if (this.renderMode === 'marker') {
        this.entities.removeAll();
        var _ref = this.geoJsonData || {},
          features = _ref.features;
        var group = this.group;
        if (features !== null && features !== void 0 && features.length) {
          features.map(function (v) {
            var entity = createFeature(v);
            if (entity) {
              var _this4$group;
              var show = true;
              var style = _this4.style;

              // 针对过滤时的处理
              if ((_this4$group = _this4.group) !== null && _this4$group !== void 0 && _this4$group.length) {
                show = false;
                group.map(function (f) {
                  if (f.filter(v.properties)) {
                    style = f.style;
                    if (!f.hasOwnProperty('show') || f.show) {
                      show = true;
                    }
                  }
                });
              }
              (0, _renderer.setRenderer)(entity, style);
              if (style) {
                var _style = style;
                if ((0, _isFunction["default"])(style)) {
                  _style = (0, _isFunction["default"])(style);
                }
                if (_style.type === 'Marker' && _style.style) {
                  var _style$style = _style.style,
                    image = _style$style.image,
                    imageType = _style$style.imageType,
                    imageKey = _style$style.imageKey;
                  if (image && imageType) {
                    if (imageType === 'gif') {
                      entity.setGifImage(image, imageKey);
                    }
                  }
                }
              }
              entity.show = show;
              entity.type = _this4.modalType || _this4.key;
              entity.key = _this4.key;
              entity.properties = v.properties || {};
              _this4.entities.add(entity);
            }
          });
        }
      }
    }

    // 展示聚合
  }, {
    key: "showClustering",
    value: function showClustering() {
      var _this$cluster,
        _this$cluster2,
        _this5 = this;
      // 是否聚合
      this.customStyle();

      // 聚合点的判定范围(像素单位)
      this.clustering.pixelRange = ((_this$cluster = this.cluster) === null || _this$cluster === void 0 ? void 0 : _this$cluster.pixelRange) || 100;

      // 最小簇大小
      this.clustering.minimumClusterSize = ((_this$cluster2 = this.cluster) === null || _this$cluster2 === void 0 ? void 0 : _this$cluster2.minimumClusterSize) || 2;

      // 默认关闭，延时开启，避免一开始不生效
      this.clustering.enabled = false;
      setTimeout(function () {
        var _this5$cluster;
        // 解决一开始不聚合的问题
        _this5.clustering.pixelRange = 0;
        _this5.clustering.pixelRange = ((_this5$cluster = _this5.cluster) === null || _this5$cluster === void 0 ? void 0 : _this5$cluster.pixelRange) || 100;
        _this5.clustering.enabled = true;
      }, 50);

      // 高度监听
      this.heightListerHeight();
    }
  }, {
    key: "heightListerHeight",
    value: function heightListerHeight() {
      if ((0, _cesium.defined)(this.removeListenerHeight) && this.removeListenerHeight) {
        this.removeListenerHeight();
        this.removeListenerHeight = undefined;
      }
      var viewer = this.map;
      var _this = this;
      // 监听scene的postRender事件
      this.removeListenerHeight = viewer.scene.postRender.addEventListener(function () {
        // 获取当前的相机高度
        var currentCameraHeight = viewer.camera.positionCartographic.height;
        _this.clustering.enabled = true;
        if (_this.cluster && _this.cluster.height) {
          var height = _this.cluster.height;
          if (currentCameraHeight <= height) {
            _this.clustering.enabled = false;
          }
        } else if (currentCameraHeight <= (viewer.fitViewHeight || 5000) + 1000) {
          // 当高度小于阈值时禁用聚合
          _this.clustering.enabled = false;
        }
      });
    }

    // 隐藏聚合
  }, {
    key: "hideClustering",
    value: function hideClustering() {
      this.clustering.enabled = false;
      if ((0, _cesium.defined)(this.removeListener) && this.removeListener) {
        this.removeListener();
        this.removeListener = undefined;
      }
      if ((0, _cesium.defined)(this.removeListenerHeight) && this.removeListenerHeight) {
        this.removeListenerHeight();
        this.removeListenerHeight = undefined;
      }
    }

    // 自定义样式
  }, {
    key: "customStyle",
    value: function customStyle() {
      var _this = this;
      if ((0, _cesium.defined)(this.removeListener) && this.removeListener) {
        this.removeListener();
        this.removeListener = undefined;
      }
      this.removeListener = this.clustering.clusterEvent.addEventListener(function (clusteredEntities, cluster) {
        cluster.label.show = false;
        cluster.billboard.show = true;
        cluster.billboard.id = cluster.label.id;
        cluster.billboard.verticalOrigin = _cesium.VerticalOrigin.BOTTOM;
        cluster.billboard.heightReference = _cesium.HeightReference.CLAMP_TO_GROUND;
        cluster.billboard.horizontalOrigin = _cesium.HorizontalOrigin.CENTER;
        var text = clusteredEntities.length;
        if (_this.cluster) {
          var style = _this.cluster.style;
          var image,
            scale = 1;
          if ((0, _isFunction["default"])(style)) {
            image = style(clusteredEntities);
          } else if ((0, _isObject["default"])(style)) {
            var icon = style.icon,
              type = style.type,
              otherStyle = _objectWithoutProperties(style, _excluded);
            image = (0, _renderer.getImgUrl)(type || 'CommonIcon2', _objectSpread({
              canvasIcon: icon,
              color: 'rgb(0,128,255)',
              hideFooter: true,
              info: [{
                text: text,
                fontSize: 24
              }]
            }, otherStyle));
            scale = style === null || style === void 0 ? void 0 : style.scale;
          } else if (typeof style === 'string') {
            image = (0, _renderer.getImgUrl)('CommonIcon2', {
              canvasIcon: style,
              color: 'rgb(0,128,255)',
              hideFooter: true,
              info: [{
                text: text,
                fontSize: 24
              }]
            });
          }
          cluster.billboard.image = image;
          cluster.billboard.scale = scale || 1;
        } else if ((0, _isObject["default"])(_this.style) || typeof _this.style === 'string') {
          var _icon = _this.style,
            _type = 'CommonIcon2';
          if ((0, _isObject["default"])(_this.style) && _this.style.type === 'Marker') {
            _icon = _this.style.style.icon || _icon;
            _type = _this.style.style.type || _type;
          }
          var color = 'rgb(9,220,107)';
          if (clusteredEntities.length >= 50) {
            text = '50+';
            color = 'rgb(220,33,9)';
          } else if (clusteredEntities.length >= 40) {
            text = '40+';
            color = 'rgb(232,119,5)';
          } else if (clusteredEntities.length >= 30) {
            text = '30+';
            color = 'rgb(232,194,4)';
          } else if (clusteredEntities.length >= 20) {
            text = '20+';
            color = 'rgba(20, 232, 4, 1)';
          } else if (clusteredEntities.length >= 10) {
            text = '10+';
            color = 'rgb(0,128,255)';
          }
          cluster.billboard.image = (0, _renderer.getImgUrl)(_type, {
            canvasIcon: _icon,
            color: color,
            hideFooter: true,
            info: [{
              text: text,
              fontSize: 24
            }]
          });
        }
      });
    }

    // 根据条件展示对应的视角
  }, {
    key: "fitViewByFilter",
    value: function fitViewByFilter(filter) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var _ref2 = this.geoJsonData || {},
        features = _ref2.features;
      if (features !== null && features !== void 0 && features.length) {
        var geoJsonData = JSON.parse(JSON.stringify(this.geoJsonData));
        if (filter) {
          geoJsonData.features = features.filter(function (v) {
            return filter(v.properties);
          });
        }
        this.map.fitView({
          geoJson: geoJsonData,
          options: _objectSpread({
            padding: [3000, 3000]
          }, options)
        });
      }
    }
  }]);
}(_cesium.CustomDataSource);
var _default = exports["default"] = FeatureLayer;
//# sourceMappingURL=FeatureLayer.js.map
