"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 _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
var _ol = require("ol");
var _layer2 = require("ol/layer");
var _classnames = _interopRequireDefault(require("classnames"));
var _layerControl = require("../tools/layer-control");
var _popup = _interopRequireDefault(require("../popup"));
require("./style");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), 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 _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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var ClusterTitle = function ClusterTitle(props) {
  var layer = props.layer;
  var name = layer.name;
  var imgUrl = (0, _layerControl.getImgUrl)(layer);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-map-popup-cluster-title')
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: imgUrl,
    alt: "",
    className: (0, _classnames["default"])('ol-map-popup-cluster-title-img')
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])('ol-map-popup-cluster-title-text')
  }, name));
};
var Cluster = function Cluster(props) {
  var layer = props.layer,
    features = props.features,
    onFeatureClick = props.onFeatureClick,
    onFitView = props.onFitView;
  var labelField = layer.labelField;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-map-popup-cluster')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-map-popup-cluster-header')
  }, "\u5171 ", features.length, " \u4E2A\u70B9\u4F4D", /*#__PURE__*/_react["default"].createElement("a", {
    onClick: onFitView
  }, "\u7F29\u653E\u81F3")), /*#__PURE__*/_react["default"].createElement(_antd.Table, {
    pagination: false,
    size: "small",
    dataSource: features,
    scroll: {
      y: 120
    },
    columns: [{
      title: '名称',
      dataIndex: '名称',
      width: 60,
      render: function render(text, record) {
        return /*#__PURE__*/_react["default"].createElement("a", {
          onClick: function onClick() {
            return onFeatureClick(record);
          }
        }, record.values_[labelField]);
      }
    }, {
      title: '操作',
      dataIndex: '操作',
      width: 30,
      render: function render(text, record) {
        return /*#__PURE__*/_react["default"].createElement("a", {
          onClick: function onClick() {
            return onFeatureClick(record);
          }
        }, "\u5B9A\u4F4D");
      }
    }]
  }));
};
var FeatureTable = function FeatureTable(props) {
  var tableData = props.tableData,
    onFeatureClick = props.onFeatureClick,
    onFitView = props.onFitView;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-map-popup-cluster')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-map-popup-cluster-header'),
    style: {
      padding: '10px 0'
    }
  }, "\u5171 ", tableData.length, " \u4E2A\u70B9\u4F4D", /*#__PURE__*/_react["default"].createElement("a", {
    onClick: onFitView
  }, "\u7F29\u653E\u81F3")), /*#__PURE__*/_react["default"].createElement(_antd.Table, {
    pagination: false,
    size: "small",
    dataSource: tableData,
    scroll: {
      y: 120
    },
    columns: [{
      title: '图层',
      dataIndex: 'layerName',
      width: 40,
      render: function render(text, record) {
        return record.layer.name;
      }
    }, {
      title: '名称',
      dataIndex: 'name',
      width: 60,
      render: function render(text, record) {
        var _record$layer;
        return /*#__PURE__*/_react["default"].createElement("a", {
          onClick: function onClick() {
            return onFeatureClick(record);
          }
        }, record.feature.values_[(record === null || record === void 0 || (_record$layer = record.layer) === null || _record$layer === void 0 ? void 0 : _record$layer.labelField) || 'name'] || '-');
      }
    }]
  }));
};
var MapPopup = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useState = (0, _react.useState)(null),
    _useState2 = _slicedToArray(_useState, 2),
    content = _useState2[0],
    setContent = _useState2[1];
  var _useState3 = (0, _react.useState)(null),
    _useState4 = _slicedToArray(_useState3, 2),
    title = _useState4[0],
    setTitle = _useState4[1];
  var overlayRef = (0, _react.useRef)();
  var popupRef = (0, _react.useRef)();
  var featureRef = (0, _react.useRef)();
  var viewRef = (0, _react.useRef)({});
  var map = props.map;
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      showTemplate: showTemplate,
      hideTemplate: hideTemplate,
      setLastView: setLastView
    };
  });
  (0, _react.useEffect)(function () {
    var overlay = new _ol.Overlay({
      element: popupRef.current.wrapDom,
      autoPan: {
        animation: {
          duration: 250
        }
      },
      stopEvent: true,
      positioning: 'bottom-center',
      offset: [10, -45]
    });
    overlayRef.current = overlay;
    map.addOverlay(overlay);
    return function () {
      map.removeOverlay(overlay);
    };
  }, []);
  var showTemplate = function showTemplate(feature, options) {
    var _ref = options || {},
      fitViewOptions = _ref.fitViewOptions;
    if (Array.isArray(feature) && feature.length >= 2 && !map.hidePopupTable) {
      showTemplateByFeatures(feature, options);
      return;
    }
    feature = Array.isArray(feature) ? feature[0] : feature;
    featureRef.current = feature;
    if (!feature) {
      hideTemplate();
      return;
    }
    var layer = map.getLayerByFeature(feature);
    map.featureRef = feature;

    // 判断是否为聚合点击
    var features = feature.get('features');
    if (features && features.length >= 2) {
      showTemplateByCluster(feature, layer, features);
      return;
    }

    // 记录放大前的视角
    if (map.autoView) {
      getView();
    }
    map.highlightLayer.addHighlightFeature(feature, _objectSpread({
      autoView: map.autoView
    }, fitViewOptions));
    if (!(layer !== null && layer !== void 0 && layer.template)) {
      return;
    }
    if (layer) {
      var template = layer.template;
      var labelField = layer.labelField;
      if (labelField) {
        setTitle(feature.values_[labelField]);
      }
      if (template) {
        setContent(template(feature));
        var offset = layer instanceof _layer2.Image ? [10, -10] : [10, -45];
        var geometry = feature.getGeometry();
        if (geometry) {
          var type = geometry.getType();
          var coordinate = geometry.getCoordinates();
          if (['MultiLineString', 'LineString'].includes(type)) {
            if (geometry.getFlatMidpoints) {
              coordinate = geometry.getFlatMidpoints();
            } else if (geometry.getFlatMidpoint) {
              coordinate = geometry.getFlatMidpoint();
            }
            offset = [7, 0];
          } else if (['MultiPolygon', 'Polygon'].includes(type)) {
            if (geometry.getFlatInteriorPoints) {
              coordinate = geometry.getFlatInteriorPoints();
            } else if (geometry.getFlatInteriorPoint) {
              coordinate = geometry.getFlatInteriorPoint();
            }
            offset = [10, 0];
          }
          overlayRef.current.setPosition(coordinate);
          overlayRef.current.values_.offset = offset;
        }
      }
    }
  };

  // 聚合点位展示
  var showTemplateByCluster = function showTemplateByCluster(feature, layer, features) {
    var _feature$getGeometry, _layer$_options;
    var coordinate = feature === null || feature === void 0 || (_feature$getGeometry = feature.getGeometry()) === null || _feature$getGeometry === void 0 ? void 0 : _feature$getGeometry.getCoordinates();
    overlayRef.current.setPosition(coordinate);
    setTitle( /*#__PURE__*/_react["default"].createElement(ClusterTitle, {
      layer: layer
    }));

    // 判断是否有自定义聚合列表模版
    var Template = (layer === null || layer === void 0 || (_layer$_options = layer._options) === null || _layer$_options === void 0 || (_layer$_options = _layer$_options.cluster) === null || _layer$_options === void 0 ? void 0 : _layer$_options.template) || Cluster;
    setContent( /*#__PURE__*/_react["default"].createElement(Template, {
      layer: layer,
      features: features,
      onFitView: function onFitView() {
        map.fitView(features);
        hideTemplate();
      },
      onFeatureClick: function onFeatureClick(f) {
        map.fitView(f);
        showTemplate(f);
      }
    }));
  };

  // 多个点位展示
  var showTemplateByFeatures = function showTemplateByFeatures(features) {
    overlayRef.current.setPosition(map._clickObject.coordinate);
    overlayRef.current.values_.offset = [10, -10];
    setTitle(null);
    var tableData = [];
    features.map(function (feature) {
      var layer = map.getLayerByFeature(feature);
      // 判断是否为聚合点击
      var clusterFeature = feature.get('features');
      if (clusterFeature && clusterFeature.length >= 2) {
        clusterFeature.map(function (f) {
          tableData.push({
            layer: layer,
            feature: f
          });
        });
      } else {
        var _layer = map.getLayerByFeature(feature);
        tableData.push({
          layer: _layer,
          feature: feature
        });
      }
    });
    setContent( /*#__PURE__*/_react["default"].createElement(FeatureTable, {
      tableData: tableData,
      onFitView: function onFitView() {
        map.fitView(features);
        hideTemplate();
      },
      onFeatureClick: function onFeatureClick(record) {
        var feature = record.feature;
        var layer = map.getLayerByFeature(feature);
        var properties = feature.getProperties();
        layer === null || layer === void 0 || layer.onClick(properties, map._clickObject);
        if (layer !== null && layer !== void 0 && layer.template) {
          map.fitView(feature);
          showTemplate(feature);
        }
      }
    }));
  };

  // 恢复上一次视角
  var setLastView = function setLastView() {
    // 恢复打开前的视角
    if (map.autoView && map.closePopupAutoView && viewRef.current) {
      var _viewRef$current = viewRef.current,
        zoom = _viewRef$current.zoom,
        center = _viewRef$current.center;
      map.getView().animate({
        zoom: zoom,
        center: center
      });
    }
  };
  var hideTemplate = function hideTemplate() {
    overlayRef.current.setPosition(undefined);
    map.highlightLayer.clearFeatures();
    setContent(null);
    setTitle(null);
    featureRef.current = null;
    map.featureRef = null;
  };
  var getView = function getView() {
    var view = map.getView();
    var zoom = view.getZoom();
    var viewParams;
    if (zoom < 15) {
      viewParams = {
        extent: view.calculateExtent(map.getSize()),
        zoom: view.getZoom(),
        center: view.getCenter()
      };
    }
    viewRef.current = viewParams;
  };
  var onClose = function onClose() {
    // 回调事件
    map.onCloseTemplateBefore && map.onCloseTemplateBefore(featureRef.current);

    // 隐藏气泡
    hideTemplate();

    // 恢复打开前的视角
    setLastView();
  };
  return /*#__PURE__*/_react["default"].createElement(_popup["default"], {
    ref: popupRef,
    title: title,
    onClose: onClose
  }, content);
});
var _default = exports["default"] = MapPopup;
//# sourceMappingURL=Popup.js.map
