"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getWMSFeatureInfoByLayers = exports.getWMSFeatureInfoByLayer = exports.getWFSFeatureInfoByLayers = exports.getWFSFeatureInfoByLayer = exports["default"] = void 0;
var _antd = require("antd");
var _layer = require("ol/layer");
var _source = require("ol/source");
var _format = require("ol/format");
var _geom = require("ol/geom");
var _Feature = _interopRequireDefault(require("ol/Feature"));
var _style2 = require("ol/style");
var _http = _interopRequireDefault(require("../_util/http"));
var _createFeatureCollection = require("../feature-layer/createFeatureCollection");
var _getUrlParam = _interopRequireDefault(require("../_util/getUrlParam"));
var _getSystemInfo = _interopRequireDefault(require("../_util/getSystemInfo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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 _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 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(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(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 geoJsonFormat = new _format.GeoJSON();

/**
 * 获取图形信息
 * @param layer
 * @returns {*}
 */
var getWFSFeatureInfoByLayer = exports.getWFSFeatureInfoByLayer = function getWFSFeatureInfoByLayer(layer, cql_filter, filterBefore, coorStr) {
  var _source$params_, _source$params_2;
  var source = layer === null || layer === void 0 ? void 0 : layer.getSource();
  var url = source === null || source === void 0 ? void 0 : source.url_;
  var filter = source === null || source === void 0 || (_source$params_ = source.params_) === null || _source$params_ === void 0 ? void 0 : _source$params_.cql_filter;
  var typeName = source === null || source === void 0 || (_source$params_2 = source.params_) === null || _source$params_2 === void 0 ? void 0 : _source$params_2.layers;
  var _cql_filter = cql_filter;
  if (coorStr !== null && coorStr !== void 0 && coorStr.coorStr) {
    var location = (layer === null || layer === void 0 ? void 0 : layer.location) || 'geo_location';
    _cql_filter = "INTERSECTS(".concat(location, ", POLYGON((").concat(coorStr === null || coorStr === void 0 ? void 0 : coorStr.coorStr, ")))");
  }
  if (!url) return;
  var CQL_FILTER;
  if (_cql_filter && filter) {
    CQL_FILTER = "(".concat(filter, ") and ").concat(_cql_filter);
  } else {
    CQL_FILTER = filter || _cql_filter || '';
  }
  if (filterBefore) {
    CQL_FILTER = filterBefore(CQL_FILTER, layer);
  }
  var params = {
    service: 'WFS',
    version: '1.0.0',
    request: 'GetFeature',
    maxFeatures: 99999,
    outputFormat: 'application/json',
    typeName: typeName,
    cql_filter: CQL_FILTER,
    viewparams: "tenantId:".concat((0, _getUrlParam["default"])('tenantId') || (0, _getSystemInfo["default"])('tenantId') || '')
  };
  return _http["default"].get(url, {
    body: _objectSpread({}, params)
  }).then(function (response) {
    var _response$features;
    var features = [];
    if (response !== null && response !== void 0 && (_response$features = response.features) !== null && _response$features !== void 0 && _response$features.length) {
      features = geoJsonFormat.readFeatures(response);
      features.map(function (item) {
        item.key = layer === null || layer === void 0 ? void 0 : layer.key;
        item.name = layer === null || layer === void 0 ? void 0 : layer.name;
        item.labelField = layer === null || layer === void 0 ? void 0 : layer.labelField;
        item.codeField = layer === null || layer === void 0 ? void 0 : layer.codeField;
        item.setProperties({
          key: layer === null || layer === void 0 ? void 0 : layer.key,
          label: (layer === null || layer === void 0 ? void 0 : layer.title) || (layer === null || layer === void 0 ? void 0 : layer.name),
          codeField: layer === null || layer === void 0 ? void 0 : layer.codeField
        });
      });
    }
    return features;
  })["catch"](function () {
    return [];
  });
};

/**
 * 获取图形信息
 * @param layers
 * @returns {Promise<FlatArray<Awaited<unknown>[], 2>[]>|*}
 */
var getWFSFeatureInfoByLayers = exports.getWFSFeatureInfoByLayers = function getWFSFeatureInfoByLayers(layers, cql_filter, filterBefore, coorStr) {
  if (Array.isArray(layers)) {
    var req = [];
    layers.map(function (v) {
      req.push(getWFSFeatureInfoByLayer(v, cql_filter, filterBefore, coorStr));
    });
    return Promise.all(req).then(function (layers) {
      return layers.flat(2);
    });
  } else {
    return getWFSFeatureInfoByLayer(layers, cql_filter, filterBefore, coorStr);
  }
};

/**
 * 获取图形信息
 * @param event
 * @param map
 * @param layer
 * @returns {*}
 */
var getWMSFeatureInfoByLayer = exports.getWMSFeatureInfoByLayer = function getWMSFeatureInfoByLayer(event, map, layer) {
  var source = layer.getSource();
  var view = map.getView();
  var url = source.getFeatureInfoUrl(event.coordinate, view.getResolution(), view.getProjection(), {
    cql_filter: source.params_.cql_filter,
    QUERY_LAYERS: source.params_.layers,
    INFO_FORMAT: 'application/json',
    FEATURE_COUNT: 50
  });
  return _http["default"].get(url).then(function (data) {
    var _data$features;
    var features = [];
    if (data !== null && data !== void 0 && (_data$features = data.features) !== null && _data$features !== void 0 && _data$features.length) {
      features = geoJsonFormat.readFeatures(data);
      features.map(function (item) {
        item.key = layer === null || layer === void 0 ? void 0 : layer.key;
      });
    }
    return features;
  })["catch"](function () {
    return [];
  });
};

/**
 * 获取图形信息
 * @param event
 * @param map
 * @param layers
 * @returns {Promise<FlatArray<Awaited<unknown>[], 2>[]>|*}
 */
var getWMSFeatureInfoByLayers = exports.getWMSFeatureInfoByLayers = function getWMSFeatureInfoByLayers(event, map, layers) {
  if (Array.isArray(layers)) {
    var req = [];
    layers.map(function (v) {
      req.push(getWMSFeatureInfoByLayer(event, map, v));
    });
    return Promise.all(req).then(function (layers) {
      return layers.flat(2);
    });
  } else {
    return getWMSFeatureInfoByLayer(event, map, layers);
  }
};
var _default = exports["default"] = /*#__PURE__*/function () {
  function _default(props) {
    _classCallCheck(this, _default);
    var _props$fit = props.fit,
      fit = _props$fit === void 0 ? true : _props$fit,
      _props$otherParams = props.otherParams,
      otherParams = _props$otherParams === void 0 ? {} : _props$otherParams;
    this.highStyle = new _style2.Style({
      // 高亮样式
      image: new _style2.Circle({
        radius: 7,
        fill: new _style2.Fill({
          color: '#ff4d4f'
        }),
        stroke: new _style2.Stroke({
          color: '#FFFFFF',
          width: 2
        })
      }),
      fill: new _style2.Fill({
        color: '#ff4d4f'
      }),
      stroke: new _style2.Stroke({
        color: '#ff4d4f',
        width: 4
      })
    });
    this.map = props.map;
    this.field = props.field;
    this.fit = fit;
    this.cql_filter = props.cql_filter || props.filter;
    this.source = new _source.Vector();
    this.key = props.key;
    this.layer = new _layer.Vector(_objectSpread({
      source: this.source,
      zIndex: 9999,
      style: this.highStyle
    }, otherParams));
    this.map.addLayer(this.layer);
    this.url = props.url || '/geoserver/zhsw/wms';
    this.layerName = props.layerName || 'zhsw:putian_line';
    this.params = _objectSpread({
      service: 'WFS',
      version: '1.0.0',
      request: 'GetFeature',
      typeName: 'mumu:points',
      maxFeatures: 99999,
      outputFormat: 'application/json'
    }, props.params);
    this.selectFeature = null;
  }
  return _createClass(_default, [{
    key: "filter",
    set: function set(val) {
      this.clearSelectFeature();
      this.clearFeatures();
      if (val) {
        if (_typeof(val) === 'object' && val.isGetUrl) {
          // 接口获取图层
          this.setUrlLayerData(val);
        } else {
          var cqlFilter = val;
          if (this.cql_filter) {
            cqlFilter = "".concat(this.cql_filter, " and ").concat(val);
          }
          this.setLayerData({
            cql_filter: cqlFilter
          });
        }
      }
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this.map.removeLayer(this.layer);
    }
  }, {
    key: "clearFeatures",
    value: function clearFeatures() {
      this.source && this.source.clear();
    }
  }, {
    key: "setUrlLayerData",
    value: function setUrlLayerData(val) {
      var _this = this;
      this.getUrlData(val).then(function (features) {
        if (features && features.length) {
          var view = _this.map.getView();
          _this.source.addFeatures(features);
          if (view) {
            view.fit(_this.source.getExtent(), {
              maxZoom: 20,
              duration: 500
            });
          }
        }
      });
    }
  }, {
    key: "getUrlData",
    value: function getUrlData(req) {
      var _this2 = this;
      // codes 符合条件的数据变量集合，
      var _ref = req || {},
        url = _ref.url,
        params = _ref.params,
        _data = _ref.data,
        _ref$codes = _ref.codes,
        codes = _ref$codes === void 0 ? [] : _ref$codes,
        _ref$fileValue = _ref.fileValue,
        fileValue = _ref$fileValue === void 0 ? 'code' : _ref$fileValue,
        _ref$type = _ref.type,
        type = _ref$type === void 0 ? 'point' : _ref$type;
      var request = _http["default"].get;
      var data = params;
      if (req.method === 'POST') {
        request = _http["default"].post;
        data = _data;
      }
      return request(url, {
        body: _objectSpread({}, data)
      }).then(function (res) {
        var features = [];
        if (String(res === null || res === void 0 ? void 0 : res.result) && res !== null && res !== void 0 && res.data) {
          if (type === 'point') {
            res.data.map(function (item) {
              var geometryInfo = item.geometryInfo;
              var _ref2 = geometryInfo || {},
                _ref2$lngLats = _ref2.lngLats,
                lngLats = _ref2$lngLats === void 0 ? '' : _ref2$lngLats;
              var lngLat = [];
              if (lngLats) {
                lngLat = lngLats.split(',');
              }
              if (lngLat[0] && lngLat[1] && codes.includes(item[fileValue])) {
                features.push(new _Feature["default"]({
                  geometry: new _geom.Point([Number(lngLat[0]), Number(lngLat[1])]),
                  properties: _objectSpread({}, item),
                  type: type
                }));
              }
            });
          }
        }
        features.map(function (v) {
          v.key = _this2.key;
        });
        return features;
      })["catch"](function () {
        return [];
      });
    }
  }, {
    key: "loadData",
    value: function loadData(data) {
      this.clearFeatures();
      var res = (0, _createFeatureCollection.createFeatureCollection)(Array.isArray(data) ? data : [data]);
      var features = geoJsonFormat.readFeatures(res);
      this.source.addFeatures(features);
    }
  }, {
    key: "setLayerData",
    value: function setLayerData(params) {
      var _this3 = this;
      this.clearSelectFeature();
      this.clearFeatures();
      var val = _objectSpread({
        service: 'WFS',
        version: '1.0.0',
        request: 'GetFeature',
        maxFeatures: 99999,
        outputFormat: 'application/json',
        typeName: this.layerName,
        layers: this.layerName,
        QUERY_LAYERS: this.layerName,
        cql_filter: this.cql_filter
      }, params);
      return this.getLayerData(this.url || val.url, val).then(function (features) {
        if (features !== null && features !== void 0 && features.length) {
          _this3.source.addFeatures(features);
          if (_this3.fit) {
            _this3.map.getView().fit(_this3.source.getExtent(), {
              maxZoom: 20,
              duration: 500
            });
          }
        }
        return features;
      });
    }
  }, {
    key: "getLayerData",
    value: function getLayerData(url, params) {
      var _this4 = this;
      return _http["default"].get(url, {
        body: params
      }).then(function (response) {
        var _response$features2;
        var features;
        if (response !== null && response !== void 0 && (_response$features2 = response.features) !== null && _response$features2 !== void 0 && _response$features2.length) {
          var _features;
          var _geoJsonFormat = new _format.GeoJSON();
          features = _geoJsonFormat.readFeatures(response);
          (_features = features) === null || _features === void 0 || _features.map(function (v) {
            v.key = _this4.key;
          });
        }
        return features;
      });
    }
  }, {
    key: "setCenterByCode",
    value: function setCenterByCode(code, style, field) {
      this.clearSelectFeature();
      var features = this.source.getFeatures();

      // 查询字段
      var fieldCode = field || this.field || 'code';
      var feature = features.find(function (v) {
        var _v$get;
        return (v.get(fieldCode) || ((_v$get = v.get('properties')) === null || _v$get === void 0 ? void 0 : _v$get[fieldCode])) === code;
      });
      if (feature) {
        feature.setStyle();
        this.map.getView().fit(feature.values_.geometry.getExtent(), {
          maxZoom: 18,
          duration: 500
        });
        this.setSelectFeature(feature, style);
      } else {
        _antd.message.warning('地图上未查询到该数据，请检查是否配置坐标信息！');
      }
    }
  }, {
    key: "clearSelectFeature",
    value: function clearSelectFeature() {
      if (this.selectFeature) {
        this.selectFeature.setStyle();
        this.selectFeature = null;
      }
    }
  }, {
    key: "setSelectFeature",
    value: function setSelectFeature(feature, style) {
      if (feature) {
        var styleArr = [new _style2.Style({
          image: new _style2.Circle({
            radius: 7,
            fill: new _style2.Fill({
              color: '#2491fc'
            }),
            stroke: new _style2.Stroke({
              color: '#FFFFFF',
              width: 2
            })
          }),
          fill: new _style2.Fill({
            color: '#2491fc'
          }),
          stroke: new _style2.Stroke({
            color: '#2491fc',
            width: 4
          })
        })];
        if (typeof style === 'function') {
          var _style = style(feature);
          if (Array.isArray(_style) && _style !== null && _style !== void 0 && _style.length) styleArr.push.apply(styleArr, _toConsumableArray(_style));
        }
        this.selectFeature = feature;
        this.selectFeature.setStyle(styleArr);
      }
    }
  }]);
}();
//# sourceMappingURL=index.js.map
