"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 _propTypes = _interopRequireDefault(require("prop-types"));
var _HighlightLayer = _interopRequireDefault(require("../highlight-layer/HighlightLayer"));
var _base = require("./base");
require("./material");
var _getDefaultMapInfo2 = _interopRequireDefault(require("../_util/getDefaultMapInfo"));
require("cesium/Build/Cesium/Widgets/widgets.css");
var _classnames = _interopRequireDefault(require("classnames"));
var _events = require("../events");
var _Popup = _interopRequireDefault(require("./Popup"));
var _Provider = _interopRequireDefault(require("../_util/Provider"));
var _Layers = _interopRequireDefault(require("./Layers"));
var _EventEmitter = _interopRequireDefault(require("../_util/EventEmitter"));
var _useGetMapFeatureInfoByText = _interopRequireDefault(require("./hooks/useGetMapFeatureInfoByText"));
var _lodash = _interopRequireDefault(require("lodash"));
var _createFeatureCollection = require("../feature-layer/createFeatureCollection");
var _getBBoxFromGeojson = _interopRequireDefault(require("../_util/getBBoxFromGeojson.js"));
var _excluded = ["center", "dark", "zoom", "createdMap"],
  _excluded2 = ["geoJson", "geometryInfo", "data", "entity", "lng", "lat", "height"];
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 _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
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 _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 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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 _Cesium = Cesium,
  Viewer = _Cesium.Viewer,
  SceneMode = _Cesium.SceneMode,
  Cartesian3 = _Cesium.Cartesian3,
  Math = _Cesium.Math,
  Ion = _Cesium.Ion,
  WebMapTileServiceImageryProvider = _Cesium.WebMapTileServiceImageryProvider,
  defined = _Cesium.defined,
  when = _Cesium.when,
  ScreenSpaceEventHandler = _Cesium.ScreenSpaceEventHandler,
  ScreenSpaceEventType = _Cesium.ScreenSpaceEventType,
  ImageryLayerFeatureInfo = _Cesium.ImageryLayerFeatureInfo,
  Primitive = _Cesium.Primitive,
  Cartesian2 = _Cesium.Cartesian2,
  Ellipsoid = _Cesium.Ellipsoid,
  Cartographic = _Cesium.Cartographic,
  Rectangle = _Cesium.Rectangle;
