"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.handelGeometry = exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _cesium = require("cesium");
var _icons = require("@ant-design/icons");
var _antd = require("antd");
var _InfoTool = _interopRequireDefault(require("./InfoTool"));
var _classnames = _interopRequireDefault(require("classnames"));
var _turf = require("@turf/turf");
var _Polygon = _interopRequireDefault(require("../polygon/Polygon"));
var _Polyline = _interopRequireDefault(require("../polyline/Polyline"));
var _layerControl = require("../tools/layer-control");
var _createFeatureCollection = require("../feature-layer/createFeatureCollection");
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 _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 _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; }
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; }
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"])('cs-map-popup-cluster-title')
  }, /*#__PURE__*/_react["default"].createElement("img", {
    src: imgUrl,
    alt: "",
    className: (0, _classnames["default"])('cs-map-popup-cluster-title-img')
  }), /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])('cs-map-popup-cluster-title-text')
  }, name));
};
ClusterTitle.propTypes = {
  layer: _propTypes["default"].object
};
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"])('cs-map-popup-cluster')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('cs-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");
      }
    }]
  }));
};
Cluster.propTypes = {
  layer: _propTypes["default"].object,
  features: _propTypes["default"].array,
  onFeatureClick: _propTypes["default"].func,
  onFitView: _propTypes["default"].func
};
var handelGeometry = exports.handelGeometry = function handelGeometry(entity) {
  var _entity$data, _coordinates, _midpoint;
  var geometry = entity === null || entity === void 0 || (_entity$data = entity.data) === null || _entity$data === void 0 ? void 0 : _entity$data.geometry;
  var type = geometry === null || geometry === void 0 ? void 0 : geometry.type;
  var coordinates = geometry === null || geometry === void 0 ? void 0 : geometry.coordinates;
  var midpoint = entity === null || entity === void 0 ? void 0 : entity.data; // 默认点
  var position = null;
  var offset = {
    x: 0,
    y: 20
  };
  if (['MultiLineString', 'LineString'].includes(type) && (_coordinates = coordinates) !== null && _coordinates !== void 0 && _coordinates.length) {
    var point1 = null;
    var point2 = null;
    // 线
    if (coordinates.length > 1) {
      point1 = (0, _turf.point)(coordinates[0]);
      point2 = (0, _turf.point)(coordinates[1]);
    } else {
      var lngLatArr = coordinates[0];
      point1 = (0, _turf.point)(lngLatArr[0]);
      point2 = (0, _turf.point)(lngLatArr[1]);
    }
    midpoint = (0, _turf.midpoint)(point1, point2);
  } else if (['Polygon', 'MultiPolygon'].includes(type)) {
    var _coordinates2;
    // 兼容polygon首尾坐标不一致情况
    coordinates = (_coordinates2 = coordinates) === null || _coordinates2 === void 0 ? void 0 : _coordinates2.map(function (item) {
      if (item[0][0] !== item[item.length - 1][0] || item[0][1] !== item[item.length - 1][1]) {
        return [].concat(_toConsumableArray(item), [item[0]]);
      }
      return item;
    });
    // 面
    // 注意：polygon首尾坐标要一致
    var polygon = (0, _turf.polygon)(coordinates);
    midpoint = (0, _turf.centerOfMass)(polygon);
  } else if (['Point'].includes(type)) {
    offset = {
      x: 5,
      y: 20
    };
  }
  if ((_midpoint = midpoint) !== null && _midpoint !== void 0 && (_midpoint = _midpoint.geometry) !== null && _midpoint !== void 0 && _midpoint.coordinates) {
    position = _cesium.Cartesian3.fromDegrees.apply(_cesium.Cartesian3, _toConsumableArray(midpoint.geometry.coordinates));
  }
  return {
    position: position,
    geometryType: type,
    _offset: offset
  };
};
var Popup = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var map = props.map;
  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 popupRef = (0, _react.useRef)();
  var featureRef = (0, _react.useRef)();
  var infoToolRef = (0, _react.useRef)(new _InfoTool["default"]({
    map: map
  }));
  var viewRef = (0, _react.useRef)();
  var highlightLayerRef = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      showTemplate: showTemplate,
      hideTemplate: hideTemplate
    };
  });
  var showTemplate = function showTemplate(feature, highlightLayer) {
    var _feature$_position, _feature$data, _highlightLayer2;
    // 判断是否为聚合点击
    if (feature && feature.length >= 2) {
      var _layer2$_options;
      var points = [];
      var features = feature.map(function (f) {
        var properties = map.getProperties(f);
        points.push((0, _turf.point)(f.geometry));
        return {
          feature: f,
          geometryInfo: (properties === null || properties === void 0 ? void 0 : properties.geometryInfo) || {
            type: 'point',
            lngLats: f.geometry.join(','),
            coordType: 'wgs84'
          },
          values_: properties,
          properties: properties
        };
      });
      var center = (0, _turf.centerOfMass)((0, _turf.featureCollection)(points));
      var _handelGeometry = handelGeometry({
          data: center
        }),
        _position2 = _handelGeometry.position;
      var _layer2 = map.getLayerByFeature(feature[0]);
      infoToolRef.current.add({
        position: _position2,
        content: '',
        element: popupRef.current,
        inputFeature: feature,
        type: '',
        offset: {
          x: 0,
          y: 50
        }
      });
      setTitle( /*#__PURE__*/_react["default"].createElement(ClusterTitle, {
        layer: _layer2
      }));

      // 判断是否有自定义聚合列表模版
      var Template = (_layer2 === null || _layer2 === void 0 || (_layer2$_options = _layer2._options) === null || _layer2$_options === void 0 || (_layer2$_options = _layer2$_options.cluster) === null || _layer2$_options === void 0 ? void 0 : _layer2$_options.template) || Cluster;
      setContent( /*#__PURE__*/_react["default"].createElement(Template, {
        layer: _layer2,
        features: features,
        onFitView: function onFitView() {
          map.fitView({
            data: features
          });
          hideTemplate(null, map.autoView);
        },
        onFeatureClick: function onFeatureClick(f) {
          showTemplate(f.feature, highlightLayer);
        }
      }));
      return;
    }
    var layer = map.getLayerByFeature(feature);
    if (layer !== null && layer !== void 0 && layer.cancelPopup || feature !== null && feature !== void 0 && feature.cancelPopup) {
      return;
    }
    map.layers.highlightFeature = feature;
    var properties = map.getProperties(feature);
    feature.values_ = properties;
    featureRef.current = feature;
    var position = feature === null || feature === void 0 || (_feature$_position = feature._position) === null || _feature$_position === void 0 ? void 0 : _feature$_position._value;
    // 偏移量
    var offset = {
      x: 5,
      y: 76
    };
    var height = map.fitViewHeight || 5000;
    if (feature instanceof _Polygon["default"] || feature !== null && feature !== void 0 && feature._polygon) {
      var _feature$_polygon;
      var coordinates = [((feature === null || feature === void 0 || (_feature$_polygon = feature._polygon) === null || _feature$_polygon === void 0 || (_feature$_polygon = _feature$_polygon._hierarchy) === null || _feature$_polygon === void 0 || (_feature$_polygon = _feature$_polygon._value) === null || _feature$_polygon === void 0 ? void 0 : _feature$_polygon.positions) || []).map(function (v) {
        var cartographic = _cesium.Cartographic.fromCartesian(v); // 经纬高对象
        var lng = _cesium.Math.toDegrees(cartographic.longitude);
        var lat = _cesium.Math.toDegrees(cartographic.latitude);
        return [lng, lat];
      })];
      var _handelGeometry2 = handelGeometry({
          data: {
            geometry: {
              type: 'Polygon',
              coordinates: coordinates
            }
          }
        }),
        _position = _handelGeometry2.position,
        _offset = _handelGeometry2._offset;
      position = _position;
      offset = _offset;
      height = null;
    } else if (feature instanceof _Polyline["default"] || feature !== null && feature !== void 0 && feature._polyline) {
      var _feature$_polyline;
      var _coordinates3 = ((feature === null || feature === void 0 || (_feature$_polyline = feature._polyline) === null || _feature$_polyline === void 0 || (_feature$_polyline = _feature$_polyline._positions) === null || _feature$_polyline === void 0 ? void 0 : _feature$_polyline._value) || []).map(function (v) {
        var cartographic = _cesium.Cartographic.fromCartesian(v); // 经纬高对象
        var lng = _cesium.Math.toDegrees(cartographic.longitude);
        var lat = _cesium.Math.toDegrees(cartographic.latitude);
        return [lng, lat];
      });
      var _handelGeometry3 = handelGeometry({
          data: {
            geometry: {
              type: 'LineString',
              coordinates: _coordinates3
            }
          }
        }),
        _position3 = _handelGeometry3.position,
        _offset2 = _handelGeometry3._offset;
      position = _position3;
      offset = _offset2;
      height = null;
    }
    if (feature instanceof _cesium.Cesium3DTileFeature) {
      offset = {
        x: 0,
        y: 20
      };
      position = map._clickObject.position;
      // position = Cartesian3.fromDegrees();
    } else if (feature.primitive) {
      var _midpoint$geometry;
      offset = {
        x: 0,
        y: 20
      };
      var geometry = (0, _createFeatureCollection.transformGeometry)(properties.geometryInfo);
      var _geometry$coordinates = _slicedToArray(geometry.coordinates[0], 2),
        point1 = _geometry$coordinates[0],
        point2 = _geometry$coordinates[1];
      var midpoint = (0, _turf.midpoint)(point1, point2);
      if (midpoint !== null && midpoint !== void 0 && (_midpoint$geometry = midpoint.geometry) !== null && _midpoint$geometry !== void 0 && _midpoint$geometry.coordinates) {
        position = _cesium.Cartesian3.fromDegrees.apply(_cesium.Cartesian3, _toConsumableArray(midpoint.geometry.coordinates));
      }
    }

    // 影像图层的数据
    if (feature instanceof _cesium.ImageryLayerFeatureInfo || feature !== null && feature !== void 0 && (_feature$data = feature.data) !== null && _feature$data !== void 0 && (_feature$data = _feature$data.geometry) !== null && _feature$data !== void 0 && _feature$data.coordinates) {
      var _handelGeometry4 = handelGeometry(feature),
        _position4 = _handelGeometry4.position,
        _offset3 = _handelGeometry4._offset;
      position = _position4;
      offset = _offset3;
    }
    if (layer !== null && layer !== void 0 && layer.template) {
      var template = layer.template;
      var labelField = layer.labelField;
      setTitle(labelField && properties[labelField]);
      setContent(feature && template(feature));
      infoToolRef.current.add({
        position: position,
        content: '',
        element: popupRef.current,
        inputFeature: feature,
        type: '',
        offset: offset
      });
      map.popupRef = feature;
    }
    var currentCameraHeight = map.camera.positionCartographic.height;
    var viewThreshold = currentCameraHeight < height;
    var viewHeight = viewThreshold ? currentCameraHeight : height;
    if (!viewRef.current && map.autoView) {
      getView();
    }
    if (viewThreshold) {
      viewRef.current = null;
    }
    highlightLayer = highlightLayer || map.highlightLayer;
    highlightLayerRef.current = highlightLayer;
    highlightLayer.addHighlightFeature(feature);
    if ((_highlightLayer2 = highlightLayer) !== null && _highlightLayer2 !== void 0 && _highlightLayer2.layer && map.autoView && !viewThreshold) {
      map.fitView({
        entity: highlightLayer.layer,
        height: viewHeight
      });
    }
  };
  var hideTemplate = function hideTemplate(_layer) {
    if (_layer) {
      var layer = typeof _layer === 'string' ? map.getLayerByKey(_layer) : _layer;
      if (layer && layer.key && map.popupRef) {
        var _highlightLayer = map.getLayerByFeature(map.popupRef);
        if (_highlightLayer.key === layer.key) {
          onClose();
        }
      }
    } else {
      onClose();
    }
  };

  // 判断点位异常-点位异常展示红色
  function judgeAbnormal() {
    var _ref = map.getProperties(featureRef.current) || {},
      status = _ref.status;
    return status && [1, 2, 4].includes(status);
  }

  // 关闭气泡
  var onClose = function onClose() {
    var _infoToolRef$current, _highlightLayerRef$cu, _highlightLayerRef$cu2;
    map.onCloseTemplateBefore && map.onCloseTemplateBefore(featureRef.current);
    map.popupRef = null;
    featureRef.current = null;
    infoToolRef === null || infoToolRef === void 0 || (_infoToolRef$current = infoToolRef.current) === null || _infoToolRef$current === void 0 || _infoToolRef$current.remove();
    map.layers.highlightFeature = null;
    if (map.entities.getById('highlight-1')) {
      map.entities.remove(map.entities.getById('highlight-1'));
    }

    // 清除高亮
    (_highlightLayerRef$cu = highlightLayerRef.current) === null || _highlightLayerRef$cu === void 0 || (_highlightLayerRef$cu2 = _highlightLayerRef$cu.clearHighlight) === null || _highlightLayerRef$cu2 === void 0 || _highlightLayerRef$cu2.call(_highlightLayerRef$cu);
    // highlightLayerRef.current.clearFeatures();

    // map.fitView();

    if (map.autoView) {
      setView();
    }
  };
  var getView = function getView() {
    //获取当前视角的pitch
    var pitch = map.camera.pitch;
    //获取当前视角的heading
    var heading = map.camera.heading;
    //获取当前视角的postion（位置）
    var position = map.camera.position;
    viewRef.current = {
      x: position.x,
      y: position.y,
      z: position.z,
      pitch: pitch,
      heading: heading
    };
  };
  var setView = function setView() {
    if (viewRef.current) {
      map.camera.flyTo({
        //定位到范围中心点
        destination: {
          x: viewRef.current.x,
          y: viewRef.current.y,
          z: viewRef.current.z
        },
        orientation: {
          heading: viewRef.current.heading,
          //左右方向
          pitch: viewRef.current.pitch,
          //上下方向
          roll: 0.0
        },
        duration: 2
      });
      viewRef.current = null;
    }
  };
  return /*#__PURE__*/_react["default"].createElement("div", {
    ref: popupRef,
    className: (0, _classnames["default"])('cesium-popup', {
      'cesium-popup-abnormal': judgeAbnormal()
    })
  }, /*#__PURE__*/_react["default"].createElement(_icons.CloseOutlined, {
    className: (0, _classnames["default"])('cesium-popup-close'),
    width: 16,
    height: 16,
    onClick: onClose
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('cesium-popup-title', {
      'cesium-popup-no-title': !title
    })
  }, title), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('cesium-popup-content'),
    id: "content"
  }, content));
});
Popup.propTypes = {
  map: _propTypes["default"].object,
  feature: _propTypes["default"].object,
  layer: _propTypes["default"].object,
  highlightLayer: _propTypes["default"].object,
  onClose: _propTypes["default"].func
};
var _default = exports["default"] = Popup;
//# sourceMappingURL=Popup.js.map
