"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 _icons = require("@ant-design/icons");
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 _createFeatureCollection = require("../feature-layer/createFeatureCollection");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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 _Cesium = Cesium,
  ImageryLayerFeatureInfo = _Cesium.ImageryLayerFeatureInfo,
  Cartesian3 = _Cesium.Cartesian3,
  Cartographic = _Cesium.Cartographic,
  Math = _Cesium.Math;
;
var handelGeometry = function handelGeometry(entity) {
  var _entity$data, _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 !== 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)) {
    // 面
    // 注意：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 = Cartesian3.fromDegrees.apply(Cartesian3, _toConsumableArray(midpoint.geometry.coordinates));
  }
  return {
    position: position,
    geometryType: type,
    _offset: offset
  };
};
exports.handelGeometry = handelGeometry;
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)();
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      showTemplate: showTemplate,
      hideTemplate: hideTemplate
    };
  });
  var showTemplate = function showTemplate(feature, highlightLayer) {
    var _feature$_position, _feature$data;
    var layer = map.getLayerByFeature(feature);
    if (!(layer !== null && layer !== void 0 && layer.template)) {
      return;
    }
    var properties = map.getProperties(feature);
    feature.values_ = properties;
    featureRef.current = feature;
    if (layer) {
      var template = layer.template;
      var labelField = layer.labelField;
      setTitle(labelField && properties[labelField]);
      setContent(feature && template(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 = 5000;
    if (feature instanceof _Polygon["default"]) {
      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 = Cartographic.fromCartesian(v); // 经纬高对象
        var lng = Math.toDegrees(cartographic.longitude);
        var lat = Math.toDegrees(cartographic.latitude);
        return [lng, lat];
      })];
      var _handelGeometry = handelGeometry({
          data: {
            geometry: {
              type: 'Polygon',
              coordinates: coordinates
            }
          }
        }),
        _position = _handelGeometry.position,
        _offset = _handelGeometry._offset;
      position = _position;
      offset = _offset;
      height = null;
    } else if (feature instanceof _Polyline["default"]) {
      var _feature$_polyline;
      var _coordinates = ((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 = Cartographic.fromCartesian(v); // 经纬高对象
        var lng = Math.toDegrees(cartographic.longitude);
        var lat = Math.toDegrees(cartographic.latitude);
        return [lng, lat];
      });
      var _handelGeometry2 = handelGeometry({
          data: {
            geometry: {
              type: 'LineString',
              coordinates: _coordinates
            }
          }
        }),
        _position2 = _handelGeometry2.position,
        _offset2 = _handelGeometry2._offset;
      position = _position2;
      offset = _offset2;
      height = null;
    }
    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 = Cartesian3.fromDegrees.apply(Cartesian3, _toConsumableArray(midpoint.geometry.coordinates));
      }
    }

    // 影像图层的数据
    if (feature instanceof 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 _handelGeometry3 = handelGeometry(feature),
        _position3 = _handelGeometry3.position,
        _offset3 = _handelGeometry3._offset;
      position = _position3;
      offset = _offset3;
    }
    infoToolRef.current.add({
      position: position,
      content: '',
      element: popupRef.current,
      inputFeature: feature,
      type: '',
      offset: offset
    });
    map.popupRef = feature;
    if (!viewRef.current && map.autoView) {
      getView();
    }
    if (highlightLayer !== null && highlightLayer !== void 0 && highlightLayer.layer && map.autoView) {
      map.fitView({
        entity: highlightLayer.layer,
        height: height
      });
    }
  };
  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;
    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();
    if (map.entities.getById('highlight-1')) {
      map.entities.remove(map.entities.getById('highlight-1'));
    }

    // 清除高亮
    // highlightLayer.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));
});
var _default = Popup;
exports["default"] = _default;
//# sourceMappingURL=Popup.js.map
