"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 _message = _interopRequireDefault(require("antd/lib/message"));
var _table = _interopRequireDefault(require("antd/lib/table"));
var _button = _interopRequireDefault(require("antd/lib/button"));
var _select = _interopRequireDefault(require("antd/lib/select"));
var _input = _interopRequireDefault(require("antd/lib/input"));
var _radio = _interopRequireDefault(require("antd/lib/radio"));
var _useProps2 = _interopRequireDefault(require("@vtx/ol-map/lib/use-props"));
var _featureDraw = _interopRequireDefault(require("@vtx/ol-map/lib/feature-draw"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _Modal = _interopRequireDefault(require("../_component/Modal"));
var _RequiredLabel = _interopRequireDefault(require("../_component/RequiredLabel"));
var _Select = _interopRequireDefault(require("../_component/Select"));
var _ToolsSelect = _interopRequireDefault(require("../_component/ToolsSelect"));
var _classnames = _interopRequireDefault(require("classnames"));
var _Polygon = require("ol/geom/Polygon");
var _Observable = require("ol/Observable");
var _request = _interopRequireDefault(require("../_mapUtil/request"));
var _config = _interopRequireDefault(require("../_mapUtil/config"));
var _service = _interopRequireDefault(require("../_mapUtil/service"));
var _FeatureLayer = _interopRequireDefault(require("@vtx/ol-map/lib/feature-layer/FeatureLayer"));
var _ImageLayer = _interopRequireDefault(require("@vtx/ol-map/lib/image-layer/ImageLayer"));
var _FeatureSelect = _interopRequireDefault(require("../_mapUtil/GetData/FeatureSelect"));
var _PublicService = _interopRequireDefault(require("../_mapUtil/PublicService"));
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 _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; } /**
 * 条件相关
 * @description: 用于展示条件查询、绘制控件等
 */
var tenantId = _PublicService["default"].getQueryString('tenantId') || _PublicService["default"].getSystemInfo('tenantId');
var CONFIG = {
  '1': {
    name: '数值',
    operator: ['=', '>', '<', '>=', '<=']
  },
  '2': {
    name: '字符串',
    operator: ['=', '包含']
  },
  '3': {
    name: '枚举',
    operator: ['=', '包含']
  },
  '4': {
    name: '布尔',
    operator: ['=']
  }
};

// 数据转条件
var dataToCQLFilter = function dataToCQLFilter(data, whereValue) {
  var cql_filter = '';
  if (data !== null && data !== void 0 && data.length) {
    data.map(function (v) {
      var type = v.type,
        field = v.field,
        operator = v.operator,
        value = v.value;
      if (operator === '包含') {
        if (String(type) === '3') {
          operator = 'in';
          value = "(".concat(value.join(','), ")");
        } else {
          operator = 'like';
          value = "'%".concat(value, "%'");
        }
      } else {
        value = "'".concat(value, "'");
      }
      var where = "".concat(field, " ").concat(operator, " ").concat(value);
      cql_filter = cql_filter ? "".concat(cql_filter, " ").concat(whereValue, " ").concat(where) : where;
    });
  }
  return cql_filter;
};

// 字段
var Field = function Field(props) {
  var options = props.options,
    value = props.value,
    status = props.status,
    onChange = props.onChange;
  return /*#__PURE__*/_react["default"].createElement(_select["default"], {
    status: status,
    value: value,
    style: {
      width: '100%'
    },
    onChange: onChange,
    options: options
  });
};
Field.propTypes = {
  options: _propTypes["default"].array,
  value: _propTypes["default"].string,
  status: _propTypes["default"].string,
  onChange: _propTypes["default"].func
};
// 操作符
var Operator = function Operator(props) {
  var value = props.value,
    options = props.options,
    status = props.status,
    onChange = props.onChange;
  return /*#__PURE__*/_react["default"].createElement(_select["default"], {
    value: value,
    status: status,
    style: {
      width: '100%'
    },
    onChange: onChange,
    options: options
  });
};
Operator.propTypes = {
  value: _propTypes["default"].string,
  options: _propTypes["default"].array,
  status: _propTypes["default"].string,
  onChange: _propTypes["default"].func
};
// 值
var Value = function Value(props) {
  var type = props.type,
    operator = props.operator,
    options = props.options,
    value = props.value,
    status = props.status,
    _onChange = props.onChange;
  if (type === '3') {
    return /*#__PURE__*/_react["default"].createElement(_select["default"], {
      status: status,
      value: value,
      mode: operator === '包含' ? 'multiple' : null,
      style: {
        width: '100%'
      },
      onChange: _onChange,
      options: options
    });
  }
  if (type === '4') {
    return /*#__PURE__*/_react["default"].createElement(_select["default"], {
      status: status,
      value: value,
      style: {
        width: '100%'
      },
      onChange: _onChange,
      options: [{
        label: '否',
        value: 0
      }, {
        label: '是',
        value: 1
      }]
    });
  }
  return /*#__PURE__*/_react["default"].createElement(_input["default"], {
    value: value,
    status: status,
    onChange: function onChange(e) {
      return _onChange(e.target.value);
    }
  });
};
Value.propTypes = {
  type: _propTypes["default"].string,
  operator: _propTypes["default"].string,
  options: _propTypes["default"].array,
  value: _propTypes["default"].string,
  status: _propTypes["default"].string,
  onChange: _propTypes["default"].func
};
var Table = function Table(props) {
  var map = props.map,
    layerList = props.layerList,
    layerKey = props.layerKey,
    onAnalysis = props.onAnalysis;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    dataSource = _useState2[0],
    setDataSource = _useState2[1];
  var _useState3 = (0, _react.useState)([]),
    _useState4 = _slicedToArray(_useState3, 2),
    fieldList = _useState4[0],
    setFieldList = _useState4[1];
  var _useState5 = (0, _react.useState)('and'),
    _useState6 = _slicedToArray(_useState5, 2),
    whereValue = _useState6[0],
    setWhereValue = _useState6[1];
  (0, _react.useEffect)(function () {
    setDataSource([{
      key: new Date().getTime()
    }]);
    if (layerKey && layerList.length > 0) {
      getColumnRelationByTableName('zhsw_' + _service["default"].getCodeByOptions(layerList, layerKey));
    }
  }, [layerKey, layerList]);
  var getColumnRelationByTableName = function getColumnRelationByTableName(tableName) {
    var url = "".concat(_config["default"].publicUrlJCSS, "/api/tableColumnRelation/getColumnRelationByTableName");
    var params = {
      tableName: tableName
    };
    _request["default"].get(url, {
      body: params
    }).then(function (res) {
      var _res$data, _res$data2;
      var _fieldList = [];
      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) {
        res.data.map(function (v) {
          _fieldList.push({
            label: v.name,
            value: v.columnName,
            values: v
          });
        });
      }
      if ((res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length) == 0) {
        setDataSource([]);
      }
      setFieldList(_fieldList);
    });
  };

  // 字段选择
  var onFieldChange = function onFieldChange(value, index) {
    var _fieldList$find, _CONFIG$type;
    var _dataSource = _toConsumableArray(dataSource);
    _dataSource[index].field = value;
    _dataSource[index].field_status = '';

    // 设置类型和枚举项
    var _ref = ((_fieldList$find = fieldList.find(function (v) {
        return v.value === value;
      })) === null || _fieldList$find === void 0 ? void 0 : _fieldList$find.values) || {},
      type = _ref.type,
      enumList = _ref.enumList;
    _dataSource[index].type = type;
    _dataSource[index].enumList = enumList ? enumList.map(function (v) {
      return {
        label: v.key,
        value: v.value
      };
    }) : [];

    // 设置操作符数据
    var options = (CONFIG === null || CONFIG === void 0 || (_CONFIG$type = CONFIG[type]) === null || _CONFIG$type === void 0 ? void 0 : _CONFIG$type.operator) || [];
    options = options.map(function (v) {
      return {
        label: v,
        value: v
      };
    });
    _dataSource[index].operatorList = options;

    // 清空数据
    _dataSource[index].operator = '';
    _dataSource[index].value = '';
    setDataSource(_dataSource);
  };

  // 操作符选择
  var onOperatorChange = function onOperatorChange(value, index) {
    var _dataSource = _toConsumableArray(dataSource);
    _dataSource[index].operator = value;
    _dataSource[index].operator_status = '';
    _dataSource[index].value = value === '包含' ? [] : '';
    setDataSource(_dataSource);
  };
  var onValueChange = function onValueChange(value, index) {
    var _dataSource = _toConsumableArray(dataSource);
    _dataSource[index].value = value;
    _dataSource[index].value_status = '';
    setDataSource(_dataSource);
  };
  var verifyData = function verifyData() {
    var _dataSource = _toConsumableArray(dataSource);
    var error = false;
    _dataSource.map(function (v) {
      ['field', 'operator', 'value'].map(function (f) {
        if (!v[f]) {
          v["".concat(f, "_status")] = 'error';
          error = true;
        }
      });
    });
    setDataSource(_dataSource);
    return error;
  };
  var onFinish = function onFinish() {
    var error = verifyData();
    if (!error) {
      onAnalysis(dataSource, whereValue);
    } else {
      _message["default"].info('查询条件存在空项');
    }
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, (dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) > 0 && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('row')
  }, /*#__PURE__*/_react["default"].createElement(_RequiredLabel["default"], {
    label: "\u6761\u4EF6\u5173\u7CFB"
  }, /*#__PURE__*/_react["default"].createElement(_radio["default"].Group, {
    style: {
      paddingLeft: 6
    },
    onChange: function onChange(e) {
      return setWhereValue(e.target.value);
    },
    value: whereValue
  }, /*#__PURE__*/_react["default"].createElement(_radio["default"], {
    value: "and"
  }, "\u5E76\u4E14"), /*#__PURE__*/_react["default"].createElement(_radio["default"], {
    value: "or"
  }, "\u6216\u8005")))), /*#__PURE__*/_react["default"].createElement(_table["default"], {
    className: (0, _classnames["default"])('tableWrap'),
    size: "middle",
    columns: [{
      title: '序号',
      dataIndex: 'num',
      width: 50,
      align: 'center',
      render: function render(_, _2, index) {
        return index + 1;
      }
    }, {
      title: /*#__PURE__*/_react["default"].createElement(_RequiredLabel["default"], {
        label: "\u5B57\u6BB5"
      }),
      dataIndex: 'field',
      width: 120,
      align: 'left',
      render: function render(text, record, index) {
        return /*#__PURE__*/_react["default"].createElement(Field, {
          value: text,
          status: record.field_status,
          options: fieldList,
          onChange: function onChange(value) {
            return onFieldChange(value, index);
          }
        });
      }
    }, {
      title: /*#__PURE__*/_react["default"].createElement(_RequiredLabel["default"], {
        label: "\u64CD\u4F5C\u7B26"
      }),
      dataIndex: 'operator',
      width: 120,
      align: 'left',
      render: function render(text, record, index) {
        return /*#__PURE__*/_react["default"].createElement(Operator, {
          value: text,
          status: record.operator_status,
          options: record.operatorList || [],
          onChange: function onChange(value) {
            return onOperatorChange(value, index);
          }
        });
      }
    }, {
      title: /*#__PURE__*/_react["default"].createElement(_RequiredLabel["default"], {
        label: "\u503C"
      }),
      dataIndex: 'value',
      width: 120,
      align: 'left',
      render: function render(text, record, index) {
        return /*#__PURE__*/_react["default"].createElement(Value, {
          value: text,
          status: record.value_status,
          type: record.type && String(record.type),
          operator: record.operator,
          record: record,
          options: record.enumList || [],
          onChange: function onChange(value) {
            return onValueChange(value, index);
          }
        });
      }
    }, {
      title: '操作',
      dataIndex: 'c',
      width: 60,
      align: 'left',
      render: function render(_, _2, index) {
        return /*#__PURE__*/_react["default"].createElement(_button["default"], {
          type: "link",
          disabled: dataSource.length === 1,
          style: {
            padding: 0
          },
          onClick: function onClick() {
            var _dataSource = _toConsumableArray(dataSource);
            _dataSource.splice(index, 1);
            setDataSource(_dataSource);
          }
        }, "\u5220\u9664");
      }
    }],
    dataSource: dataSource,
    pagination: false,
    toolbar: false,
    scroll: {
      y: map.getViewport().clientHeight - 362
    },
    footer: function footer() {
      return /*#__PURE__*/_react["default"].createElement("div", {
        onClick: function onClick() {
          var newTableData = JSON.parse(JSON.stringify(dataSource));
          newTableData.push({
            key: new Date().getTime()
          });
          setDataSource(newTableData);
        }
      }, "+\u6DFB\u52A0");
    },
    rowKey: "code"
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('btn')
  }, /*#__PURE__*/_react["default"].createElement(_button["default"], {
    type: "primary",
    onClick: onFinish
  }, "\u67E5\u8BE2")));
};
Table.propTypes = {
  map: _propTypes["default"].any,
  layerList: _propTypes["default"].array,
  layerKey: _propTypes["default"].string,
  onAnalysis: _propTypes["default"].func
};
var Search = function Search(props) {
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map,
    setVisible = _useProps.setVisible,
    setLoading = _useProps.setLoading,
    setTableData = _useProps.setTableData,
    options = _useProps.options,
    activeKey = _useProps.activeKey,
    onClose = _useProps.onClose,
    setActiveKey = _useProps.setActiveKey,
    analysisLayer = _useProps.analysisLayer,
    highLayer = _useProps.highLayer;
  var _useState7 = (0, _react.useState)(''),
    _useState8 = _slicedToArray(_useState7, 2),
    toolsKey = _useState8[0],
    setToolsKey = _useState8[1];
  var _useState9 = (0, _react.useState)([]),
    _useState10 = _slicedToArray(_useState9, 2),
    flatCoordinates = _useState10[0],
    setFlatCoordinates = _useState10[1];
  var _useState11 = (0, _react.useState)(''),
    _useState12 = _slicedToArray(_useState11, 2),
    drawType = _useState12[0],
    setDrawType = _useState12[1];
  var _useState13 = (0, _react.useState)(null),
    _useState14 = _slicedToArray(_useState13, 2),
    features = _useState14[0],
    setFeatures = _useState14[1];
  var moveKey = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    onLayerInit();
    map.on('loadstart', function () {
      onLayerInit();
    });
    return function () {
      moveKey.current && (0, _Observable.unByKey)(moveKey.current); // 监听地图移动事件
    };
  }, []);
  var onLayerInit = function onLayerInit() {};
  var onLayerChange = function onLayerChange(key) {
    setActiveKey(key);
  };
  var onToolsChange = function onToolsChange(key) {
    moveKey.current && (0, _Observable.unByKey)(moveKey.current);
    if (key && key !== 'CurrentView') {
      // 选择了其他类型
      // drawRef.current.drawType = key;
      setDrawType(key);
    } else if (key === 'CurrentView') {
      setDrawType('');
      // 选择了当前范围
      setFlatCoordinates(_service["default"].getExtend(map));
      moveKey.current = map.on('moveend', function () {
        var extend = _service["default"].getExtend(map);
        setFlatCoordinates(extend);
      });
    }
    setToolsKey(key);
  };

  // 查询
  var _onAnalysis = function onAnalysis(dataSource, whereValue, key) {
    var cql_filter = dataToCQLFilter(dataSource, whereValue);
    if (!activeKey) {
      return _message["default"].info('请选择查询图层');
    }
    if (!(features !== null && features !== void 0 && features.length) && key !== 'CurrentView') {
      return _message["default"].info('请绘制查询范围');
    }
    setLoading(true);
    setTableData([]);
    setVisible(true);
    var coorStr = '';
    var coordinates = '';
    if (key !== 'CurrentView') {
      var geometry = features[0].getGeometry();
      coordinates = geometry.getCoordinates();
      // 圈选处理
      if (toolsKey === 'Circle') {
        var polygonGeometry = new _Polygon.fromCircle(geometry);
        coordinates = polygonGeometry.getCoordinates();
      }
    }
    // 当前范围
    if (key === 'CurrentView') {
      coordinates = flatCoordinates;
    }
    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 layer = _service["default"].getLayerByActiveKey(map, activeKey);
    analysisLayer === null || analysisLayer === void 0 || analysisLayer.clearFeatures();
    highLayer === null || highLayer === void 0 || highLayer.clearFeatures();
    if (layer instanceof _ImageLayer["default"]) {
      var filter = layer === null || layer === void 0 ? void 0 : layer.cql_filter;
      var _cql_filter = filter ? "".concat(filter, " and ").concat(cql_filter) : "".concat(cql_filter);
      var params = {
        url: layer.url,
        typeName: layer.params.typeName,
        layers: layer.params.typeName,
        QUERY_LAYERS: layer.params.QUERY_LAYERS,
        cql_filter: _cql_filter ? "".concat(_cql_filter, " and INTERSECTS(geo_location, POLYGON((").concat(coorStr, ")))") : "INTERSECTS(geo_location, POLYGON((".concat(coorStr, ")))"),
        viewparams: "tenantId:".concat(tenantId)
      };
      analysisLayer.key = activeKey;
      analysisLayer.setLayerData(params).then(function (data) {
        setLoading(false);
        setTableData(data);
      });
    }
    if (layer instanceof _FeatureLayer["default"]) {
      var _data = (0, _FeatureSelect["default"])({
        map: map,
        feature: features === null || features === void 0 ? void 0 : features[0],
        layers: [layer],
        loadingFn: function loadingFn() {},
        highLayerFn: function highLayerFn() {}
      });
      if ((dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) > 0 && whereValue) {
        _service["default"].getFeaturesByFieldValueOpera({
          features: _data === null || _data === void 0 ? void 0 : _data.features,
          dataSource: dataSource,
          whereValue: whereValue
        }).then(function (result) {
          setTableData(result);
          highLayer.setHighlight(result);
          setLoading(false);
        });
      } else {
        setTableData(_data === null || _data === void 0 ? void 0 : _data.features);
        highLayer.setHighlight(_data === null || _data === void 0 ? void 0 : _data.features);
        setLoading(false);
      }
    }
  };
  var onDrawEnd = function onDrawEnd(feature) {
    setFeatures([feature]);
  };
  var onClosefn = function onClosefn() {
    onClose && onClose();
    try {
      map.hideTemplate();
    } catch (err) {}
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: "\u8BBE\u65BD\u641C\u7D22",
    onClose: onClosefn,
    width: 500
  }, /*#__PURE__*/_react["default"].createElement(_ToolsSelect["default"], {
    title: "",
    value: toolsKey,
    onChange: onToolsChange,
    options: _service["default"].btnList
  }), /*#__PURE__*/_react["default"].createElement(_Select["default"], {
    width: "100%",
    layout: "horizontal",
    options: options,
    title: "\u56FE\u5C42\u9009\u62E9",
    value: activeKey,
    onChange: onLayerChange
  }), /*#__PURE__*/_react["default"].createElement(Table, {
    map: map,
    layerKey: activeKey,
    layerList: options,
    onAnalysis: function onAnalysis(dataSource, whereValue) {
      return _onAnalysis(dataSource, whereValue, toolsKey);
    }
  }), /*#__PURE__*/_react["default"].createElement(_featureDraw["default"], {
    drawType: drawType,
    onDrawEnd: onDrawEnd
  })));
};
var _default = exports["default"] = Search;
//# sourceMappingURL=Search.js.map
