"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
var _icons = require("@ant-design/icons");
var _Table = _interopRequireDefault(require("../../components/Table"));
var _Modal = _interopRequireDefault(require("../../components/Modal"));
var _layer = require("../../../_util/layer");
var _layer2 = require("ol/layer");
var _Polygon = require("ol/geom/Polygon");
var _Draw = _interopRequireDefault(require("../../Utils/Draw"));
require("./index.less");
var _useProps2 = _interopRequireDefault(require("../../../use-props"));
var _classnames2 = _interopRequireDefault(require("classnames"));
var _ahooks = require("ahooks");
var _ImageLayer = require("../../../image-layer/ImageLayer");
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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 _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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /*
                                                                       * @Description:框选、圈选、多边形选择
                                                                       */
var classPrefix = 'selectTools';
var LayerSelect = function LayerSelect(props) {
  var _list;
  var _props$options = props.options,
    options = _props$options === void 0 ? [] : _props$options,
    value = props.value,
    onChange = props.onChange,
    currentKey = props.currentKey;
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = (0, _react.useState)(value),
    _useState4 = _slicedToArray(_useState3, 2),
    active = _useState4[0],
    setActive = _useState4[1];
  var time = (0, _react.useRef)();
  (0, _ahooks.useUpdateEffect)(function () {
    setActive(value);
  }, [value]);
  if (!(options !== null && options !== void 0 && options.length)) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
  }
  var showOpen = (options === null || options === void 0 ? void 0 : options.length) > 9;
  var list = options;
  if (options !== null && options !== void 0 && options.length) {
    if (!open) {
      if (options.length > 9) {
        list = options.slice(0, 9);
      }
    } else {
      list = options;
    }
  }
  var _onClick = function onClick(value) {
    setActive(value);
    currentKey.current = value;
    if (time.current) {
      clearTimeout(time.current);
    }
    time.current = setTimeout(function () {
      onChange === null || onChange === void 0 ? void 0 : onChange(value);
    }, 500);
  };
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])("".concat(classPrefix, "-layer-select"), {
      'selectTools-layer-select-scroll': open
    })
  }, /*#__PURE__*/_react["default"].createElement(_antd.Space, {
    size: [8, 8],
    wrap: true
  }, ((_list = list) === null || _list === void 0 ? void 0 : _list.length) > 0 && list.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      className: (0, _classnames2["default"])("".concat(classPrefix, "-layer-select-item"), _defineProperty({}, "".concat(classPrefix, "-layer-select-item-active"), active === item.value)),
      onClick: function onClick() {
        return _onClick(item.value);
      }
    }, item.label);
  })), showOpen && /*#__PURE__*/_react["default"].createElement(_antd.Divider, {
    style: {
      margin: 0
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    icon: open ? /*#__PURE__*/_react["default"].createElement(_icons.VerticalAlignTopOutlined, null) : /*#__PURE__*/_react["default"].createElement(_icons.VerticalAlignBottomOutlined, null),
    onClick: function onClick() {
      return setOpen(!open);
    },
    type: "link"
  }, open ? '收起' : '展开')));
};
var _default = function _default(props) {
  var onClose = props.onClose,
    drawType = props.drawType,
    title = props.title,
    renderTableActive = props.renderTableActive;
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var _useState5 = (0, _react.useState)(''),
    _useState6 = _slicedToArray(_useState5, 2),
    currentLayerKey = _useState6[0],
    setCurrentLayerKey = _useState6[1];
  var _useState7 = (0, _react.useState)([]),
    _useState8 = _slicedToArray(_useState7, 2),
    dataSource = _useState8[0],
    setDataSource = _useState8[1];
  var _useState9 = (0, _react.useState)(false),
    _useState10 = _slicedToArray(_useState9, 2),
    loading = _useState10[0],
    setLoading = _useState10[1];
  var _useState11 = (0, _react.useState)(true),
    _useState12 = _slicedToArray(_useState11, 2),
    open = _useState12[0],
    setOpen = _useState12[1];
  var _useState13 = (0, _react.useState)([]),
    _useState14 = _slicedToArray(_useState13, 2),
    layersOpts = _useState14[0],
    setLayersOpts = _useState14[1];
  var _useState15 = (0, _react.useState)({}),
    _useState16 = _slicedToArray(_useState15, 2),
    feature = _useState16[0],
    setFeature = _useState16[1];
  var draw = (0, _react.useRef)();
  var currentKey = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    onClick();
  }, [currentLayerKey, JSON.stringify(feature), layersOpts]);
  (0, _react.useEffect)(function () {
    var layersChange = function layersChange() {
      getOptions();
    };
    layersChange();

    // 添加图层变化监听事件
    map.layers.on('change', layersChange);
    return function () {
      // 移除图层变化监听事件
      map.layers.un('change', layersChange);
    };
  }, []);
  (0, _react.useEffect)(function () {
    draw.current = new _Draw["default"]({
      map: map,
      zIndex: 80
    });
    draw.current.draw(drawType, function (feature) {
      setFeature(feature);
    });
    return function () {
      draw.current.destroy();
      map.hideTemplate();
      currentKey.current = null;
    };
  }, []);
  var getOptions = function getOptions() {
    if (map) {
      var _opts$;
      var opts = [];
      var layers = map.getAllLayers().filter(function (v) {
        return !v.viewOnly && v.key && v.name && v.layerControl && v.show;
      });
      layers.map(function (v) {
        opts.push(_objectSpread(_objectSpread({}, v), {}, {
          value: v.key,
          label: v.name
        }));
      });

      // 当前key对应的图层还显示的话取当前的key否者取第一个layersOpts的key
      var _key = opts === null || opts === void 0 ? void 0 : (_opts$ = opts[0]) === null || _opts$ === void 0 ? void 0 : _opts$.value;
      if (currentKey.current) {
        var layer = map.layers.getLayerByKey(currentKey.current);
        if (layer && layer !== null && layer !== void 0 && layer.show) {
          _key = currentKey.current;
        }
      }
      currentKey.current = _key;
      setCurrentLayerKey(_key);
      setLayersOpts(opts);
    }
  };
  var onClick = function onClick() {
    var _feature$getGeometry;
    setDataSource([]);
    if (!feature) return;
    var geometry = feature === null || feature === void 0 ? void 0 : (_feature$getGeometry = feature.getGeometry) === null || _feature$getGeometry === void 0 ? void 0 : _feature$getGeometry.call(feature);
    if (!geometry) return;
    setLoading(true);
    var layer = map.layers.getLayerByKey(currentLayerKey);
    if (geometry && currentLayerKey && layer) {
      var tableData = [];
      // wms图层
      if (layer instanceof _layer2.Image) {
        getWmsData(geometry, layer, tableData);
      } else if (layer instanceof _layer2.Vector) {
        getWfsData(geometry, layer, tableData);
      }
    } else {
      setLoading(false);
      if (!geometry) {
        _antd.message.destroy();
        _antd.message.info('请先框选图层', 2);
      }
      if (!currentLayerKey) {
        _antd.message.destroy();
        _antd.message.info('请先选择图层', 2);
      }
    }
  };

  /**
   * @description: wfs图层时获取框选数据
   * @param {*} geometry
   * @param {*} layer
   * @param {*} tableData
   * @return {*}
   */
  var getWfsData = function getWfsData(geometry, layer, tableData) {
    var extent = geometry.getExtent();
    var source = layer.getSource();
    var features = [];
    var getFeatureInfo = function getFeatureInfo(feature) {
      var listKeys = feature.getKeys();
      var data = {};
      listKeys.forEach(function (item) {
        if (feature.get(item)) {
          data[item] = feature.get(item);
          if (layer.labelField) {
            data.NAME = feature.get(layer.labelField);
          }
          data.feature = feature;
        }
      });
      return data;
    };
    if (source.forEachFeatureIntersectingExtent && extent) {
      source.forEachFeatureIntersectingExtent(extent, function (feature) {
        var featureList = feature.get('features');
        if ((featureList === null || featureList === void 0 ? void 0 : featureList.length) > 1) {
          featureList.forEach(function (feature) {
            var data = getFeatureInfo(feature);
            tableData.push(data);
            features.push(feature);
          });
        } else {
          var data = getFeatureInfo(feature);
          tableData.push(data);
          features.push(feature);
        }
      });
      setLoading(false);
      map.setHighlightFeature(features);
      setDataSource(tableData);
    } else {
      setLoading(false);
    }
  };

  /**
   * @description: wms图层时获取框选数据
   * @return {*}
   */
  var getWmsData = function getWmsData(geometry, layer, tableData) {
    var _layer$group;
    var _filter = '';
    if (layer !== null && layer !== void 0 && (_layer$group = layer.group) !== null && _layer$group !== void 0 && _layer$group.length) {
      _filter = (0, _ImageLayer.getFilter)(layer.group);
    }
    var coorStr = '';
    var coordinates = geometry.getCoordinates();

    // 圈选处理
    if (drawType === 'Circle') {
      var polygonGeometry = new _Polygon.fromCircle(geometry);
      coordinates = polygonGeometry.getCoordinates();
    }
    coordinates[0].forEach(function (v, i) {
      if (i == 0) {
        coorStr += "".concat(v[0], " ").concat(v[1]);
      } else {
        coorStr += ", ".concat(v[0], " ").concat(v[1]);
      }
    });
    // 增加图层的其他过滤
    var filter = _filter ? "(".concat(_filter, ") and ") : '';
    (0, _layer.getWFSFeatureInfoByLayer)(layer, "".concat(filter, "INTERSECTS(geo_location, POLYGON((").concat(coorStr, ")))")).then(function (features) {
      setLoading(false);
      map.setHighlightFeature(features);
      if (features !== null && features !== void 0 && features.length) {
        features.forEach(function (item) {
          var listKeys = item.getKeys();
          var data = {};
          listKeys.forEach(function (itemk) {
            if (item.get(itemk)) {
              data[itemk] = item.get(itemk);
              data.feature = item;
            }
          });
          if (layer.labelField) {
            data.NAME = item.get(layer.labelField) || '';
          }
          tableData.push(data);
        });
        setDataSource(tableData);
      } else {
        _antd.message.destroy();
        _antd.message.info('暂无数据', 2);
      }
    });
  };
  var columns = [{
    title: '编码/名称',
    dataIndex: 'NAME',
    width: 200,
    render: function render(text, record) {
      return /*#__PURE__*/_react["default"].createElement("a", {
        onClick: function onClick() {
          var _map$getViewport;
          var doc = document.getElementsByClassName('ol-map-tools')[0];
          var rect = doc === null || doc === void 0 ? void 0 : doc.getBoundingClientRect();
          var parentRect = (_map$getViewport = map.getViewport()) === null || _map$getViewport === void 0 ? void 0 : _map$getViewport.getBoundingClientRect();
          var left = 400;
          if (rect && parentRect) {
            left = (rect === null || rect === void 0 ? void 0 : rect.left) - (parentRect === null || parentRect === void 0 ? void 0 : parentRect.left) + 12 + 350 + 150;
          }
          map.showTemplate(record.feature, {
            fitViewOptions: {
              padding: [100, 400, 100, left]
            }
          });
        }
      }, text);
    }
  }];
  return /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: title || '',
    onClose: onClose,
    width: 300
  }, /*#__PURE__*/_react["default"].createElement(_antd.Spin, {
    spinning: loading
  }, /*#__PURE__*/_react["default"].createElement(LayerSelect, {
    options: layersOpts,
    value: currentLayerKey,
    onChange: setCurrentLayerKey,
    currentKey: currentKey
  }), renderTableActive && renderTableActive(dataSource, currentLayerKey, onClick), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      minHeight: 20
    }
  }, open && /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    rowKey: "code",
    dataSource: dataSource,
    columns: columns,
    size: "small"
  })), (dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) > 0 && /*#__PURE__*/_react["default"].createElement("div", {
    className: "ol-map-search-result-button",
    onClick: function onClick() {
      return setOpen(!open);
    }
  }, open ? '收起' : '展开', open ? /*#__PURE__*/_react["default"].createElement(_icons.CaretUpOutlined, null) : /*#__PURE__*/_react["default"].createElement(_icons.CaretDownOutlined, null))));
};
exports["default"] = _default;
//# sourceMappingURL=index.js.map
