"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"] = VmMap;
var _tslib = require("tslib");
var _jquery = _interopRequireDefault(require("jquery"));
var _react = _interopRequireWildcard(require("react"));
var _map = require("@vtx/map");
var _useSettings2 = _interopRequireDefault(require("../vm-hooks/useSettings"));
var _mapStyle = require("./mapStyle");
require("./style");
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 _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; } /* eslint-disable no-undef */
function VmMap(_a) {
  var _b, _c;
  var _a$mapType = _a.mapType,
    mapType = _a$mapType === void 0 ? 'bmap' : _a$mapType,
    _a$mapPoints = _a.mapPoints,
    mapPoints = _a$mapPoints === void 0 ? [] : _a$mapPoints,
    mapCenter = _a.mapCenter,
    _a$mapPolygons = _a.mapPolygons,
    mapPolygons = _a$mapPolygons === void 0 ? [] : _a$mapPolygons,
    currentLayer = _a.currentLayer,
    geometryType = _a.geometryType,
    clickGraphic = _a.clickGraphic,
    rest = (0, _tslib.__rest)(_a, ["mapType", "mapPoints", "mapCenter", "mapPolygons", "currentLayer", "geometryType", "clickGraphic"]);
  var mapRef = (0, _react.useRef)(null);
  var markers = (0, _react.useRef)([]);
  var mappolygons = (0, _react.useRef)([]);
  var highlightLayer = (0, _react.useRef)([]);
  var _useSettings = (0, _useSettings2["default"])(),
    isDark = _useSettings.isDark,
    theme = _useSettings.theme,
    mapInfo = _useSettings.mapInfo;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    defaultCenter = _useState2[0],
    setDefaultCenter = _useState2[1];
  var _useState3 = (0, _react.useState)([]),
    _useState4 = _slicedToArray(_useState3, 2),
    points = _useState4[0],
    setPoints = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = _slicedToArray(_useState5, 2),
    center = _useState6[0],
    setCenter = _useState6[1];
  var _useState7 = (0, _react.useState)([]),
    _useState8 = _slicedToArray(_useState7, 2),
    polygons = _useState8[0],
    setPolygons = _useState8[1];
  var _useState9 = (0, _react.useState)([]),
    _useState10 = _slicedToArray(_useState9, 2),
    lines = _useState10[0],
    setLines = _useState10[1];
  (0, _react.useEffect)(function () {
    if (mapInfo === null || mapInfo === void 0 ? void 0 : mapInfo.longitude) {
      setDefaultCenter([mapInfo.longitude, mapInfo.latitude]);
    }
  }, [mapInfo]);
  (0, _react.useEffect)(function () {
    var wrapScroll = document.querySelector('.ant-modal-body');
    wrapScroll && wrapScroll.addEventListener('scroll', function () {
      window.scrollY = (wrapScroll === null || wrapScroll === void 0 ? void 0 : wrapScroll.scrollTop) || 0;
    });
  }, []);
  (0, _react.useEffect)(function () {
    if (theme !== 'light' && mapType != 'olmap') {
      initMap();
    }
  }, [theme, defaultCenter]);
  (0, _react.useEffect)(function () {
    if ((mapPoints === null || mapPoints === void 0 ? void 0 : mapPoints.length) > 0) {
      var _list = mapPoints.map(function (ele) {
        return Object.assign(Object.assign({}, ele), {
          longitude: ele.lng,
          latitude: ele.lat
        });
      }) || [];
      setPoints(_list);
    }
  }, [mapPoints]);
  (0, _react.useEffect)(function () {
    var filterMapPolygons = mapPolygons.filter(function (_ref) {
      var rings = _ref.rings;
      return !!rings;
    });
    if ((filterMapPolygons === null || filterMapPolygons === void 0 ? void 0 : filterMapPolygons.length) > 0) {
      if (geometryType === 'polyline') {
        setLines(filterMapPolygons.map(function (item) {
          return {
            id: item.id,
            config: item.config,
            paths: item.rings.split(';').map(function (v) {
              return v.split(',').map(function (v) {
                return Number(v);
              });
            })
          };
        }));
      } else {
        setPolygons(filterMapPolygons.map(function (item) {
          return Object.assign(Object.assign({}, item), {
            rings: item.rings.split(';').map(function (v) {
              return v.split(',').map(function (v) {
                return Number(v);
              });
            })
          });
        }));
      }
    }
  }, [mapPolygons]);
  (0, _react.useEffect)(function () {
    if (mapRef === null || mapRef === void 0 ? void 0 : mapRef.current) {
      addPoints(mapPoints);
      addPolygons(mapPolygons);
    }
  }, [JSON.stringify(mapPoints), JSON.stringify(mapPolygons), mapRef === null || mapRef === void 0 ? void 0 : mapRef.current]);
  (0, _react.useEffect)(function () {
    var _a;
    if (theme !== 'light') {
      removeHighLightPolygons();
      // 清空高亮图层并绘制新图层
      if (currentLayer === null || currentLayer === void 0 ? void 0 : currentLayer.id) addPolygons([{
        id: currentLayer.id,
        rings: (_a = currentLayer === null || currentLayer === void 0 ? void 0 : currentLayer.geometryInfo) === null || _a === void 0 ? void 0 : _a.lngLats,
        config: {
          lineWidth: 2,
          lineOpacity: 0.5
        }
      }], 'highlight');
    }
  }, [theme, JSON.stringify(currentLayer)]);
  var init = function init() {
    var center = mapCenter || defaultCenter;
    mapRef.current = new window.BMapGL.Map('modalMap', {
      style: {
        styleJson: isDark || theme == 'blue' ? _mapStyle.customStyle : _mapStyle.customLight
      }
    });
    var point = new window.BMapGL.Point(center[0], center[1]);
    // 设置中心点和层级
    mapRef.current.centerAndZoom(point, 15);
    // mapRef.current.addOverlay(new window.BMapGL.Marker(point));
    mapRef.current.enableScrollWheelZoom(); // 滚轮放大缩小
  };
  var initMap = function initMap() {
    if (window.BMapGL) {
      init();
    } else {
      _jquery["default"].getScript("//api.map.baidu.com/getscript?type=webgl&v=1.0&ak=1XjLLEhZhQNUzd93EjU5nOGQ", function () {
        init();
      });
    }
  };
  // 地图添加点位
  var addPoints = function addPoints() {
    var points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    removePoints();
    if (!(points === null || points === void 0 ? void 0 : points.length)) {
      var _center = mapCenter || defaultCenter;
      var point = new window.BMapGL.Point(_center[0], _center[1]);
      mapRef.current.addOverlay(new window.BMapGL.Marker(point));
      return;
    }
    // 添加点位
    var positions = [];
    points.forEach(function (item) {
      var _a, _b;
      var position = new window.BMapGL.Point(item.lng, item.lat);
      positions.push(position);
      var icon = new window.BMapGL.Icon(item.url || require('./imgs/defaultMarker.png'), new window.BMapGL.Size(item.width || 32, item.height || 45));
      var marker = new window.BMapGL.Marker(position, {
        icon: icon,
        offset: new window.BMapGL.Size(((_a = item === null || item === void 0 ? void 0 : item.offset) === null || _a === void 0 ? void 0 : _a.width) || -10, ((_b = item === null || item === void 0 ? void 0 : item.offset) === null || _b === void 0 ? void 0 : _b.height) || -16),
        title: item.name || ''
      });
      markers.current.push(marker);
      mapRef.current.addOverlay(marker);
    });
    mapRef.current.setViewport(positions);
  };
  // 清除地图点位
  var removePoints = function removePoints() {
    var _a;
    ((_a = markers.current) === null || _a === void 0 ? void 0 : _a.length) && markers.current.forEach(function (marker) {
      mapRef.current.addOverlay(marker);
    });
    markers.current = [];
  };
  //点击图元事件
  var clickPolygon = function clickPolygon(item, e) {
    if (typeof clickGraphic === 'function') {
      var obj = {
        item: item,
        e: e
      };
      clickGraphic(obj);
    }
  };
  // 地图添加线
  var addPolygons = function addPolygons() {
    var polygons = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var type = arguments.length > 1 ? arguments[1] : undefined;
    removePolygons();
    var list = polygons === null || polygons === void 0 ? void 0 : polygons.filter(function (ele) {
      return !!ele.rings;
    });
    if (!(list === null || list === void 0 ? void 0 : list.length)) return;
    var points = [];
    //遍历添加图层(图元)
    polygons.map(function (item) {
      //初始化参数
      var cg = {
        lineType: 'solid',
        lineWidth: 5,
        lineColor: '#277ffa',
        lineOpacity: geometryType === 'polyline' ? 1 : 0.3,
        color: '#fff',
        pellucidity: 0.5
        // isHidden: false  //后期需要再加
      };
      if (item.config) {
        cg = Object.assign(Object.assign({}, cg), item.config);
      }
      //面的参数
      var polygonOption = {
          strokeColor: cg.lineColor,
          strokeOpacity: cg.lineOpacity,
          strokeWeight: cg.lineWidth,
          strokeStyle: cg.lineType,
          fillColor: cg.color,
          fillOpacity: cg.pellucidity
        },
        polygonPath = item.rings.split(';').map(function (item) {
          var _ref2 = item === null || item === void 0 ? void 0 : item.split(','),
            _ref3 = _slicedToArray(_ref2, 2),
            lng = _ref3[0],
            lat = _ref3[1];
          var _point = new window.BMapGL.Point(lng, lat);
          points.push(_point);
          return _point;
        });
      //创建面对象
      var polygon = geometryType === 'polyline' ? new window.BMapGL.Polyline(polygonPath, polygonOption) : new window.BMapGL.Polygon(polygonPath, polygonOption);
      //添加点击事件
      polygon.on('click', function (e) {
        clickPolygon(item, e);
        // 居中显示
        setTimeout(function () {
          mapRef.current.setViewport(item.rings.split(';').map(function (item) {
            var _ref4 = item === null || item === void 0 ? void 0 : item.split(','),
              _ref5 = _slicedToArray(_ref4, 2),
              lng = _ref5[0],
              lat = _ref5[1];
            var _point = new window.BMapGL.Point(lng, lat);
            return _point;
          }));
        }, 300);
      });
      if (type) {
        // 若为高亮图层，单独保存，用于单独清除
        highlightLayer.current.push(polygon);
        mapRef.current.addOverlay(polygon);
      } else {
        mappolygons.current.push(polygon);
        mapRef.current.addOverlay(polygon);
      }
    });
    mapRef.current.setViewport(points);
  };
  // 清除地图图元
  var removePolygons = function removePolygons() {
    var _a;
    ((_a = mappolygons.current) === null || _a === void 0 ? void 0 : _a.length) && mappolygons.current.forEach(function (polygon) {
      mapRef.current.removeOverlay(polygon);
    });
    mappolygons.current = [];
  };
  // 清除高亮图元
  var removeHighLightPolygons = function removeHighLightPolygons() {
    highlightLayer.current.forEach(function (polygon) {
      mapRef.current.removeOverlay(polygon);
    });
    highlightLayer.current = [];
  };
  var list = [].concat(_toConsumableArray(polygons), _toConsumableArray(lines));
  var pointCneter;
  if ((points === null || points === void 0 ? void 0 : points.length) > 0) {
    pointCneter = [(_b = points === null || points === void 0 ? void 0 : points[0]) === null || _b === void 0 ? void 0 : _b.lng, (_c = points === null || points === void 0 ? void 0 : points[0]) === null || _c === void 0 ? void 0 : _c.lat];
  }
  var mapProps = Object.assign({
    mapId: 'vtx_modal_map',
    mapCenter: pointCneter || mapCenter || defaultCenter,
    mapType: mapType,
    mapPoints: points || [],
    mapPolygons: polygons || [],
    mapLines: lines || [],
    setCenter: center
  }, rest);
  // 点位层级固定显示16，可在customMapInfo传参修改
  if (list.length) {
    mapProps = Object.assign(Object.assign({}, mapProps), {
      mapVisiblePoints: {
        fitView: list.length ? list === null || list === void 0 ? void 0 : list.map(function (ele) {
          return ele.id;
        }) : [],
        type: 'all'
      },
      setVisiblePoints: Math.random() * 1000
    });
  }
  (0, _react.useEffect)(function () {
    if (mapCenter && (mapCenter === null || mapCenter === void 0 ? void 0 : mapCenter.length) > 0) {
      setCenter(true);
      setTimeout(function () {
        return setCenter(false);
      }, 2500);
    }
  }, [JSON.stringify(mapCenter)]);
  return theme == 'light' || mapProps.mapType == 'olmap' ? (defaultCenter === null || defaultCenter === void 0 ? void 0 : defaultCenter.length) > 0 ? (/*#__PURE__*/_react["default"].createElement(_map.VtxMap, Object.assign({}, mapProps))) : (/*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null)) : (/*#__PURE__*/_react["default"].createElement("div", {
    id: "modalMap",
    style: {
      width: '100%',
      height: '100%'
    }
  }));
}
//# sourceMappingURL=index.js.map
