"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"] = Search;
exports.toolOptions = exports.getMapFeatureInfoByText = void 0;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
var _icons = require("@ant-design/icons");
var _ItemWrap = _interopRequireDefault(require("../components/ItemWrap"));
var _layer = require("ol/layer");
var _format = require("ol/format");
var _utils = require("@vtx/utils");
var _useProps2 = _interopRequireDefault(require("../../use-props"));
var _ToolItem = _interopRequireDefault(require("../components/ToolItem"));
var _http = _interopRequireDefault(require("../../_util/http"));
var _encryptParams = _interopRequireDefault(require("../../_util/encryptParams"));
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 && Object.prototype.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 _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; }
/**
 * 根据关键字获取图形信息
 * @param map
 * @param searchText
 * @returns {Promise<unknown>} [{label: '图层名称', options: [{label: '', value: ''}]}]
 */
var getMapFeatureInfoByText = exports.getMapFeatureInfoByText = function getMapFeatureInfoByText(map, searchText) {
  return new Promise(function (resolve) {
    var list = [],
      reqList = [];
    map.getAllLayers().map(function (layer) {
      if (layer.getVisible() && layer.key) {
        var label = layer.name;
        var field = layer.labelField;
        if (layer instanceof _layer.Vector && layer.getSource()) {
          var features = getVectorFeatureInfoByText(layer, field || 'name', searchText);
          if (features !== null && features !== void 0 && features.length) {
            list.push({
              label: label,
              options: features
            });
          }
        } else if (layer instanceof _layer.Image && layer.getSource()) {
          reqList.push(getWmsFeatureInfoByText(layer, field || 'code', searchText).then(function (features) {
            return {
              label: label,
              options: features
            };
          }));
        }
      }
    });
    if (reqList !== null && reqList !== void 0 && reqList.length) {
      Promise.all(reqList).then(function (res) {
        res.map(function (v) {
          var _v$options;
          if ((_v$options = v.options) !== null && _v$options !== void 0 && _v$options.length) {
            list.push(v);
          }
        });
        resolve(list);
      });
    } else {
      resolve(list);
    }
  });
};

// 根据关键字获取图形信息
var getVectorFeatureInfoByText = function getVectorFeatureInfoByText(layer, field, searchText) {
  var source = layer.getSource().source || layer.getSource();
  var features = source.getFeatures();
  if (features !== null && features !== void 0 && features.length) {
    var _features = features.filter(function (v) {
      var _v$values_;
      return ((v === null || v === void 0 || (_v$values_ = v.values_) === null || _v$values_ === void 0 ? void 0 : _v$values_[field]) || '').indexOf(searchText) !== -1;
    });
    if (_features !== null && _features !== void 0 && _features.length) {
      return handleResult(_features, layer, field);
    }
  }
};

// 根据关键字获取图形信息
var getWmsFeatureInfoByText = function getWmsFeatureInfoByText(layer, field, searchText) {
  var _getUrlParam = (0, _utils.getUrlParam)(),
    tenantId = _getUrlParam.tenantId;
  var source = layer.getSource();
  var params = {
    maxFeatures: 50,
    service: 'WFS',
    request: 'GetFeature',
    outputFormat: 'application/json',
    geoserverUrl: source.url_,
    version: source.params_.VERSION,
    typeName: layer.params.QUERY_LAYERS || source.params_.QUERY_LAYERS,
    cql_filter: layer.params.cql_filter || source.params_.cql_filter,
    viewparams: "tenantId:".concat(tenantId)
  };
  var cql_filter = "".concat(field, " like %27%25").concat(searchText, "%25%27");
  params.cql_filter = params.cql_filter ? "(".concat(params.cql_filter, ") and ").concat(cql_filter) : cql_filter;
  if (layer.encrypt) {
    params = (0, _encryptParams["default"])(params, layer.encrypt);
  }
  var queryString = Object.entries(params).reduce(function (acc, _ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    return "".concat(acc).concat(key, "=").concat(value, "&");
  }, '?').slice(0, -1);
  return _http["default"].get("".concat(source.url_).concat(queryString)).then(function (data) {
    var _data$features;
    var features = [];
    if (data !== null && data !== void 0 && (_data$features = data.features) !== null && _data$features !== void 0 && _data$features.length) {
      var geoJsonFormat = new _format.GeoJSON();
      features = geoJsonFormat.readFeatures(data);
      features = handleResult(features, layer, field);
    }
    return features;
  })["catch"](function () {
    return [];
  });
};
var handleResult = function handleResult(features, layer, field) {
  return features.map(function (v) {
    var _v$values_2, _v$values_3, _v$values_4, _v$values_5;
    v.label = v === null || v === void 0 || (_v$values_2 = v.values_) === null || _v$values_2 === void 0 ? void 0 : _v$values_2[field];
    v.value = (v === null || v === void 0 || (_v$values_3 = v.values_) === null || _v$values_3 === void 0 ? void 0 : _v$values_3.id) || (v === null || v === void 0 || (_v$values_4 = v.values_) === null || _v$values_4 === void 0 ? void 0 : _v$values_4.facilityId) || (v === null || v === void 0 || (_v$values_5 = v.values_) === null || _v$values_5 === void 0 ? void 0 : _v$values_5[field]);
    v.layerKey = layer.key;
    return v;
  });
};
var toolOptions = exports.toolOptions = [
// { label: '点选', icon: 'icon-dianxuan', active: true, key: 'pointSelect' },
{
  label: '框选',
  icon: 'icon-kuangxuan',
  key: 'boxSelect'
}, {
  label: '圈选',
  icon: 'icon-quanxuan',
  key: 'circleSelect'
}, {
  label: '多边形选择',
  icon: 'icon-duobianxingxuanze',
  key: 'polygonSelect'
}
// { label: '空间定位查询', icon: 'icon-kuangxuan', key: 'spaceQuery' },
];

