"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 _http = _interopRequireDefault(require("../_util/http"));
var _config = _interopRequireDefault(require("../_mapUtil/config"));
var _Modal = _interopRequireDefault(require("../_component/Modal"));
var _useProps2 = _interopRequireDefault(require("@vtx/ol-map/lib/use-props"));
var _message = _interopRequireDefault(require("antd/lib/message"));
var _ToolsSelect = _interopRequireDefault(require("../_component/ToolsSelect"));
var _AutoComplete = _interopRequireDefault(require("../_component/AutoComplete"));
var _MyIcon = _interopRequireDefault(require("../_component/MyIcon"));
var _input = _interopRequireDefault(require("antd/lib/input"));
var _button = _interopRequireDefault(require("antd/lib/button"));
var _service = _interopRequireDefault(require("../_mapUtil/service"));
var _utils = require("../_mapUtil/utils");
var _propTypes = _interopRequireDefault(require("prop-types"));
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 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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 _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; } /**
 * @returns 纳污范围分析（污水）
 */
function Search(props) {
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map,
    highLayer = _useProps.highLayer;
  var _props$onClose = props.onClose,
    onClose = _props$onClose === void 0 ? function () {} : _props$onClose,
    _props$setTableData = props.setTableData,
    setTableData = _props$setTableData === void 0 ? function () {} : _props$setTableData,
    _props$setLoading = props.setLoading,
    setLoading = _props$setLoading === void 0 ? function () {} : _props$setLoading,
    _props$setVisible = props.setVisible,
    setVisible = _props$setVisible === void 0 ? function () {} : _props$setVisible,
    activeKey = props.activeKey;
  var _useState = (0, _react.useState)(''),
    _useState2 = _slicedToArray(_useState, 2),
    btnKey = _useState2[0],
    setBtnKey = _useState2[1];
  var btn = (0, _react.useRef)();
  var _useState3 = (0, _react.useState)({}),
    _useState4 = _slicedToArray(_useState3, 2),
    dataSourceList = _useState4[0],
    setDataSourceList = _useState4[1];
  var _useState5 = (0, _react.useState)([]),
    _useState6 = _slicedToArray(_useState5, 2),
    layerList = _useState6[0],
    setLayerList = _useState6[1];
  var _useState7 = (0, _react.useState)([]),
    _useState8 = _slicedToArray(_useState7, 2),
    layerListAll = _useState8[0],
    setLayerListAll = _useState8[1];
  var _useState9 = (0, _react.useState)([]),
    _useState10 = _slicedToArray(_useState9, 2),
    featuresAll = _useState10[0],
    setFeaturesAll = _useState10[1];
  var _useState11 = (0, _react.useState)(''),
    _useState12 = _slicedToArray(_useState11, 2),
    layerKey = _useState12[0],
    setLayerKey = _useState12[1];
  var loadLayerList = function loadLayerList(key) {
    var _map$getAllLayers;
    var _keys = map.layers.getShowKeys();
    var _layerList = (_map$getAllLayers = map.getAllLayers()) === null || _map$getAllLayers === void 0 ? void 0 : _map$getAllLayers.filter(function (item) {
      var _item$name;
      return (_keys === null || _keys === void 0 ? void 0 : _keys.indexOf(item === null || item === void 0 ? void 0 : item.key)) > -1 && (item === null || item === void 0 || (_item$name = item.name) === null || _item$name === void 0 ? void 0 : _item$name.includes('泵站'));
    });
    var _features = [];
    _layerList === null || _layerList === void 0 || _layerList.map(function (item) {
      var _layer$getSource;
      var key = item === null || item === void 0 ? void 0 : item.key;
      var layer = map === null || map === void 0 ? void 0 : map.getLayerByKey(key);
      var features = (_layer$getSource = layer.getSource()) === null || _layer$getSource === void 0 ? void 0 : _layer$getSource.getFeatures();
      if (features) {
        _features.push.apply(_features, _toConsumableArray(features));
      }
    });
    var list = _features === null || _features === void 0 ? void 0 : _features.map(function (item) {
      var _item$values_, _item$values_2;
      return {
        label: item === null || item === void 0 || (_item$values_ = item.values_) === null || _item$values_ === void 0 ? void 0 : _item$values_.facilityName,
        value: item === null || item === void 0 || (_item$values_2 = item.values_) === null || _item$values_2 === void 0 ? void 0 : _item$values_2.facilityId
      };
    });
    setFeaturesAll(_features);
    setLayerListAll(list);
    var filterList = list === null || list === void 0 ? void 0 : list.filter(function (item) {
      var _item$label;
      return (_item$label = item.label) === null || _item$label === void 0 ? void 0 : _item$label.includes(key);
    });
    setLayerList(filterList);
  };
  var onCloseFn = function onCloseFn() {
    onClose();
  };
  (0, _react.useEffect)(function () {
    // 地图点击事件
    map.on('click', mapClick);
    return function () {
      map.un('click', mapClick);
    };
  }, []);
  (0, _react.useEffect)(function () {
    if (activeKey) {
      getTableData();
    }
  }, [activeKey, dataSourceList]);
  var mapClick = function mapClick(event) {
    var _map$getFeaturesAtPix;
    var keys = map.layers.getShowKeys();
    var feature = (_map$getFeaturesAtPix = map.getFeaturesAtPixel(event.pixel)) === null || _map$getFeaturesAtPix === void 0 ? void 0 : _map$getFeaturesAtPix[0];
    if (feature && map.drawActive) {
      var _feature$values_, _highLayer$current;
      var label = feature === null || feature === void 0 || (_feature$values_ = feature.values_) === null || _feature$values_ === void 0 ? void 0 : _feature$values_.facilityName;
      setLayerKey(label);
      searchLayerList(label);
      (_highLayer$current = highLayer.current) === null || _highLayer$current === void 0 || _highLayer$current.clearFeatures();
      setTableData([]);
      var layer = map.getLayerByFeature(feature);
      if (keys !== null && keys !== void 0 && keys.includes(layer === null || layer === void 0 ? void 0 : layer.key)) {
        var _highLayer$current2;
        getPumpDetail(feature.values_);
        (_highLayer$current2 = highLayer.current) === null || _highLayer$current2 === void 0 || _highLayer$current2.setHighlight([feature]);
      }
    }
  };
  // 获取泵站详情信息
  var getPumpDetail = function getPumpDetail(properties) {
    var params = {
      facilityId: properties === null || properties === void 0 ? void 0 : properties.facilityId
    };
    _http["default"].get("".concat(_config["default"].publicUrlJCSS, "/api/pumpStation/getByFacilityId"), {
      body: params
    }).then(function (res) {
      if (String(res === null || res === void 0 ? void 0 : res.result) && res !== null && res !== void 0 && res.data) {
        var _ref = (res === null || res === void 0 ? void 0 : res.data) || {},
          _ref$relationFacility = _ref.relationFacilityInfo,
          relationFacilityInfo = _ref$relationFacility === void 0 ? {} : _ref$relationFacility;
        if (relationFacilityInfo !== null && relationFacilityInfo !== void 0 && relationFacilityInfo.code) {
          console.log(relationFacilityInfo);
          getData(relationFacilityInfo);
        } else {
          _message["default"].info('该污水泵站暂无绑定窨井！', 2);
        }
      }
    });
  };
  // 获取分析数据
  var getData = function getData(_ref2) {
    var code = _ref2.code,
      typeCode = _ref2.typeCode,
      id = _ref2.id;
    setVisible(true);
    setLoading(true);
    var url = "".concat(_config["default"].publicUrlZNFX, "/api/gisAnalyze/contaminationRange");
    var params = {
      lineType: 1,
      pointCode: code
    };
    _http["default"].post(url, {
      body: params
    }).then(function (res) {
      if ((res === null || res === void 0 ? void 0 : res.result) === 0) {
        if (res !== null && res !== void 0 && res.data) {
          var _map$layers;
          var _ref3 = res.data || [],
            _ref3$lineIds = _ref3.lineIds,
            lineIds = _ref3$lineIds === void 0 ? [] : _ref3$lineIds,
            _ref3$pointIds = _ref3.pointIds,
            pointIds = _ref3$pointIds === void 0 ? [] : _ref3$pointIds,
            _ref3$deviceMap = _ref3.deviceMap,
            deviceMap = _ref3$deviceMap === void 0 ? {} : _ref3$deviceMap;
          var _lineIds = [],
            _pointIds = [],
            newData = [];
          var deviceList = [];
          var tabKeys = ((_map$layers = map.layers) === null || _map$layers === void 0 ? void 0 : _map$layers.getShowKeys().filter(function (_keys) {
            var layer = map.layers.getLayerByKey(_keys);
            return layer.key.toUpperCase().includes('LINE') || layer.key.toUpperCase().includes('POINT');
          }).map(function (_keys) {
            var layer = map.layers.getLayerByKey(_keys);
            return {
              name: layer.name,
              key: layer.key
            };
          })) || [];
          lineIds === null || lineIds === void 0 || lineIds.map(function (item) {
            var _tabKeys$filter;
            return _lineIds.push({
              id: item,
              type: tabKeys === null || tabKeys === void 0 || (_tabKeys$filter = tabKeys.filter(function (sitem) {
                return sitem.key.toUpperCase().includes('LINE');
              })) === null || _tabKeys$filter === void 0 || (_tabKeys$filter = _tabKeys$filter[0]) === null || _tabKeys$filter === void 0 ? void 0 : _tabKeys$filter.key
            });
          });
          pointIds === null || pointIds === void 0 || pointIds.map(function (item) {
            var _tabKeys$filter2;
            return _pointIds.push({
              id: item,
              type: tabKeys === null || tabKeys === void 0 || (_tabKeys$filter2 = tabKeys.filter(function (sitem) {
                return sitem.key.toUpperCase().includes('POINT');
              })) === null || _tabKeys$filter2 === void 0 || (_tabKeys$filter2 = _tabKeys$filter2[0]) === null || _tabKeys$filter2 === void 0 ? void 0 : _tabKeys$filter2.key
            });
          });
          var deviceArr = Object.keys(deviceMap);
          if (deviceArr !== null && deviceArr !== void 0 && deviceArr.length) {
            deviceArr.map(function (v) {
              var _deviceMap$v;
              var _device = [];
              if ((_deviceMap$v = deviceMap[v]) !== null && _deviceMap$v !== void 0 && _deviceMap$v.length) {
                _device = deviceMap[v].map(function (item) {
                  return _objectSpread(_objectSpread({}, item), {}, {
                    type: v
                  });
                });
              }
              deviceList.push.apply(deviceList, _toConsumableArray(_device));
            });
          }
          newData = [].concat(_lineIds, _pointIds, deviceList);
          getDataList(newData);
        } else {
          _message["default"].info('暂无数据！', 2);
        }
      }
      setLoading(false);
    });
  };
  // 获取最终数据格式
  var getDataList = function getDataList(dataList) {
    var keys = [],
      dataSourceList = {};
    (dataList === null || dataList === void 0 ? void 0 : dataList.length) && dataList.map(function (val) {
      if (!keys.includes(val.type)) {
        keys.push(val.type);
      }
      if (!dataSourceList[val.type]) {
        dataSourceList[val.type] = [];
      }
      val.rowKey = 'id';
      dataSourceList[val.type].push(val);
    });
    setDataSourceList(dataSourceList);
  };
  var getTableData = function getTableData() {
    setTableData([]);
    var url = '',
      params = {};
    var headers = {};
    var req = _http["default"].post;
    var ids = _service["default"].getField(dataSourceList === null || dataSourceList === void 0 ? void 0 : dataSourceList[activeKey], 'id');
    if (!(ids !== null && ids !== void 0 && ids.length)) {
      return false;
    }
    setLoading(true);
    if (activeKey !== null && activeKey !== void 0 && activeKey.toUpperCase().includes('LINE')) {
      var _Object$keys;
      url = "".concat(_config["default"].publicUrlJCSS, "/api/line/list");
      var _params = {
        facilityIds: ids.toString()
      };
      params = new FormData();
      ((_Object$keys = Object.keys(_params)) === null || _Object$keys === void 0 ? void 0 : _Object$keys.length) && Object.keys(_params).map(function (key) {
        params.append(key, _params[key]);
      });
      req = _http["default"].post;
    } else if (activeKey !== null && activeKey !== void 0 && activeKey.toUpperCase().includes('POINT')) {
      var _Object$keys2;
      url = "".concat(_config["default"].publicUrlJCSS, "/api/point/list");
      var _params2 = {
        facilityIds: ids.toString()
      };
      params = new FormData();
      ((_Object$keys2 = Object.keys(_params2)) === null || _Object$keys2 === void 0 ? void 0 : _Object$keys2.length) && Object.keys(_params2).map(function (key) {
        params.append(key, _params2[key]);
      });
      req = _http["default"].post;
    } else {
      params = {
        ids: JSON.stringify(ids)
      };
      url = "".concat(_config["default"].publicUrlDEVICE, "/api/device/list");
      req = _http["default"].get;
    }
    req(url, {
      body: params
    }).then(function (res) {
      var _res$data;
      if ((res === null || res === void 0 ? void 0 : res.result) === 0 && res !== null && res !== void 0 && (_res$data = res.data) !== null && _res$data !== void 0 && _res$data.length) {
        setTableData(res.data);
        highLayer.current.addHighlightData(res.data, activeKey);
      }
      setLoading(false);
    });
  };
  var classnames = function classnames(name) {
    if (name) {
      return "contamination-range-analysis-".concat(name);
    }
    return "contamination-range-analysis";
  };
  // 根据label查询图层列表
  var searchLayerList = function searchLayerList(label) {
    if (layerListAll !== null && layerListAll !== void 0 && layerListAll.length) {
      if (label) {
        var filterList = layerListAll === null || layerListAll === void 0 ? void 0 : layerListAll.filter(function (item) {
          var _item$label2;
          return (_item$label2 = item.label) === null || _item$label2 === void 0 ? void 0 : _item$label2.includes(label);
        });
        setLayerList(filterList);
      } else {
        setLayerList(layerListAll);
      }
    } else {
      loadLayerList(label);
    }
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: "\u7EB3\u6C61\u8303\u56F4\u5206\u6790",
    visible: true,
    onClose: onCloseFn,
    style: {
      minWidth: '300px'
    }
  }, /*#__PURE__*/_react["default"].createElement(_AutoComplete["default"], {
    width: "100%"
    // layout="horizontal"
    ,
    options: layerList,
    title: "",
    value: layerKey,
    onSearch: function onSearch(e) {
      console.log(e, 'onSearch');
      setLayerKey(e);
      searchLayerList(e);
    },
    onSelect: function onSelect(e) {
      var obj = layerListAll === null || layerListAll === void 0 ? void 0 : layerListAll.find(function (item) {
        return item.value == e;
      });
      setLayerKey(obj === null || obj === void 0 ? void 0 : obj.label);
      // 搜索设施定位
      var keys = map.layers.getShowKeys();
      var feature = featuresAll === null || featuresAll === void 0 ? void 0 : featuresAll.find(function (item) {
        var _item$values_3;
        return ((_item$values_3 = item.values_) === null || _item$values_3 === void 0 ? void 0 : _item$values_3.facilityId) == e;
      });
      if (feature) {
        var _highLayer$current3;
        (_highLayer$current3 = highLayer.current) === null || _highLayer$current3 === void 0 || _highLayer$current3.setHighlight([feature]);
        setTableData([]);
        var layer = map.getLayerByFeature(feature);
        if (keys !== null && keys !== void 0 && keys.includes(layer === null || layer === void 0 ? void 0 : layer.key)) {
          getPumpDetail(feature.values_);
        }
      }
    }
  }, /*#__PURE__*/_react["default"].createElement(_input["default"], {
    className: classnames('input'),
    placeholder: "\u8BF7\u8F93\u5165",
    addonAfter: /*#__PURE__*/_react["default"].createElement(_button["default"], {
      type: btnKey === 'select' ? 'primary' : '',
      icon: /*#__PURE__*/_react["default"].createElement(_MyIcon["default"], {
        type: 'icon-dianxuan',
        className: classnames('imgBox-imgIcon'),
        style: {
          color: 'select' === btnKey ? '#fff' : '#1890ff'
        },
        onClick: function onClick() {
          if (btnKey === 'select') {
            setBtnKey('');
            map === null || map === void 0 || map.hideTip();
            btn.current = '';
            map.drawActive = false;
          } else {
            // 地图提示
            map.showTip('请单击选择污水泵站');
            setBtnKey('select');
            btn.current = 'select';
            map.drawActive = true;
          }
        }
      })
    })
  }))));
}
Search.propTypes = {
  onClose: _propTypes["default"].func,
  setTableData: _propTypes["default"].func,
  setLoading: _propTypes["default"].func,
  setColumns: _propTypes["default"].func,
  setVisible: _propTypes["default"].func,
  setIsFold: _propTypes["default"].func
};
var _default = exports["default"] = Search;
//# sourceMappingURL=Search.js.map
