"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 _propTypes = _interopRequireDefault(require("prop-types"));
var _useProps2 = _interopRequireDefault(require("@vtx/ol-map/lib/use-props"));
var _olMapLayer = require("@vtx/ol-map-layer");
var _request = _interopRequireDefault(require("../_mapUtil/request"));
var _utils = require("@vtx/utils");
var _analysisGroup = _interopRequireDefault(require("../analysis-group"));
var _analysisLayer = _interopRequireDefault(require("../analysis-layer"));
var _config = _interopRequireDefault(require("../_mapUtil/config"));
var _style = require("ol/style");
var _index = require("../index");
var _transform = require("./transform");
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; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
var AnalysisComponents = {
  BufferAnalysis: _index.BufferAnalysis,
  MacrotubuleDiagnosis: _index.MacrotubuleDiagnosis,
  ConnectivityAnalysis: _index.ConnectivityAnalysis,
  FlowAnomalyDiagnosis: _index.FlowAnomalyDiagnosis,
  InverseSlopeDiagnosis: _index.InverseSlopeDiagnosis,
  FlowDirectionAnalysis: _index.FlowDirectionAnalysis,
  IsolatedRegionDiagnosis: _index.IsolatedRegionDiagnosis,
  RingNetworkDiagnosis: _index.RingNetworkDiagnosis,
  CrossSectionAnalysis: _index.CrossSectionAnalysis,
  ProfileAnalysis: _index.ProfileAnalysis,
  SoilCoverAnalysis: _index.SoilCoverAnalysis,
  CollisionAnalysis: _index.CollisionAnalysis,
  ShortestPath: _index.ShortestPath,
  FacilitySearch: _index.FacilitySearch,
  IntersectionQuery: _index.IntersectionQuery,
  RoadQuery: _index.RoadQuery,
  AttributeQuery: _index.AttributeQuery,
  BlowoutValveClosingAnalysis: _index.BlowoutValveClosingAnalysis,
  PipelineNetworkStatistics: _index.PipelineNetworkStatistics,
  TrackingAnalysis: _index.TrackingAnalysis,
  AgeWarning: _index.AgeWarning,
  InflowInfiltrationAnalysis: _index.InflowInfiltrationAnalysis,
  InflowInfiltration: _index.InflowInfiltration,
  SedimentationAnalysis: _index.SedimentationAnalysis,
  RainSewageMixed: _index.RainSewageMixed,
  SedimentationRisk: _index.SedimentationRisk,
  LargeDiameterAnalysis: _index.LargeDiameterAnalysis,
  HydrantAnalysis: _index.HydrantAnalysis,
  ContaminationRangeAnalysis: _index.ContaminationRangeAnalysis,
  PollutionSourceAnalysis: _index.PollutionSourceAnalysis,
  RainSewageMixedAnalysis: _index.RainSewageMixedAnalysis,
  FillingDegreeAnalysis: _index.FillingDegreeAnalysis,
  SewageCollectionRateAnalysis: _index.SewageCollectionRateAnalysis,
  WaterBalanceAnalysis: _index.WaterBalanceAnalysis,
  SewageNetworkCoverage: _index.SewageNetworkCoverage,
  DrainagePollutionSource: _index.DrainagePollutionSource,
  SunnyRainRatio: _index.SunnyRainRatio,
  WaterQualityPrediction: _index.WaterQualityPrediction,
  PipelineNetworkBlockingAnalysis: _index.PipelineNetworkBlockingAnalysis
};
var AnalysisComponent = function AnalysisComponent(props) {
  var activeKey = props.activeKey,
    onClose = props.onClose,
    layersConfig = props.layersConfig;
  if (activeKey && AnalysisComponents[activeKey]) {
    var Component = AnalysisComponents[activeKey];
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, (layersConfig === null || layersConfig === void 0 ? void 0 : layersConfig.length) > 0 && /*#__PURE__*/_react["default"].createElement(Component, _extends({
      onClose: onClose,
      layersConfig: layersConfig
    }, props)));
  }
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
};
AnalysisComponent.propTypes = {
  onClose: _propTypes["default"].func,
  activeKey: _propTypes["default"].string,
  layersConfig: _propTypes["default"].array
};
var Analysis = function Analysis(props) {
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    analysisList = _useState2[0],
    setAnalysisList = _useState2[1];
  var _useState3 = (0, _react.useState)(null),
    _useState4 = _slicedToArray(_useState3, 2),
    activeKey = _useState4[0],
    setActiveKey = _useState4[1];
  var _useState5 = (0, _react.useState)([]),
    _useState6 = _slicedToArray(_useState5, 2),
    layersConfig = _useState6[0],
    setLayersConfig = _useState6[1];
  var layerShowKeysRef = (0, _react.useRef)(null);
  var analysisListRef = (0, _react.useRef)(null);
  var activeKeyRef = (0, _react.useRef)(null);
  (0, _react.useEffect)(function () {
    getConfig();
  }, []);
  var getConfig = function getConfig() {
    var url = "".concat(_config["default"].publicUrlZNFX, "/api/gisAnalyze/getConfig");
    _request["default"].get(url, {
      body: {
        tenantId: (0, _utils.getUrlParam)('tenantId')
      }
    }).then(function (res) {
      if (res.result === 0 && res.data) {
        var _analysisList = (0, _transform.transformConfig)(res.data);
        setAnalysisList(_analysisList);
        analysisListRef.current = _analysisList;
      }
    })["catch"](function () {});
  };

  // 监听选中的key
  (0, _react.useEffect)(function () {
    var activeChange = function activeChange(_activeKey) {
      loadLayersConfig(_activeKey);
    };
    map.analysis.on('activeChange', activeChange);
    return function () {
      map.analysis.un('activeChange', activeChange);
    };
  }, []);

  // 加载相关图层展示
  var loadLayersConfig = function loadLayersConfig(_activeKey) {
    var _layersConfig2;
    // 加载指定图层
    var _layersConfig = [];
    if (_activeKey) {
      var _map$layers;
      // 第一次激活分析工具，暂存当前的图层展示
      if (!activeKeyRef.current) {
        layerShowKeysRef.current = map.layers.getShowKeys();
      }

      // 清空图层展示
      var allKeys = map === null || map === void 0 || (_map$layers = map.layers) === null || _map$layers === void 0 ? void 0 : _map$layers.getAllLayersKeys();
      map.layers.setHideByKeys(allKeys);
      analysisListRef.current.map(function (v) {
        v.children.map(function (c) {
          if (c.key === _activeKey && c.layersConfig) {
            var temp = JSON.parse(c.layersConfig) || [];
            var arr = temp === null || temp === void 0 ? void 0 : temp.map(function (obj) {
              return _objectSpread(_objectSpread({}, obj), {}, {
                valueField: _objectSpread({}, obj)
              });
            });
            _layersConfig = arr;
          }
        });
      });
    } else {
      // 恢复之前的图层展示
      if (layerShowKeysRef.current) {
        map.layers.setShowByKeys(layerShowKeysRef.current);
        layerShowKeysRef.current = null;
      }
    }
    activeKeyRef.current = _activeKey;
    setActiveKey(_activeKey);
    setLayersConfig([]);
    if ((_layersConfig2 = _layersConfig) !== null && _layersConfig2 !== void 0 && _layersConfig2.length) {
      window.setTimeout(function () {
        setLayersConfig(_layersConfig);
      }, 0);
    }
  };
  var onClose = function onClose() {
    map.setAnalysisActiveKey(null);
    try {
      map.hideTemplate();
    } catch (err) {}
  };
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, (layersConfig === null || layersConfig === void 0 ? void 0 : layersConfig.length) > 0 && /*#__PURE__*/_react["default"].createElement(_olMapLayer.Layer, {
    data: layersConfig
    // onClick={e => {
    //     setTimeout(() => {
    //         const layer = map.getLayerByKey('Highlight');
    //         if (layer) {
    //             let source = layer?.getSource();
    //             let features = source.getFeatures();
    //             source.clear();
    //             source.addFeatures(features);
    //             source.getFeatures()?.[0]?.setStyle(
    //                 new Style({
    //                     image: new CircleStyle({
    //                         radius: 7,
    //                         fill: new Fill({
    //                             color: '#1890ff',
    //                         }),
    //                         stroke: new Stroke({
    //                             color: '#FFFFFF',
    //                             width: 2,
    //                         }),
    //                     }),
    //                     fill: new Fill({
    //                         color: '#1890ff',
    //                     }),
    //                     stroke: new Stroke({
    //                         color: '#1890ff',
    //                         width: 4,
    //                     }),
    //                 }),
    //             );
    //         }
    //     });
    // }}
  }), (analysisList === null || analysisList === void 0 ? void 0 : analysisList.length) > 0 && analysisList.map(function (group, groupIndex) {
    return /*#__PURE__*/_react["default"].createElement(_analysisGroup["default"], {
      key: groupIndex,
      id: group.id,
      name: group.label,
      icon: group.icon
    }, group.children.map(function (item, itemIndex) {
      return /*#__PURE__*/_react["default"].createElement(_analysisLayer["default"], _extends({}, item, {
        name: item.label,
        id: item.key,
        key: "".concat(groupIndex, "_").concat(itemIndex)
      }));
    }));
  }), /*#__PURE__*/_react["default"].createElement(AnalysisComponent, _extends({
    onClose: onClose,
    activeKey: activeKey,
    layersConfig: layersConfig
  }, props)));
};
Analysis.propTypes = {};
var _default = exports["default"] = Analysis;
//# sourceMappingURL=index.js.map