function Search(props) {
  var active = props.active,
    setActive = props.setActive;
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var time = (0, _react.useRef)(null);
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    options = _useState2[0],
    setOptions = _useState2[1];
  var _useState3 = (0, _react.useState)(''),
    _useState4 = _slicedToArray(_useState3, 2),
    value = _useState4[0],
    setValue = _useState4[1];
  var itemWrapRef = (0, _react.useRef)();

  // 地址查询
  var onSearch = function onSearch(searchText) {
    if (time.current) {
      clearTimeout(time.current);
    }
    if (searchText) {
      time.current = setTimeout(function () {
        getMapFeatureInfoByText(map, searchText).then(function (data) {
          setOptions(data);
        });
      }, 500);
    } else {
      setOptions([]);
    }
  };
  var onChange = function onChange(_value) {
    setValue(_value);
  };
  (0, _react.useEffect)(function () {
    // 挂载关闭工具方法
    map.closeToolbox = function () {
      setActive('');
    };
    return function () {
      // 移除关闭工具方法
      delete map.closeToolbox;
    };
  }, []);
  var onActive = function onActive(v) {
    if (!v.key) {
      return;
    }
    var value = active && v.key === active ? '' : v.key;

    // 执行关闭分析
    map.closeAnalysis && map.closeAnalysis();

    // 增加当前激活的工具属性
    map.toolboxActive = value;
    setActive(value);
  };
  var onSelect = function onSelect(_value, e) {
    var feature;
    options.map(function (v) {
      var _v$options2;
      if (v !== null && v !== void 0 && (_v$options2 = v.options) !== null && _v$options2 !== void 0 && _v$options2.length) {
        v.options.map(function (o) {
          if (o.value === _value) {
            feature = o;
          }
        });
      }
    });
    map.showTemplate(feature);
    map.fitView(e);
    setValue(e.label);
  };
  var onClear = function onClear() {
    map.fitView();
    map.hideTemplate();
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_ItemWrap["default"], {
    ref: itemWrapRef,
    content: /*#__PURE__*/_react["default"].createElement(_icons.SearchOutlined, null)
  }, /*#__PURE__*/_react["default"].createElement(_antd.AutoComplete, {
    placeholder: "\u8BF7\u8F93\u5165",
    options: options,
    style: {
      width: 200
    },
    value: value,
    onSearch: onSearch,
    onChange: onChange,
    onSelect: onSelect,
    allowClear: true,
    onClear: onClear,
    onFocus: function onFocus() {
      return setActive('');
    }
  }), toolOptions && toolOptions.length > 0 && toolOptions.map(function (v) {
    var params = props[v.key];
    if (params !== null && params !== void 0 && params.show) {
      return /*#__PURE__*/_react["default"].createElement(_ToolItem["default"], {
        key: v.label,
        onClick: function onClick() {
          itemWrapRef.current.setVisible(false);
          onActive(v);
        },
        label: v.label,
        icon: v.icon,
        active: active === v.key || v.active
      });
    } else {
      return null;
    }
  })));
}
Search.defaultProps = {
  boxSelect: {
    show: true
  },
  circleSelect: {
    show: true
  },
  polygonSelect: {
    show: true
  },
  spaceQuery: {
    show: true
  }
};
//# sourceMappingURL=index.js.map
