"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 _button = _interopRequireDefault(require("antd/lib/button"));
var _message = _interopRequireDefault(require("antd/lib/message"));
var _Modal = _interopRequireDefault(require("../_component/Modal"));
var _format = require("ol/format");
var _FormItem = require("../_component/FormItem");
var _request = _interopRequireDefault(require("../_mapUtil/request"));
var _config = _interopRequireDefault(require("../_mapUtil/config"));
var _PublicService = _interopRequireDefault(require("../_mapUtil/PublicService"));
var _useProps2 = _interopRequireDefault(require("@vtx/ol-map/lib/use-props"));
var _featureDraw = _interopRequireDefault(require("@vtx/ol-map/lib/feature-draw"));
var _service = _interopRequireDefault(require("../_mapUtil/service"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
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 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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : 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 _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; } /**
 * 条件相关
 * @description: 用于展示条件查询、绘制控件等
 */
var tenantId = _PublicService["default"].getQueryString('tenantId') || _PublicService["default"].getSystemInfo('tenantId');
var Search = function Search(props) {
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map,
    highLayer = _useProps.highLayer,
    options = _useProps.options;
  var onClose = props.onClose,
    onChange = props.onChange;
  var hide = (0, _react.useRef)();
  var _useState = (0, _react.useState)({
      startPoint: null,
      endPoint: null
    }),
    _useState2 = _slicedToArray(_useState, 2),
    points = _useState2[0],
    setPoints = _useState2[1];
  var _useState3 = (0, _react.useState)(true),
    _useState4 = _slicedToArray(_useState3, 2),
    visible = _useState4[0],
    setVisible = _useState4[1];
  var _useState5 = (0, _react.useState)(''),
    _useState6 = _slicedToArray(_useState5, 2),
    drawType = _useState6[0],
    setDrawType = _useState6[1];
  (0, _react.useEffect)(function () {
    map.showTip('请单击鼠标绘制与管线相交的直线');
    setDrawType('LineString');
    return function () {
      map.hideTip();
    };
  }, [map]);
  var classnames = function classnames(name) {
    if (name) {
      return "ol-map-cross-section-analysis-".concat(name);
    }
    return "ol-map-cross-section-analysis";
  };
  var onDrawEnd = function onDrawEnd(feature) {
    var pointList = feature.getGeometry().getCoordinates();
    if (pointList !== null && pointList !== void 0 && pointList.length) {
      points.startPoint = pointList[0];
      points.endPoint = pointList[1];
      setPoints(_objectSpread({}, points));
    }
  };
  var handleView = function handleView() {
    highLayer.clearFeatures();
    onChange && onChange({
      tableData: {
        lines: [],
        spacing: []
      },
      resultVisible: true
    });
    var startPoint = points.startPoint,
      endPoint = points.endPoint;
    if (startPoint && endPoint) {
      var _map$getAllLayers;
      hide.current = _message["default"].loading('分析中', 0);
      var allLayer = (_map$getAllLayers = map.getAllLayers()) === null || _map$getAllLayers === void 0 ? void 0 : _map$getAllLayers.filter(function (_layer) {
        return _layer.show;
      });
      var coorStr = '';
      [startPoint, endPoint].forEach(function (v, i) {
        if (i == 0) {
          coorStr += "".concat(v[0], " ").concat(v[1]);
        } else {
          coorStr += ", ".concat(v[0], " ").concat(v[1]);
        }
      });
      var geoJsonFormat = new _format.GeoJSON();
      var promises = [];
      allLayer.forEach(function (item, index) {
        var _item$getSource, _item$get;
        var CQL_FILTER;
        var filter = item === null || item === void 0 || (_item$getSource = item.getSource()) === null || _item$getSource === void 0 || (_item$getSource = _item$getSource.params_) === null || _item$getSource === void 0 ? void 0 : _item$getSource.cql_filter;
        var layers = (_item$get = item.get('params')) === null || _item$get === void 0 ? void 0 : _item$get.layers;
        if (filter) {
          CQL_FILTER = "".concat(filter, " and INTERSECTS(geo_location, LINESTRING(").concat(coorStr, "))");
        } else {
          CQL_FILTER = "INTERSECTS(geo_location, LINESTRING(".concat(coorStr, "))");
        }
        var geoserverParams = {
          service: 'WFS',
          version: '1.0.0',
          request: 'GetFeature',
          typeName: layers,
          maxFeatures: 99999,
          outputFormat: 'application/json',
          cql_filter: CQL_FILTER,
          viewparams: "tenantId:".concat(tenantId),
          key: item.key
        };
        promises.push(_request["default"].get(_config["default"].wfsSourceUrl, {
          body: _objectSpread({}, geoserverParams)
        }));
      });
      Promise.all(promises).then(function (data) {
        var newFeatures = [];
        if (data && data.length) {
          data.map(function (response, index) {
            if (response !== null && response !== void 0 && response.features) {
              var features = geoJsonFormat.readFeatures(response);
              features === null || features === void 0 || features.map(function (item) {
                var _item$values_;
                item.code = item === null || item === void 0 || (_item$values_ = item.values_) === null || _item$values_ === void 0 ? void 0 : _item$values_.code;
                item.key = allLayer[index].key;
                newFeatures.push(item);
              });
            }
          });
        }
        if (newFeatures.length > 0) {
          highLayer.addHighlightFeature(newFeatures);
          getResult([startPoint, endPoint], newFeatures);
        } else {
          hide.current && hide.current();
          return _message["default"].info('未识别相交管段!', 2);
        }
      });
    } else {
      return _message["default"].info('请先绘制一条与管道相交的直线', 2);
    }
  };

  // 更改分析返回数据
  var handleData = function handleData() {
    var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var _lines = [],
      _spacing = [];
    var lines = data.lines;
    if (lines && lines.length) {
      _lines = lines.sort(function (a, b) {
        return a.distance - b.distance;
      });
      _lines.map(function (item, index) {
        if (index < _lines.length - 1) {
          var _lines2;
          var space = (((_lines2 = _lines[index + 1]) === null || _lines2 === void 0 ? void 0 : _lines2.distance) - (item === null || item === void 0 ? void 0 : item.distance)) * 1000; // 单位换算（km/m）
          _spacing.push(space.toFixed(2) * 1);
        }
      });
    }
    return {
      lines: _lines,
      spacing: _spacing
    };
  };

  // 获取分析结果
  var getResult = function getResult(coordinates, newFeatures) {
    hide.current && hide.current();
    // 差一个管网类型，需等后台修改接口
    var data = {};
    var lineDTOS = [];
    newFeatures.forEach(function (item) {
      var _item$getGeometry;
      var id = item.id_;
      var pointList = item.getGeometry().getCoordinates();
      var type = item === null || item === void 0 || (_item$getGeometry = item.getGeometry()) === null || _item$getGeometry === void 0 ? void 0 : _item$getGeometry.getType();
      if (['MultiLineString'].includes(type)) pointList = pointList[0];
      lineDTOS.push({
        tenantId: tenantId,
        code: item.get('code'),
        ex: pointList[1][0],
        ey: pointList[1][1],
        sx: pointList[0][0],
        sy: pointList[0][1],
        lineType: _service["default"].getLineType(options, item.key)
      });
    });
    data.interSurfaceLines = lineDTOS;
    data.startX = coordinates[0][0];
    data.startY = coordinates[0][1];
    data.endX = coordinates[1][0];
    data.endY = coordinates[1][1];
    _request["default"].post("".concat(_config["default"].publicUrlZNFX, "/api/gisAnalyze/crossSectionalAnalyse"), {
      body: _objectSpread({}, data)
    }).then(function (res) {
      hide.current && hide.current();
      var crossRes = {};
      if (String(res === null || res === void 0 ? void 0 : res.result) === '0') {
        if (res !== null && res !== void 0 && res.data) {
          crossRes = res.data;
        }
        var _newCrossRes = handleData(crossRes);
        onChange && onChange({
          tableData: _newCrossRes,
          resultVisible: true
        });
      } else {
        _message["default"].error((res === null || res === void 0 ? void 0 : res.err) || '', 2);
      }
    });
  };
  var onClosefn = function onClosefn() {
    setVisible(false);
    onClose && onClose();
    onChange && onChange({
      tableData: {
        lines: [],
        spacing: []
      },
      resultVisible: false
    });
  };
  var startPoint = points.startPoint,
    endPoint = points.endPoint;
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: "\u6A2A\u622A\u9762\u5206\u6790",
    onClose: onClosefn,
    visible: visible
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: classnames('formWrap')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      position: 'relative',
      marginBottom: 16
    }
  }, /*#__PURE__*/_react["default"].createElement("label", null, "\u8D77\u70B9:"), (0, _FormItem.useRenderInput)({
    itemProps: {
      placeholder: '请选择起点',
      value: startPoint ? "".concat(startPoint[0].toFixed(5), ", ").concat(startPoint[1].toFixed(5)) : '',
      className: classnames('myAutoComplete')
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: classnames('endPoint')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      position: 'relative'
    }
  }, /*#__PURE__*/_react["default"].createElement("label", null, "\u7EC8\u70B9:"), (0, _FormItem.useRenderInput)({
    itemProps: {
      placeholder: '请选择终点',
      value: endPoint ? "".concat(endPoint[0].toFixed(5), ", ").concat(endPoint[1].toFixed(5)) : '',
      className: classnames('myAutoComplete')
    }
  })), /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleView,
    type: "primary"
  }, "\u5206\u6790")))), /*#__PURE__*/_react["default"].createElement(_featureDraw["default"], {
    drawType: drawType,
    onDrawEnd: onDrawEnd,
    maxPoints: 2
  })));
};
var _default = exports["default"] = Search;
//# sourceMappingURL=Search.js.map
