"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 _antd = require("antd");
var _icons = require("@ant-design/icons");
var _Table = _interopRequireDefault(require("../../components/Table"));
var _Modal = _interopRequireDefault(require("../../components/Modal"));
var _layer = require("../../../_util/layer");
var _layer2 = require("ol/layer");
var _Polygon = require("ol/geom/Polygon");
var _Draw = _interopRequireDefault(require("../../Utils/Draw"));
require("./index.less");
var _useProps3 = _interopRequireDefault(require("../../../use-props"));
var _classnames2 = _interopRequireDefault(require("classnames"));
var _ahooks = require("ahooks");
var _ImageLayer = require("../../../image-layer/ImageLayer");
var _turf = require("@turf/turf");
var _Info = _interopRequireDefault(require("../../components/Info"));
var _Chart = _interopRequireDefault(require("../../components/Chart"));
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 && {}.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 _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 _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 : 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(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; } /*
 * @Description:框选、圈选、多边形选择
 */
var classPrefix = 'selectTools';
var getFeatureIntersects = function getFeatureIntersects(polygon, feature) {
  var _feature$getGeometry, _feature$getGeometry2, _feature$getGeometry3, _lngLat$;
  var lngLat = feature === null || feature === void 0 || (_feature$getGeometry = feature.getGeometry()) === null || _feature$getGeometry === void 0 ? void 0 : _feature$getGeometry.getCoordinates();
  var poly = (0, _turf.polygon)(polygon.getCoordinates());
  var pt;
  var B = false;
  if ((feature === null || feature === void 0 || (_feature$getGeometry2 = feature.getGeometry()) === null || _feature$getGeometry2 === void 0 ? void 0 : _feature$getGeometry2.getType()) === 'Point') {
    lngLat.map(function (v) {
      return Number(v);
    });
    pt = (0, _turf.point)(lngLat);
    // 判断在点在多边形内
    if (poly && pt) {
      var intersects = (0, _turf.booleanPointInPolygon)(pt, poly);
      if (intersects) {
        B = true;
      }
    }
  }
  if ((feature === null || feature === void 0 || (_feature$getGeometry3 = feature.getGeometry()) === null || _feature$getGeometry3 === void 0 ? void 0 : _feature$getGeometry3.getType()) === 'Polygon' && lngLat !== null && lngLat !== void 0 && (_lngLat$ = lngLat[0]) !== null && _lngLat$ !== void 0 && _lngLat$.length) {
    var _lngLat$2;
    lngLat === null || lngLat === void 0 || lngLat[0].map(function (v) {
      return Number(v);
    });
    lngLat === null || lngLat === void 0 || (_lngLat$2 = lngLat[0]) === null || _lngLat$2 === void 0 || _lngLat$2.map(function (item) {
      pt = (0, _turf.point)(item);
      if (poly && pt) {
        var _intersects = (0, _turf.booleanPointInPolygon)(pt, poly);
        if (_intersects) {
          B = true;
        }
      }
    });
  }
  return B;
};
var LayerSelect = function LayerSelect(props) {
  var _list;
  var _props$options = props.options,
    options = _props$options === void 0 ? [] : _props$options,
    value = props.value,
    onChange = props.onChange,
    currentKey = props.currentKey;
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = (0, _react.useState)(value),
    _useState4 = _slicedToArray(_useState3, 2),
    active = _useState4[0],
    setActive = _useState4[1];
  var time = (0, _react.useRef)();
  (0, _ahooks.useUpdateEffect)(function () {
    setActive(value);
  }, [value]);
  if (!(options !== null && options !== void 0 && options.length)) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
  }
  var showOpen = (options === null || options === void 0 ? void 0 : options.length) > 9;
  var list = options;
  if (options !== null && options !== void 0 && options.length) {
    if (!open) {
      if (options.length > 9) {
        list = options.slice(0, 9);
      }
    } else {
      list = options;
    }
  }
  var _onClick = function onClick(value) {
    setActive(value);
    currentKey.current = value;
    if (time.current) {
      clearTimeout(time.current);
    }
    time.current = setTimeout(function () {
      onChange === null || onChange === void 0 || onChange(value);
    }, 500);
  };
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])("".concat(classPrefix, "-layer-select"), {
      'selectTools-layer-select-scroll': open
    })
  }, /*#__PURE__*/_react["default"].createElement(_antd.Space, {
    size: [8, 8],
    wrap: true
  }, ((_list = list) === null || _list === void 0 ? void 0 : _list.length) > 0 && list.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      className: (0, _classnames2["default"])("".concat(classPrefix, "-layer-select-item"), _defineProperty({}, "".concat(classPrefix, "-layer-select-item-active"), active === item.value)),
      onClick: function onClick() {
        return _onClick(item.value);
      }
    }, item.label);
  })), showOpen && /*#__PURE__*/_react["default"].createElement(_antd.Divider, {
    style: {
      margin: 0
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    icon: open ? /*#__PURE__*/_react["default"].createElement(_icons.VerticalAlignTopOutlined, null) : /*#__PURE__*/_react["default"].createElement(_icons.VerticalAlignBottomOutlined, null),
    onClick: function onClick() {
      return setOpen(!open);
    },
    type: "link"
  }, open ? '收起' : '展开')));
};
var TableView = function TableView(props) {
  var dataSource = props.dataSource,
    otherColumns = props.columns,
    info = props.info;
  var _useProps = (0, _useProps3["default"])(),
    map = _useProps.map;
  var _useState5 = (0, _react.useState)(true),
    _useState6 = _slicedToArray(_useState5, 2),
    open = _useState6[0],
    setOpen = _useState6[1];
  var columns = [{
    title: '编码/名称',
    dataIndex: 'NAME',
    width: 180,
    render: function render(text, record) {
      return /*#__PURE__*/_react["default"].createElement("a", {
        onClick: function onClick() {
          var _map$getViewport;
          var doc = document.getElementsByClassName('ol-map-tools')[0];
          var rect = doc === null || doc === void 0 ? void 0 : doc.getBoundingClientRect();
          var parentRect = (_map$getViewport = map.getViewport()) === null || _map$getViewport === void 0 ? void 0 : _map$getViewport.getBoundingClientRect();
          var left = 400;
          if (rect && parentRect) {
            left = (rect === null || rect === void 0 ? void 0 : rect.left) - (parentRect === null || parentRect === void 0 ? void 0 : parentRect.left) + 12 + 350 + 150;
          }
          map.showTemplate(record.feature, {
            fitViewOptions: {
              padding: [100, 400, 100, left]
            }
          });
        }
      }, text);
    }
  }].concat(_toConsumableArray(otherColumns || []));
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      minHeight: 20
    }
  }, open && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, info, /*#__PURE__*/_react["default"].createElement(_Table["default"], {
    rowKey: "code",
    dataSource: dataSource,
    columns: columns,
    size: "small"
  }))), (dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) > 0 && /*#__PURE__*/_react["default"].createElement("div", {
    className: "ol-map-search-result-button",
    onClick: function onClick() {
      return setOpen(!open);
    }
  }, open ? '收起' : '展开', open ? /*#__PURE__*/_react["default"].createElement(_icons.CaretUpOutlined, null) : /*#__PURE__*/_react["default"].createElement(_icons.CaretDownOutlined, null)));
};
var TYPE = [{
  label: '表格',
  value: 'table',
  icon: /*#__PURE__*/_react["default"].createElement(_icons.TableOutlined, null)
}, {
  label: '柱状图',
  value: 'bar',
  icon: /*#__PURE__*/_react["default"].createElement(_icons.BarChartOutlined, null)
}, {
  label: '折线图',
  value: 'line',
  icon: /*#__PURE__*/_react["default"].createElement(_icons.LineChartOutlined, null)
}, {
  label: '饼图',
  value: 'pie',
  icon: /*#__PURE__*/_react["default"].createElement(_icons.PieChartOutlined, null)
}];
var ChartView = function ChartView(props) {
  var type = props.type,
    data = props.data;
  return /*#__PURE__*/_react["default"].createElement(_Chart["default"], {
    style: {
      height: 300
    },
    yAxis: {
      show: type !== 'pie',
      name: "条"
    },
    legend: {
      show: false
    },
    xAxis: {
      show: type !== 'pie',
      field: 'name'
    },
    unit: "\u6761",
    series: [_objectSpread({
      type: type,
      name: '管线',
      radius: ['30%', '50%'],
      center: ['50%', '50%']
    }, type === 'pie' ? {
      data: data,
      label: {
        show: true,
        position: 'outside',
        formatter: '{b}\n{c}条'
      }
    } : {
      field: 'value',
      label: {
        show: true,
        position: 'top',
        formatter: '{c}条'
      }
    })],
    data: data
  });
};
var PipeDataView = function PipeDataView(props) {
  var _TYPE$;
  var dataSource = props.dataSource;
  var _useState7 = (0, _react.useState)((_TYPE$ = TYPE[0]) === null || _TYPE$ === void 0 ? void 0 : _TYPE$.value),
    _useState8 = _slicedToArray(_useState7, 2),
    type = _useState8[0],
    setType = _useState8[1];
  var chartData = (0, _react.useMemo)(function () {
    var data = [{
      name: '50mm以下',
      value: 0,
      filter: function filter(item) {
        return item.ds < 50;
      }
    }, {
      name: '50-100mm',
      value: 0,
      filter: function filter(item) {
        return item.ds >= 50 && item.ds < 100;
      }
    }, {
      name: '100-300mm',
      value: 0,
      filter: function filter(item) {
        return item.ds >= 100 && item.ds < 300;
      }
    }, {
      name: '300-600mm',
      value: 0,
      filter: function filter(item) {
        return item.ds >= 300 && item.ds < 600;
      }
    }, {
      name: '600-1000mm',
      value: 0,
      filter: function filter(item) {
        return item.ds >= 600 && item.ds < 1000;
      }
    }, {
      name: '1000mm以上',
      value: 0,
      filter: function filter(item) {
        return item.ds >= 1000;
      }
    }];
    dataSource.map(function (item) {
      item.ds = item.ds ? Number(item.ds) : 0;
      data.map(function (d) {
        if (d.filter(item)) {
          d.value += 1;
        }
      });
    });
    return data.filter(function (v) {
      return v.value > 0;
    });
  }, [dataSource]);
  var columns = [{
    title: '长度(m)',
    dataIndex: 'lineLength',
    width: 100
  }];
  var totalLength = 0;
  if (dataSource !== null && dataSource !== void 0 && dataSource.length) {
    totalLength = dataSource.reduce(function (prev, cur) {
      return prev + (cur['lineLength'] || 0);
    }, 0) / 1000;
  }
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_antd.Segmented, {
    options: TYPE,
    value: type,
    onChange: setType
  }), type === 'table' ? /*#__PURE__*/_react["default"].createElement(TableView, {
    columns: columns,
    dataSource: dataSource,
    info: /*#__PURE__*/_react["default"].createElement(_Info["default"], {
      list: [{
        label: '管线总数',
        value: (dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) || 0,
        unit: '条'
      }, {
        label: '管线总长',
        value: totalLength ? Number(totalLength).toFixed(2) : totalLength,
        unit: 'km'
      }]
    })
  }) : /*#__PURE__*/_react["default"].createElement(ChartView, {
    data: chartData,
    type: type
  }));
};
var DEVICE_STATUS_NAME = {
  1: {
    label: '在线',
    color: '#119FFB'
  },
  // 正常/在线
  2: {
    label: '报警',
    color: '#CE3739'
  },
  // 报警/异常
  3: {
    label: '离线',
    color: '#AAAAAD'
  },
  // 离线
  4: {
    label: '故障',
    color: '#CE3739'
  } // 故障/堵塞
};
var DeviceInfo = function DeviceInfo(props) {
  var data = props.data;
  var list = (0, _react.useMemo)(function () {
    var val = {};
    data.map(function (item) {
      var deviceValues = item.deviceValues;
      if (deviceValues !== null && deviceValues !== void 0 && deviceValues.length) {
        deviceValues.map(function (device) {
          var factorValues = device.factorValues;
          if (factorValues !== null && factorValues !== void 0 && factorValues.length) {
            factorValues.map(function (factor) {
              var monitorItemName = factor.monitorItemName,
                formatValue = factor.formatValue,
                unit = factor.unit,
                collectFrequency = factor.collectFrequency;
              if (collectFrequency === 'realtime' && formatValue) {
                val[monitorItemName] = val[monitorItemName] || {
                  name: monitorItemName,
                  unit: unit,
                  data: []
                };
                val[monitorItemName].data.push(Number(formatValue));
              }
            });
          }
        });
      }
    });
    var dataVal = [];
    for (var i in val) {
      var _data = val[i].data;
      var maxValue = Math.max.apply(Math, _toConsumableArray(_data));
      var minValue = Math.min.apply(Math, _toConsumableArray(_data));
      var avgValue = _data.reduce(function (prev, cur) {
        return prev + cur;
      }, 0) / _data.length;
      dataVal.push(_objectSpread(_objectSpread({}, val[i]), {}, {
        maxValue: maxValue,
        minValue: minValue,
        avgValue: avgValue ? Number(avgValue).toFixed(2) : avgValue
      }));
    }
    return dataVal;
  }, [data === null || data === void 0 ? void 0 : data.length]);
  if (!(list !== null && list !== void 0 && list.length)) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])("".concat(classPrefix, "-device"))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])("".concat(classPrefix, "-device-top"))
  }, /*#__PURE__*/_react["default"].createElement("div", null, "\u76D1\u6D4B\u9879"), /*#__PURE__*/_react["default"].createElement("div", null, "\u6700\u5927\u503C"), /*#__PURE__*/_react["default"].createElement("div", null, "\u6700\u5C0F\u503C"), /*#__PURE__*/_react["default"].createElement("div", null, "\u5E73\u5747\u503C")), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames2["default"])("".concat(classPrefix, "-device-content"))
  }, (list === null || list === void 0 ? void 0 : list.length) > 0 && list.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      className: (0, _classnames2["default"])("".concat(classPrefix, "-device-content-item"))
    }, /*#__PURE__*/_react["default"].createElement("div", null, item.name), /*#__PURE__*/_react["default"].createElement("div", null, item.maxValue, /*#__PURE__*/_react["default"].createElement("span", null, item.unit)), /*#__PURE__*/_react["default"].createElement("div", null, item.minValue, /*#__PURE__*/_react["default"].createElement("span", null, item.unit)), /*#__PURE__*/_react["default"].createElement("div", null, item.avgValue, /*#__PURE__*/_react["default"].createElement("span", null, item.unit)));
  })));
};
var DeviceDataView = function DeviceDataView(props) {
  var dataSource = props.dataSource;
  var _useState9 = (0, _react.useState)(null),
    _useState10 = _slicedToArray(_useState9, 2),
    filter = _useState10[0],
    setFilter = _useState10[1];
  var columns = [{
    title: '状态',
    dataIndex: 'status',
    width: 100,
    render: function render(text) {
      if (DEVICE_STATUS_NAME[text]) {
        var _DEVICE_STATUS_NAME$t = DEVICE_STATUS_NAME[text],
          color = _DEVICE_STATUS_NAME$t.color,
          label = _DEVICE_STATUS_NAME$t.label;
        return /*#__PURE__*/_react["default"].createElement("span", {
          style: {
            color: color
          }
        }, label);
      }
      return '-';
    }
  }];
  var tableData = (0, _react.useMemo)(function () {
    return filter ? dataSource.filter(function (item) {
      return Number(item.status) === filter;
    }) : dataSource;
  }, [filter, dataSource === null || dataSource === void 0 ? void 0 : dataSource.length]);
  var getTotal = function getTotal(value) {
    return dataSource.filter(function (item) {
      return Number(item.status) === value;
    }).length;
  };
  return /*#__PURE__*/_react["default"].createElement(TableView, {
    columns: columns,
    dataSource: tableData,
    info: /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_Info["default"], {
      list: [{
        label: '总数',
        value: (dataSource === null || dataSource === void 0 ? void 0 : dataSource.length) || 0,
        unit: '个',
        onClick: function onClick() {
          return setFilter(null);
        }
      }, {
        label: '在线',
        value: getTotal(1),
        unit: '个',
        onClick: function onClick() {
          return setFilter(1);
        }
      }, {
        label: '报警',
        value: getTotal(2),
        unit: '个',
        onClick: function onClick() {
          return setFilter(2);
        }
      }, {
        label: '离线',
        value: getTotal(3),
        unit: '个',
        onClick: function onClick() {
          return setFilter(3);
        }
      }]
    }), /*#__PURE__*/_react["default"].createElement(DeviceInfo, {
      data: dataSource
    }))
  });
};
var _default = exports["default"] = function _default(props) {
  var onClose = props.onClose,
    drawType = props.drawType,
    title = props.title,
    renderTableActive = props.renderTableActive,
    statistic = props.statistic;
  var _useProps2 = (0, _useProps3["default"])(),
    map = _useProps2.map;
  var _useState11 = (0, _react.useState)(''),
    _useState12 = _slicedToArray(_useState11, 2),
    currentLayerKey = _useState12[0],
    setCurrentLayerKey = _useState12[1];
  var _useState13 = (0, _react.useState)([]),
    _useState14 = _slicedToArray(_useState13, 2),
    dataSource = _useState14[0],
    setDataSource = _useState14[1];
  var _useState15 = (0, _react.useState)(false),
    _useState16 = _slicedToArray(_useState15, 2),
    loading = _useState16[0],
    setLoading = _useState16[1];
  var _useState17 = (0, _react.useState)([]),
    _useState18 = _slicedToArray(_useState17, 2),
    layersOpts = _useState18[0],
    setLayersOpts = _useState18[1];
  var _useState19 = (0, _react.useState)({}),
    _useState20 = _slicedToArray(_useState19, 2),
    feature = _useState20[0],
    setFeature = _useState20[1];
  var draw = (0, _react.useRef)();
  var currentKey = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    onClick();
  }, [currentLayerKey, JSON.stringify(feature), layersOpts]);
  (0, _react.useEffect)(function () {
    var layersChange = function layersChange() {
      getOptions();
    };
    layersChange();

    // 添加图层变化监听事件
    map.layers.on('change', layersChange);
    return function () {
      // 移除图层变化监听事件
      map.layers.un('change', layersChange);
    };
  }, []);
  (0, _react.useEffect)(function () {
    draw.current = new _Draw["default"]({
      map: map,
      zIndex: 80
    });
    draw.current.draw(drawType, function (feature) {
      setFeature(feature);
    });
    return function () {
      draw.current.destroy();
      map.hideTemplate();
      currentKey.current = null;
    };
  }, []);
  var getOptions = function getOptions() {
    if (map) {
      var _opts$;
      var opts = [];
      var layers = map.getAllLayers().filter(function (v) {
        return !v.viewOnly && v.key && v.name && v.layerControl && v.show;
      });
      layers.map(function (v) {
        opts.push(_objectSpread(_objectSpread({}, v), {}, {
          value: v.key,
          label: v.name
        }));
      });

      // 当前key对应的图层还显示的话取当前的key否者取第一个layersOpts的key
      var _key = opts === null || opts === void 0 || (_opts$ = opts[0]) === null || _opts$ === void 0 ? void 0 : _opts$.value;
      if (currentKey.current) {
        var layer = map.layers.getLayerByKey(currentKey.current);
        if (layer && layer !== null && layer !== void 0 && layer.show) {
          _key = currentKey.current;
        }
      }
      currentKey.current = _key;
      setCurrentLayerKey(_key);
      setLayersOpts(opts);
    }
  };
  var onClick = function onClick() {
    var _feature$getGeometry4;
    setDataSource([]);
    if (!feature) return;
    var geometry = feature === null || feature === void 0 || (_feature$getGeometry4 = feature.getGeometry) === null || _feature$getGeometry4 === void 0 ? void 0 : _feature$getGeometry4.call(feature);
    if (!geometry) return;
    setLoading(true);
    var layer = map.layers.getLayerByKey(currentLayerKey);
    if (geometry && currentLayerKey && layer) {
      var tableData = [];
      // wms图层
      if (layer instanceof _layer2.Image) {
        getWmsData(geometry, layer, tableData);
      } else if (layer instanceof _layer2.Vector) {
        getWfsData(geometry, layer, tableData);
      }
    } else {
      setLoading(false);
      if (!geometry) {
        _antd.message.destroy();
        _antd.message.info('请先框选图层', 2);
      }
      if (!currentLayerKey) {
        _antd.message.destroy();
        _antd.message.info('请先选择图层', 2);
      }
    }
  };

  /**
   * @description: wfs图层时获取框选数据
   * @param {*} geometry
   * @param {*} layer
   * @param {*} tableData
   * @return {*}
   */
  var getWfsData = function getWfsData(geometry, layer, tableData) {
    var extent = geometry.getExtent();
    var source = layer.getSource();
    var features = [];
    var getFeatureInfo = function getFeatureInfo(feature) {
      var listKeys = feature.getKeys();
      var data = {};
      listKeys.forEach(function (item) {
        if (feature.get(item)) {
          data[item] = feature.get(item);
          if (layer.labelField) {
            data.NAME = feature.get(layer.labelField);
          }
          data.feature = feature;
        }
      });
      return data;
    };
    if (source.forEachFeatureIntersectingExtent && extent) {
      source.forEachFeatureIntersectingExtent(extent, function (feature) {
        var featureList = feature.get('features');
        var addTableData = function addTableData(f) {
          var data = getFeatureInfo(f);
          tableData.push(data);
          features.push(f);
        };
        if ((featureList === null || featureList === void 0 ? void 0 : featureList.length) > 1) {
          featureList.forEach(function (f) {
            // 圈选处理
            if (drawType === 'Circle') {
              var polygonGeometry = new _Polygon.fromCircle(geometry);
              var featureIntersects = getFeatureIntersects(polygonGeometry, f);
              if (!featureIntersects) {
                return;
              }
            }
            addTableData(f);
          });
        } else {
          // 圈选处理
          if (drawType === 'Circle') {
            var polygonGeometry = new _Polygon.fromCircle(geometry);
            var featureIntersects = getFeatureIntersects(polygonGeometry, feature);
            if (!featureIntersects) {
              return;
            }
          }
          addTableData(feature);
        }
      });
      setLoading(false);
      map.setHighlightFeature(features);
      setDataSource(tableData);
    } else {
      setLoading(false);
    }
  };

  /**
   * @description: wms图层时获取框选数据
   * @return {*}
   */
  var getWmsData = function getWmsData(geometry, layer, tableData) {
    var _layer$group;
    var _filter = '';
    if (layer !== null && layer !== void 0 && (_layer$group = layer.group) !== null && _layer$group !== void 0 && _layer$group.length) {
      _filter = (0, _ImageLayer.getFilter)(layer.group);
    }
    var coorStr = '';
    var coordinates = geometry.getCoordinates();

    // 圈选处理
    if (drawType === '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]);
      }
    });
    // 增加图层的其他过滤
    var filter = _filter ? "(".concat(_filter, ") and ") : '';
    (0, _layer.getWFSFeatureInfoByLayer)(layer, "".concat(filter, "INTERSECTS(geo_location, POLYGON((").concat(coorStr, ")))")).then(function (features) {
      setLoading(false);
      map.setHighlightFeature(features);
      if (features !== null && features !== void 0 && features.length) {
        features.forEach(function (item) {
          var listKeys = item.getKeys();
          var data = {};
          listKeys.forEach(function (key) {
            if (item.get(key)) {
              data[key] = item.get(key);
              data.feature = item;
            }
          });
          if (layer.labelField) {
            data.NAME = item.get(layer.labelField) || '';
          }

          // 处理管线长度字段
          if (data.line_length) {
            data.lineLength = data.lineLength || data.line_length;
          }
          tableData.push(data);
        });
        setDataSource(tableData);
      } else {
        _antd.message.destroy();
        _antd.message.info('暂无数据', 2);
      }
    });
  };

  // 判断是否是设备图层
  var isDeviceLayer = (0, _react.useMemo)(function () {
    var _layer$params, _layer$url;
    var layer = map === null || map === void 0 ? void 0 : map.getLayerByKey(currentLayerKey);
    var deviceTypeId = layer === null || layer === void 0 || (_layer$params = layer.params) === null || _layer$params === void 0 ? void 0 : _layer$params.deviceTypeId;
    var url = (layer === null || layer === void 0 || (_layer$url = layer.url) === null || _layer$url === void 0 ? void 0 : _layer$url.indexOf('/cloud/device/deviceMap/list')) !== -1;
    return Boolean(deviceTypeId && url);
  }, [currentLayerKey]);

  // 判断是否是管线图层
  var isPipeLineLayer = currentLayerKey && currentLayerKey.toUpperCase().indexOf('LINE') !== -1;
  return /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: title || '',
    onClose: onClose,
    width: 300
  }, /*#__PURE__*/_react["default"].createElement(_antd.Spin, {
    spinning: loading
  }, /*#__PURE__*/_react["default"].createElement(LayerSelect, {
    options: layersOpts,
    value: currentLayerKey,
    onChange: setCurrentLayerKey,
    currentKey: currentKey
  }), renderTableActive && renderTableActive(dataSource, currentLayerKey, onClick), statistic ? isPipeLineLayer ? /*#__PURE__*/_react["default"].createElement(PipeDataView, {
    dataSource: dataSource
  }) : isDeviceLayer ? /*#__PURE__*/_react["default"].createElement(DeviceDataView, {
    dataSource: dataSource
  }) : /*#__PURE__*/_react["default"].createElement(TableView, {
    dataSource: dataSource
  }) : /*#__PURE__*/_react["default"].createElement(TableView, {
    dataSource: dataSource
  })));
};
//# sourceMappingURL=index.js.map