function Map(props) {
  var _props$width = props.width,
    width = _props$width === void 0 ? '100%' : _props$width,
    _props$height = props.height,
    height = _props$height === void 0 ? '100%' : _props$height,
    _props$dark = props.dark,
    dark = _props$dark === void 0 ? true : _props$dark,
    _props$mapStyle = props.mapStyle,
    mapStyle = _props$mapStyle === void 0 ? 'vec' : _props$mapStyle,
    tk = props.tk,
    children = props.children,
    onCloseTemplateBefore = props.onCloseTemplateBefore,
    onZoom = props.onZoom,
    _props$defaultPitch = props.defaultPitch,
    defaultPitch = _props$defaultPitch === void 0 ? -88.0 : _props$defaultPitch,
    _props$onEvents = props.onEvents,
    onEvents = _props$onEvents === void 0 ? {} : _props$onEvents,
    baseMapUrl = props.baseMapUrl,
    _props$duration = props.duration,
    duration = _props$duration === void 0 ? 3 : _props$duration,
    _props$baseMapStyle = props.baseMapStyle,
    baseMapStyle = _props$baseMapStyle === void 0 ? {
      imageryProvider: 'GeoQImageryProvider',
      style: 'Blue'
    } : _props$baseMapStyle,
    _props$autoView = props.autoView,
    autoView = _props$autoView === void 0 ? true : _props$autoView;
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    mapLoaded = _useState2[0],
    setMapLoaded = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    tipVis = _useState4[0],
    setTipVis = _useState4[1];
  var _useState5 = (0, _react.useState)(null),
    _useState6 = _slicedToArray(_useState5, 2),
    tip = _useState6[0],
    setTip = _useState6[1];
  var mapRef = (0, _react.useRef)(null);
  var mapDomRef = (0, _react.useRef)(null);
  var tipRef = (0, _react.useRef)(null);
  var popupRef = (0, _react.useRef)();
  var highlightLayer = (0, _react.useRef)();
  var getMapFeatureInfoByText = (0, _useGetMapFeatureInfoByText["default"])(mapRef);
  (0, _react.useEffect)(function () {
    initMap();
  }, []);
  (0, _react.useEffect)(function () {
    if (mapRef !== null && mapRef !== void 0 && mapRef.current) {
      highlightLayer.current = new _HighlightLayer["default"]({
        map: mapRef.current
      });
      mapRef.current.highlightLayer = highlightLayer.current;
      return function () {
        highlightLayer.current.destroy();
        mapRef.current.highlightLayer = null;
      };
    }
  }, []);
  var addImageryProvider = function addImageryProvider() {
    var TDT_CIA_W = "https://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=".concat(tk);
    var cia = new WebMapTileServiceImageryProvider({
      // 调用影响中文注记服务
      url: TDT_CIA_W,
      layer: 'cia_w',
      style: 'default',
      format: 'tiles',
      tileMatrixSetID: 'GoogleMapsCompatible',
      subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
      // 天地图8个服务器
      minimumLevel: 0,
      maximumLevel: 18
    });
    mapRef.current.imageryLayers.addImageryProvider(cia); // 添加到cesium图层上
  };

  (0, _react.useEffect)(function () {
    if (baseMapStyle.imageryProvider === 'TdtImageryProvider') {
      addImageryProvider();
    } else {
      if (mapRef.current) {
        var layers = mapRef.current.imageryLayers._layers || [];
        var ciaLayer = layers.find(function (item) {
          var _item$_imageryProvide;
          return ((_item$_imageryProvide = item._imageryProvider) === null || _item$_imageryProvide === void 0 ? void 0 : _item$_imageryProvide._layer) === 'cia_w';
        });
        if (ciaLayer) {
          mapRef.current.imageryLayers.remove(ciaLayer);
        }
      }
    }
  }, [baseMapStyle.imageryProvider]);
  var initMap = function initMap() {
    var center = props.center,
      dark = props.dark,
      zoom = props.zoom,
      createdMap = props.createdMap,
      options = _objectWithoutProperties(props, _excluded);
    var _getDefaultMapInfo = (0, _getDefaultMapInfo2["default"])(),
      minZoom = _getDefaultMapInfo.minZoom,
      maxZoom = _getDefaultMapInfo.maxZoom,
      defaultZoomLevel = _getDefaultMapInfo.defaultZoomLevel,
      longitude = _getDefaultMapInfo.longitude,
      latitude = _getDefaultMapInfo.latitude;

    // 全屏
    var viewDefault = {
      center: center || longitude && latitude && [longitude, latitude] || [120.081627, 30.89638],
      zoom: zoom || defaultZoomLevel && Number(defaultZoomLevel) || 0,
      minZoom: minZoom && Number(minZoom) || 0,
      maxZoom: maxZoom && Number(maxZoom) || 20
    };
    Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjc0ZDQ1ZS0wNWNhLTRhMDQtODJmYy03NTcyNDcxYzgzMDUiLCJpZCI6NzE4MTQsImlhdCI6MTYzNTQ3NzgyNX0.4TrdZWPWc9_6jLeGe90bRmBPB14XptwinSewVMu1iCE';
    var imageryProvider = new _base.Imagery[baseMapStyle.imageryProvider]({
      style: baseMapStyle.style,
      url: baseMapUrl,
      crs: 'WGS84'
    });
    var map = new Viewer(mapDomRef.current, _objectSpread({
      shouldAnimate: true,
      animation: false,
      // 控制场景动画的播放速度控件
      baseLayerPicker: false,
      // 底图切换控件
      fullscreenButton: false,
      // 全屏控件
      geocoder: false,
      // 地理位置查询定位控件
      homeButton: false,
      // 默认相机位置控件
      timeline: false,
      // 时间滚动条控件
      infoBox: false,
      //是否显示信息框
      sceneModePicker: false,
      //是否显示3D/2D选择器
      selectionIndicator: false,
      // 点击点绿色弹出 是否显示选取指示器组件
      sceneMode: SceneMode.SCENE3D,
      //设定3维地图的默认场景模式: SceneMode.SCENE2D、SceneMode.SCENE3D、SceneMode.MORPHING
      navigationHelpButton: false,
      // 默认的相机控制提示控件
      scene3DOnly: true,
      // 每个几何实例仅以3D渲染以节省GPU内存
      navigationInstructionsInitiallyVisible: false,
      showRenderLoopErrors: true,
      //是否显示渲染错误
      orderIndependentTranslucency: false,
      //设置背景透明
      imageryProvider: imageryProvider
    }, options));
    map.autoView = autoView; // 自动调整视角

    // 事件订阅
    map.eventEmitter = new _EventEmitter["default"]();

    // 去版权信息
    map._cesiumWidget._creditContainer.style.display = 'none'; // 隐藏cesium ion

    mapRef.current = map;
    map.dark = dark;
    // 底图服务
    map.baseMap = new _base.BaseMap({
      map: map,
      imageryProvider: baseMapStyle.imageryProvider,
      style: baseMapStyle.style,
      layer: imageryProvider
    });

    // 添加 dataSource 和 imagery 图层
    map.layers = new _Layers["default"]({
      map: map
    });

    // 图层改变的时候
    map.layers.on('change', function (layers) {
      onEvents.layersChange && onEvents.layersChange(layers);
      map.eventEmitter.emit('layersChange', layers);
    });

    // 图层新增
    map.layers.on('add', function (layer) {
      onEvents.layersAdd && onEvents.layersAdd(layer);
      map.eventEmitter.emit('layersAdd', layer);
    });

    // 图层移除
    map.layers.on('remove', function (layer) {
      onEvents.layersRemove && onEvents.layersRemove(layer);
      map.eventEmitter.emit('layersRemove', layer);
    });

    // 图层清空
    map.layers.on('clear', function () {
      onEvents.layersClear && onEvents.layersClear();
      map.eventEmitter.emit('layersClear');
    });

    // 图层展示隐藏
    map.layers.on('visible', function (layer, visible) {
      map.layers.onChange(); // 触发图层改变

      // 图层关闭时，隐藏自身的气泡
      if (!visible && map.popupRef) {
        map.hideTemplate(layer);
      }
      onEvents.layersVisible && onEvents.layersVisible(layer, visible);
      map.eventEmitter.emit('layersVisible');
    });

    // 图层变化
    map.layersChange = function () {
      map.layers.onChange();
    };

    // 获取 layers 里面的 key 集合
    map.getAllKeys = function () {
      return map.layers.getAllKeys();
    };

    // 获取当前展示的 keys
    map.getLayersShowKeys = function () {
      return map.layers.getShowKeys();
    };

    // 获取当前隐藏的 keys
    map.getLayersHiddenKeys = function () {
      return map.layers.getHiddenKeys();
    };

    // 根据 keys 设置图层的显示，其他的隐藏
    map.setLayersShowByKeys = function (_keys) {
      return map.layers.setShowByKeys(_keys);
    };

    // 根据 keys 设置图层的隐藏，其他的显示
    map.setLayersHideByKeys = function (_keys) {
      return map.layers.setHideByKeys(_keys);
    };

    // 添加图层
    map.addLayer = function (layer, index) {
      return map.layers.addLayer(layer, index);
    };

    // 移除图层
    map.removeLayer = function (layer) {
      return map.layers.removeLayer(layer);
    };

    // 清除图层和entity
    map.clearLayers = function () {
      return map.layers.clearLayers();
    };

    // 获取 ImageLayer 图层
    map.getImageLayers = function (keys) {
      return map.layers.getImageLayers(keys);
    };

    // 获取 FeatureLayer 图层
    map.getFeatureLayers = function (keys) {
      return map.layers.getFeatureLayers(keys);
    };

    // 获取 Imagery 图层最后一个 index 值
    map.getImageryLastIndex = function (_index) {
      var index = 1;
      var layers = map.getImageryLayers();
      if (layers !== null && layers !== void 0 && layers.length) {
        if (_index && layers.findIndex(function (v) {
          return _index < v.zIndex;
        }) !== -1) {
          index = layers.findIndex(function (v) {
            return _index < v.zIndex;
          }) + 1;
        } else {
          index = layers.length;
        }
      }
      return index;
    };

    // 查找所有dataSource和imagery图层
    map.getAllLayers = function () {
      var _map$dataSources, _map$imageryLayers, _map$scene;
      var dataSources = (map === null || map === void 0 || (_map$dataSources = map.dataSources) === null || _map$dataSources === void 0 ? void 0 : _map$dataSources._dataSources) || [];
      var imageryLayers = (map === null || map === void 0 || (_map$imageryLayers = map.imageryLayers) === null || _map$imageryLayers === void 0 ? void 0 : _map$imageryLayers._layers) || [];
      var primitives = (map === null || map === void 0 || (_map$scene = map.scene) === null || _map$scene === void 0 || (_map$scene = _map$scene.primitives) === null || _map$scene === void 0 ? void 0 : _map$scene._primitives) || [];
      return [].concat(_toConsumableArray(dataSources), _toConsumableArray(imageryLayers), _toConsumableArray(primitives));
    };

    // 根据key查找imageryLayers图层
    map.getImageryLayers = function (_keys) {
      var _map$imageryLayers2;
      var layers = (map === null || map === void 0 || (_map$imageryLayers2 = map.imageryLayers) === null || _map$imageryLayers2 === void 0 ? void 0 : _map$imageryLayers2._layers) || [];
      if (_keys && layers.length) {
        var keys = Array.isArray(_keys) ? _keys : [_keys];
        return layers.filter(function (layer) {
          return layer.key && keys.includes(layer.key);
        });
      }
      return layers;
    };

    // 通过图形查询所属图层
    map.getLayerByFeature = function (entity) {
      return map.getAllLayers().find(function (layer) {
        if (entity instanceof ImageryLayerFeatureInfo) {
          var _entity$imageryLayer;
          if (layer !== null && layer !== void 0 && layer.key && layer.key === (entity === null || entity === void 0 || (_entity$imageryLayer = entity.imageryLayer) === null || _entity$imageryLayer === void 0 ? void 0 : _entity$imageryLayer.key)) {
            return layer;
          }
        } else if (layer instanceof Primitive) {
          var _entity$primitive;
          if (layer !== null && layer !== void 0 && layer.key && layer.key === (entity === null || entity === void 0 || (_entity$primitive = entity.primitive) === null || _entity$primitive === void 0 ? void 0 : _entity$primitive.key)) {
            return layer;
          }
        } else {
          if (layer !== null && layer !== void 0 && layer.key && layer.key === (entity === null || entity === void 0 ? void 0 : entity.key)) {
            return layer;
          }
        }
      });
    };

    // 获取entity中数据
    map.getProperties = function (feature) {
      var _feature$_properties, _properties;
      if (feature !== null && feature !== void 0 && feature.primitive && (feature === null || feature === void 0 ? void 0 : feature.primitive) instanceof Primitive) {
        return feature.primitive.data.find(function (item) {
          return item.id === feature.id;
        });
      }
      var properties = (feature === null || feature === void 0 || (_feature$_properties = feature._properties) === null || _feature$_properties === void 0 ? void 0 : _feature$_properties.getValue(feature._id)) || (feature === null || feature === void 0 ? void 0 : feature.properties) || {};
      properties = ((_properties = properties) === null || _properties === void 0 ? void 0 : _properties.properties) || properties;
      return properties;
    };

    // 通过key查询图层
    map.getLayerByKey = function (key) {
      return map.getAllLayers().find(function (layer) {
        return key && layer.key && layer.key === key;
      });
    };

    // 通过keys查询多个图层
    map.getLayerByKeys = function (keys) {
      return map.getAllLayers().filter(function (layer) {
        return layer.key && keys.includes(layer.key);
      });
    };
    map.destroyhighlightLayer = function () {
      highlightLayer.current.clearFeatures();
    };
    // 通过返回值控制是否执行关闭
    map.onCloseTemplateBefore = function (feature) {
      // 清除高亮
      map.destroyhighlightLayer();
      if (onCloseTemplateBefore) {
        return onCloseTemplateBefore(feature);
      }
    };

    // 根据key查找展示的图层
    map.getVisibleLayersByKeys = function (keys) {
      var layers = map.getAllLayers() || [];
      return layers.filter(function (layer) {
        if (typeof keys === 'string') {
          return layer.key === keys && layer.show;
        } else if (Array.isArray(keys)) {
          return keys.includes(layer.key) && layer.show;
        } else {
          return layer.show && layer.key;
        }
      });
    };

    // 展示提示
    map.showTip = function (content) {
      setTip(content);
    };

    // 隐藏提示
    map.hideTip = function () {
      setTip(null);
    };

    // 根据图层条件设置图层选中
    map.showTemplateByFilter = function (key, field, value) {
      var layer = map.getLayerByKey(key);
      if (layer !== null && layer !== void 0 && layer.show) {
        var feature = layer.getFeatureByFieldValue(field, value);
        if (feature) {
          map.showTemplate(feature);
        }
      }
    };

    // 展示看板
    map.showTemplate = function (feature, event, highlightLayer) {
      var _popupRef$current;
      (_popupRef$current = popupRef.current) === null || _popupRef$current === void 0 || _popupRef$current.showTemplate(feature, highlightLayer);
    };

    // 隐藏看板
    map.hideTemplate = function () {
      var _popupRef$current2;
      (_popupRef$current2 = popupRef.current) === null || _popupRef$current2 === void 0 || _popupRef$current2.hideTemplate();
    };

    // 鼠标事件控制器
    var handlePoint = new ScreenSpaceEventHandler(map.scene.canvas);

    // 获取图层上的图形信息
    map.pickDataSourcesFeature = function (event) {
      if (event !== null && event !== void 0 && event.position) {
        var position = event.position;
        var pick = map.scene.pick(position);
        if (_lodash["default"].isObject(pick === null || pick === void 0 ? void 0 : pick.id)) {
          return pick.id;
        }
        return pick;
      }
    };

    // 根据关键字获取图形信息
    map.getMapFeatureInfoByText = getMapFeatureInfoByText;

    // 获取wms的图形数据
    map.pickImageryLayerFeatures = function (event) {
      if (event !== null && event !== void 0 && event.position) {
        var position = event.position;
        var pickRay = map.camera.getPickRay(position);
        return map.imageryLayers.pickImageryLayerFeatures(pickRay, map.scene);
      }
    };

    // 获取当前地图中心的经纬度
    map.getCenterPosition = function () {
      var centerResult = map.camera.pickEllipsoid(new Cartesian2(map.canvas.clientWidth / 2, map.canvas.clientHeight / 2));
      var curPosition = Ellipsoid.WGS84.cartesianToCartographic(centerResult);
      var curLongitude = curPosition.longitude * 180 / Math.PI;
      var curLatitude = curPosition.latitude * 180 / Math.PI;
      return [curLongitude, curLatitude];
    };

    // 二三维切换
    map.setViewMode = function (type) {
      map.viewMode = type;
      map.fitView();
    };

    // 注册事件
    (0, _events.registerEventLayer)(map, props);

    // 注册地图组件事件
    function registerMapEvent(e, event) {
      if (map[event]) {
        map[event](e);
        onEvents[event] && onEvents[event](e);
      }
    }

    // 注册图层组件事件
    function registerEvent(feature, event) {
      if (feature) {
        var _feature$event;
        var properties = map.getProperties(feature) || {};
        if (feature instanceof ImageryLayerFeatureInfo && feature !== null && feature !== void 0 && feature.data) {
          properties = _objectSpread(_objectSpread({}, properties), {}, {
            data: feature === null || feature === void 0 ? void 0 : feature.data
          });
        }

        // 触发自身事件
        (_feature$event = feature[event]) === null || _feature$event === void 0 || _feature$event.call(feature, properties);
        var layer = map.getLayerByFeature(feature);
        if (layer !== null && layer !== void 0 && layer[event]) {
          layer[event](properties);
        }
      }
    }

    // 点击事件
    handlePoint.setInputAction(function (event) {
      event.lonLat = map.getPositionLonLat(event);
      registerMapEvent(event, 'onClick');
      map.hideTip();
      var entity = map.pickDataSourcesFeature(event);
      var featuresPromise = map.pickImageryLayerFeatures(event);
      if (entity) {
        map.onClickTemplateAfter && map.onClickTemplateAfter(entity);
        registerEvent(entity, 'onClick');
        highlightLayer.current.addHighlightFeature(entity);
        map.showTemplate(entity, event, highlightLayer.current);
      } else if (defined(featuresPromise)) {
        when(featuresPromise, function (features) {
          features.sort(function (a, b) {
            return b.imageryLayer._layerIndex - a.imageryLayer._layerIndex;
          });
          var feature = features === null || features === void 0 ? void 0 : features[0];
          highlightLayer.current.addHighlightFeature(feature);
          registerEvent(feature, 'onClick');
          map.showTemplate(feature, event, highlightLayer.current);
        });
      }
    }, ScreenSpaceEventType.LEFT_CLICK);

    // 双击事件
    handlePoint.setInputAction(function (event) {
      map.trackedEntity = undefined; // 取消双击锁定

      event.lonLat = map.getPositionLonLat(event);
      registerMapEvent(event, 'onDoubleClick');
      var feature = map.pickDataSourcesFeature(event);
      registerEvent(feature, 'onDoubleClick');
    }, ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    // 鼠标移动
    var hoverFeature;
    var getUid = function getUid(feature) {
      if (feature && !feature._id) {
        feature._id = window.Math.random();
      }
      return feature._id;
    };

    // 鼠标移入移出
    handlePoint.setInputAction(function (event) {
      event.lonLat = map.getPositionLonLat({
        position: event.endPosition
      });
      registerMapEvent(event, 'onMouseMove');
      var feature = map.pickDataSourcesFeature({
        position: event.endPosition
      });
      if (feature) {
        var _map$getLayerByFeatur;
        var labelField = (_map$getLayerByFeatur = map.getLayerByFeature(feature)) === null || _map$getLayerByFeatur === void 0 ? void 0 : _map$getLayerByFeatur.labelField;
        if (labelField) {
          var properties = map.getProperties(feature);
          var label = properties ? properties[labelField] : '';
          if (label) {
            map.showTip(label);
          }
        }
        registerEvent(feature, 'onMouseMove');

        // 判断是否在图形内移动
        if (hoverFeature) {
          var uid = getUid(feature);
          var hoverUid = getUid(hoverFeature);

          // 判断是否进入新的图形
          if (uid !== hoverUid) {
            registerEvent(hoverFeature, 'onMouseLeave');
            registerEvent(feature, 'onMouseEnter');
            hoverFeature = feature;
          }
        } else {
          registerEvent(feature, 'onMouseEnter');
          hoverFeature = feature;
        }
        registerEvent(feature, 'onMouseMove');
      } else {
        if (hoverFeature) {
          registerEvent(hoverFeature, 'onMouseLeave');
        }
        hoverFeature = null;
        map.hideTip();
      }
    }, ScreenSpaceEventType.MOUSE_MOVE);

    // 层级事件
    if (onZoom) {
      map.camera.moveEnd.addEventListener(function () {
        var viewRectangle = map.camera.computeViewRectangle();
        var west = viewRectangle.west / Math.PI * 180; // 左上方（西）
        var north = viewRectangle.north / Math.PI * 180; //右上方（北）
        var east = viewRectangle.east / Math.PI * 180; // 右下方（东）
        var south = viewRectangle.south / Math.PI * 180; // 左下方（南）
        var cameraHeight = map.camera.positionCartographic.height;
        onZoom && onZoom({
          west: west,
          north: north,
          east: east,
          south: south,
          cameraHeight: cameraHeight,
          viewRectangle: viewRectangle
        });
      });
    }

    // 动态调整视角，不传参数为默认视角，参数可以是图层、图形、数据等
    map.fitView = function (e) {
      var _ref = e || {},
        geoJson = _ref.geoJson,
        geometryInfo = _ref.geometryInfo,
        data = _ref.data,
        entity = _ref.entity,
        lng = _ref.lng,
        lat = _ref.lat,
        _ref$height = _ref.height,
        height = _ref$height === void 0 ? 50000 : _ref$height,
        rest = _objectWithoutProperties(_ref, _excluded2);
      var pitch = map.camera.pitch;

      // 判断是否点击了图形
      if (entity) {
        if (map.viewMode === '3D') {
          map.flyTo(entity, {
            duration: 2
          });
        } else {
          map.flyTo(entity, {
            duration: 2,
            offset: {
              heading: Math.toRadians(0.0),
              pitch: pitch,
              range: height
            }
          });
        }
      } else if (lng && lat) {
        map.camera.flyTo(_objectSpread({
          destination: new Cartesian3.fromDegrees(Number(lng), Number(lat), height),
          orientation: {
            pitch: Math.toRadians(-88.0),
            roll: 0.0
          },
          duration: 2
        }, rest));
      } else if (data || geometryInfo || geoJson) {
        var _geoJson = geoJson;
        if (geometryInfo) {
          _geoJson = (0, _createFeatureCollection.createFeatureCollection)([{
            geometryInfo: geometryInfo
          }]);
        }
        if (data) {
          _geoJson = (0, _createFeatureCollection.createFeatureCollection)(Array.isArray(data) ? data : [data]);
        }
        var box = (0, _getBBoxFromGeojson["default"])(_geoJson, 0.035);
        map.camera.flyTo(_objectSpread({
          destination: _construct(Rectangle.fromDegrees, _toConsumableArray(box)),
          //west, south, east, north,
          orientation: {
            pitch: map.viewMode === '3D' ? Math.toRadians(-35) : Math.toRadians(defaultPitch),
            roll: 0.0
          },
          duration: 2
        }, rest));
      } else {
        var _viewDefault$center = _slicedToArray(viewDefault.center, 3),
          x = _viewDefault$center[0],
          y = _viewDefault$center[1],
          _viewDefault$center$ = _viewDefault$center[2],
          z = _viewDefault$center$ === void 0 ? 80000.0 : _viewDefault$center$;
        if (map.viewMode === '3D') {
          map.camera.flyTo(_objectSpread({
            destination: Cartesian3.fromDegrees(x, y - 0.5, z / 2),
            orientation: {
              pitch: Math.toRadians(-35),
              roll: 0.0
            },
            duration: 2
          }, options));
        } else {
          map.camera.flyTo({
            destination: new Cartesian3.fromDegrees(x, y, z),
            orientation: {
              pitch: Math.toRadians(defaultPitch),
              roll: 0.0
            },
            duration: 2
          });
        }
      }
    };
    map.getPositionLonLat = function (event) {
      var cartesian = map.camera.pickEllipsoid(event.position, map.scene.globe.ellipsoid); // Cartesian3对象
      if (cartesian) {
        var cartographic = Cartographic.fromCartesian(cartesian); // 经纬高对象
        var lng = Math.toDegrees(cartographic.longitude);
        var lat = Math.toDegrees(cartographic.latitude);
        return [lng, lat];
      }
      return [];
    };
    if (duration) {
      // 自动调整视角
      map.fitView();

      // 延时触发回调事件
      setTimeout(function () {
        setMapLoaded(true);
        createdMap && createdMap(map);
        onEvents.createdMap && onEvents.createdMap(map);
      }, duration);
    } else {
      var _viewDefault$center2 = _slicedToArray(viewDefault.center, 3),
        x = _viewDefault$center2[0],
        y = _viewDefault$center2[1],
        _viewDefault$center2$ = _viewDefault$center2[2],
        z = _viewDefault$center2$ === void 0 ? 80000.0 : _viewDefault$center2$;
      map.camera.setView({
        destination: new Cartesian3.fromDegrees(x, y, z)
      });
      setMapLoaded(true);
      createdMap && createdMap(map);
      onEvents.createdMap && onEvents.createdMap(map);
    }
  };
  var onMouseMove = function onMouseMove(event) {
    if (tip) {
      tipRef.current.style.left = "".concat(event.nativeEvent.layerX + 15, "px");
      tipRef.current.style.top = "".concat(event.nativeEvent.layerY + 15, "px");
    }
  };
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      width: width,
      height: height,
      background: dark ? '#152937' : '#cccccc'
    },
    className: (0, _classnames["default"])('map-container')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    ref: mapDomRef,
    className: (0, _classnames["default"])('map'),
    onMouseMove: onMouseMove,
    onMouseOver: function onMouseOver() {
      return setTipVis(true);
    },
    onMouseOut: function onMouseOut() {
      return setTipVis(false);
    }
  }, tip && tipVis && /*#__PURE__*/_react["default"].createElement("div", {
    ref: tipRef,
    className: (0, _classnames["default"])('custom-tip')
  }, tip), mapRef.current && /*#__PURE__*/_react["default"].createElement(_Popup["default"], {
    ref: popupRef,
    map: mapRef.current
  })), mapLoaded && /*#__PURE__*/_react["default"].createElement(_Provider["default"], {
    value: {
      map: mapRef.current
    }
  }, children));
}
var _default = Map;
exports["default"] = _default;
Map.propTypes = {
  width: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
  height: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
  createdMap: _propTypes["default"].func,
  onCloseTemplateBefore: _propTypes["default"].func,
  onZoom: _propTypes["default"].func,
  center: _propTypes["default"].array,
  zoom: _propTypes["default"].number,
  minZoom: _propTypes["default"].number,
  maxZoom: _propTypes["default"].number,
  defaultPitch: _propTypes["default"].number,
  dark: _propTypes["default"].bool,
  mapStyle: _propTypes["default"].oneOfType(['vec', 'img']),
  tk: _propTypes["default"].string.isRequired,
  onEvents: _propTypes["default"].object,
  baseMapUrl: _propTypes["default"].string,
  duration: _propTypes["default"].number,
  baseMapStyle: _propTypes["default"].object
};
//# sourceMappingURL=index.js.map
