"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"] = _default;
var _react = _interopRequireWildcard(require("react"));
var _Modal = _interopRequireDefault(require("../../components/Modal"));
var _antd = require("antd");
var _RequiredLabel = _interopRequireDefault(require("../../components/RequiredLabel"));
var _Select = _interopRequireDefault(require("../../components/Select"));
var _Table = _interopRequireDefault(require("../../components/Table"));
var _ToolsSelect = _interopRequireDefault(require("../../components/ToolsSelect"));
var _http = _interopRequireDefault(require("../../../_util/http"));
var _analysisLayer = _interopRequireDefault(require("../../../analysis-layer"));
var _Draw = _interopRequireDefault(require("../../Utils/Draw"));
var _Polygon = require("ol/geom/Polygon");
require("./index.less");
var _classnames = _interopRequireDefault(require("classnames"));
var _useProps2 = _interopRequireDefault(require("../../../use-props"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
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; }
var CONFIG = {
  '1': {
    name: '数值',
    operator: ['=', '>', '<', '>=', '<=']
  },
  '2': {
    name: '字符串',
    operator: ['=', '包含']
  },
  '3': {
    name: '枚举',
    operator: ['=', '包含']
  },
  '4': {
    name: '布尔',
    operator: ['=']
  }
};
var LAYER = {
  GSGW: {
    label: '供水管线',
    value: 'GSGW',
    table_name: 'zhsw_water_supply_line',
    layer: 'zhsw:putian_water_supply_line'
  },
  WSGX: {
    label: '污水管线',
    value: 'WSGX',
    table_name: 'zhsw_line',
    layer: 'zhsw:putian_ws_line'
  },
  GSGD: {
    label: '供水管点',
    value: 'GSGD',
    table_name: 'zhsw_water_supply_point',
    layer: 'zhsw:putian_water_supply_point'
  },
  WSGD: {
    label: '污水管点',
    value: 'WSGD',
    table_name: 'zhsw_point',
    layer: 'zhsw:putian_ws_point'
  }
};
// 数据转条件
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, "%'");
        }
      }
      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(_antd.Select, {
    status: status,
    value: value,
    style: {
      width: '100%'
    },
    onChange: onChange,
    options: options
  });
};

// 操作符
var Operator = function Operator(props) {
  var value = props.value,
    options = props.options,
    status = props.status,
    onChange = props.onChange;
  return /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    value: value,
    status: status,
    style: {
      width: '100%'
    },
    onChange: onChange,
    options: options
  });
};

// 值
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(_antd.Select, {
      status: status,
      value: value,
      mode: operator === '包含' ? 'multiple' : null,
      style: {
        width: '100%'
      },
      onChange: _onChange,
      options: options
    });
  }
  if (type === '4') {
    return /*#__PURE__*/_react["default"].createElement(_antd.Select, {
      status: status,
      value: value,
      style: {
        width: '100%'
      },
      onChange: _onChange,
      options: [{
        label: '否',
        value: 0
      }, {
        label: '是',
        value: 1
      }]
    });
  }
  return /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    value: value,
    status: status,
    onChange: function onChange(e) {
      return _onChange(e.target.value);
    }
  });
};
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) {
      var _layerList$find = layerList.find(function (v) {
          return v.value === layerKey;
        }),
        table_name = _layerList$find.table_name;
      getColumnRelationByTableName(table_name);
    }
  }, [layerKey]);
  var getColumnRelationByTableName = function getColumnRelationByTableName(tableName) {
    var url = "/cloud/zhsw-jcss/api/tableColumnRelation/getColumnRelationByTableName";
    var params = {
      tableName: tableName
    };
    _http["default"].get(url, {
      body: params
    }).then(function (res) {
      var _res$data;
      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
          });
        });
      }
      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) {
      var cql_filter = dataToCQLFilter(dataSource, whereValue);
      onAnalysis(cql_filter);
    } else {
      _antd.message.info('查询条件存在空项');
    }
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('space-query-row')
  }, /*#__PURE__*/_react["default"].createElement(_RequiredLabel["default"], {
    label: "\u6761\u4EF6\u5173\u7CFB"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Radio.Group, {
    style: {
      paddingLeft: 6
    },
    onChange: function onChange(e) {
      return setWhereValue(e.target.value);
    },
    value: whereValue
  }, /*#__PURE__*/_react["default"].createElement(_antd.Radio, {
    value: "and"
  }, "\u5E76\u4E14"), /*#__PURE__*/_react["default"].createElement(_antd.Radio, {
    value: "or"
  }, "\u6216\u8005"))), /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    type: "primary",
    onClick: onFinish
  }, "\u67E5\u8BE2")), /*#__PURE__*/_react["default"].createElement(_antd.Table, {
    className: (0, _classnames["default"])('space-query-table'),
    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: 100,
      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: 50,
      align: 'left',
      render: function render(_, _2, index) {
        return /*#__PURE__*/_react["default"].createElement(_antd.Button, {
          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");
    }
  }));
};
function _default(props) {
  var onClose = props.onClose;
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var _useState7 = (0, _react.useState)(''),
    _useState8 = _slicedToArray(_useState7, 2),
    layerKey = _useState8[0],
    setLayerKey = _useState8[1];
  var _useState9 = (0, _react.useState)(''),
    _useState0 = _slicedToArray(_useState9, 2),
    toolsKey = _useState0[0],
    setToolsKey = _useState0[1];
  var _useState1 = (0, _react.useState)(false),
    _useState10 = _slicedToArray(_useState1, 2),
    loading = _useState10[0],
    setLoading = _useState10[1];
  var _useState11 = (0, _react.useState)([]),
    _useState12 = _slicedToArray(_useState11, 2),
    dataSource = _useState12[0],
    setDataSource = _useState12[1];
  var _useState13 = (0, _react.useState)([]),
    _useState14 = _slicedToArray(_useState13, 2),
    layerList = _useState14[0],
    setLayerList = _useState14[1];
  var analysisLayer = (0, _react.useRef)();
  var drawRef = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    onLayerInit();
    map.on('loadstart', function () {
      onLayerInit();
    });
    analysisLayer.current = new _analysisLayer["default"]({
      map: map,
      layerName: 'zhsw:putian_network_access_enterprise'
    });
    drawRef.current = new _Draw["default"]({
      map: map
    });
    return function () {
      analysisLayer.current.destroy();
      drawRef.current.destroy();
    };
  }, []);
  var onLayerInit = function onLayerInit() {
    var _layerList = [];
    map.getAllLayers().map(function (layer) {
      if (layer.key && LAYER[layer.key]) {
        _layerList.push(LAYER[layer.key]);
      }
    });
    setLayerList(_layerList);
  };
  var onLayerChange = function onLayerChange(key) {
    setLayerKey(key);
  };
  var onToolsChange = function onToolsChange(key) {
    drawRef.current.drawType = key;
    setToolsKey(key);
  };
  var onAnalysis = function onAnalysis(cql_filter) {
    if (!layerKey) {
      return _antd.message.info('请选择查询图层');
    }
    var features = drawRef.current.source.getFeatures();
    if (!(features !== null && features !== void 0 && features.length)) {
      return _antd.message.info('请绘制查询范围');
    }
    var geometry = features[0].getGeometry();
    var coorStr = '';
    var coordinates = geometry.getCoordinates();

    // 圈选处理
    if (toolsKey === '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]);
      }
    });
    setLoading(true);
    var _layerList$find2 = layerList.find(function (v) {
        return v.value === layerKey;
      }),
      layer = _layerList$find2.layer;
    var params = {
      typeName: layer,
      layers: layer,
      QUERY_LAYERS: layer,
      cql_filter: "".concat(cql_filter, " and INTERSECTS(geo_location, POLYGON((").concat(coorStr, ")))")
    };
    analysisLayer.current.setLayerData(params).then(function (data) {
      setDataSource(data);
      setLoading(false);
    });
  };
  return /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: "\u7A7A\u95F4\u5B9A\u4F4D\u67E5\u8BE2",
    onClose: onClose,
    width: 500
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('space-query-row')
  }, /*#__PURE__*/_react["default"].createElement(_Select["default"], {
    options: layerList,
    title: "\u56FE\u5C42\u9009\u62E9",
    value: layerKey,
    onChange: onLayerChange
  }), /*#__PURE__*/_react["default"].createElement(_ToolsSelect["default"], {
    title: "\u5730\u56FE\u9009\u62E9",
    value: toolsKey,
    onChange: onToolsChange,
    options: [{
      label: '框选',
      key: 'DragBox',
      isActive: false,
      icon: 'icon-kuangxuan'
    }, {
      label: '圈选',
      key: 'Circle',
      isActive: false,
      icon: 'icon-quanxuan'
    }, {
      label: '多边形选择',
      key: 'Polygon',
      isActive: false,
      icon: 'icon-duobianxingxuanze'
    }]
  })), /*#__PURE__*/_react["default"].createElement(_antd.Tabs, null, /*#__PURE__*/_react["default"].createElement(_antd.Tabs.TabPane, {
    tab: "\u67E5\u8BE2\u6761\u4EF6",
    key: "1"
  }, /*#__PURE__*/_react["default"].createElement(Table, {
    map: map,
    layerKey: layerKey,
    layerList: layerList,
    onAnalysis: onAnalysis
  })), /*#__PURE__*/_react["default"].createElement(_antd.Tabs.TabPane, {
    tab: "\u67E5\u8BE2\u7ED3\u679C",
    key: "2"
  }, /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    columns: [{
      title: '编码',
      dataIndex: ['values_', 'code'],
      width: 100,
      render: function render(text) {
        return /*#__PURE__*/_react["default"].createElement("a", {
          onClick: function onClick() {
            return analysisLayer.current.setCenterByCode(text);
          }
        }, text);
      }
    }],
    loading: loading,
    dataSource: dataSource,
    scroll: {
      y: map.getViewport().clientHeight - 330
    }
  }))));
}
//# sourceMappingURL=index.js.map
