"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = _default;
exports.getTreeData = exports.getIcon = void 0;
var _react = _interopRequireWildcard(require("react"));
var _useProps2 = _interopRequireDefault(require("../use-props"));
var _classnames = _interopRequireDefault(require("classnames"));
var _renderer = require("../renderer");
var _lodash = require("lodash");
var _excluded = ["icon", "text"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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 _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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 _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 _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 _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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var getIcon = function getIcon(v) {
  var _ref = (0, _lodash.isString)(v) ? {
      icon: v
    } : v,
    icon = _ref.icon,
    text = _ref.text,
    other = _objectWithoutProperties(_ref, _excluded);
  return (0, _renderer.getImage)(_objectSpread({
    color: '#007FF9',
    icon: icon,
    hideFooter: true
  }, other));
};
exports.getIcon = getIcon;
var getStyleByObject = function getStyleByObject(_style) {
  var type = _style.type,
    style = _style.style;
  if (type) {
    if (type === 'Marker') {
      return getIcon(style);
    } else if (type === 'Polyline') {
      return getIcon(_objectSpread(_objectSpread({
        icon: 'WS_GW'
      }, _style), {}, {
        type: 'Icon'
      }));
    } else if (type === 'Polygon') {
      return getIcon(_objectSpread(_objectSpread({
        icon: 'AREA'
      }, _style), {}, {
        type: 'Icon'
      }));
    } else {
      return getIcon(_objectSpread({}, _style));
    }
  } else if (_style.icon) {
    return (0, _renderer.getImage)(_objectSpread({
      hideFooter: true
    }, _style));
  } else if (_style.image) {
    return _style.image;
  } else {
    return (0, _renderer.getImage)(_objectSpread({
      hideFooter: true
    }, _style));
  }
};
var getStyle = function getStyle(v) {
  if (v) {
    if ((0, _lodash.isString)(v)) {
      return getIcon(v);
    } else if ((0, _lodash.isObject)(v)) {
      return getStyleByObject(v);
    }
  }
};
var getItem = function getItem(v) {
  var imgList = [];
  if (v.legend) {
    if ((0, _lodash.isArray)(v.legend)) {
      v.legend.map(function (l) {
        var icon = getStyle(l);
        icon && imgList.push(_objectSpread({
          name: l.name,
          src: icon
        }, l));
      });
    } else {
      var icon = getStyle(v.legend);
      var _style = (0, _lodash.isObject)(v.legend) ? v.legend : {};
      icon && imgList.push(_objectSpread({
        name: v.name,
        src: icon
      }, _style));
    }
  } else if (v.style) {
    var style = v.style;
    if ((0, _lodash.isFunction)(v.style)) {
      style = v.style();
    }
    if ((0, _lodash.isString)(style)) {
      var _icon = getStyle(style);
      _icon && imgList.push({
        name: v.name,
        src: _icon
      });
    } else if ((0, _lodash.isObject)(style)) {
      var _icon2 = getStyleByObject(style);
      _icon2 && imgList.push({
        name: v.name,
        src: _icon2
      });
    } else if ((0, _lodash.isArray)(style)) {
      style.map(function (l) {
        var icon = getStyleByObject(l);
        icon && imgList.push({
          name: l.name,
          src: icon
        });
      });
    }
  }
  return imgList;
};
var getTreeData = function getTreeData(data) {
  var imgList = [];
  data.map(function (v) {
    var _v$group;
    if ((_v$group = v.group) !== null && _v$group !== void 0 && _v$group.length) {
      v.group.map(function (r) {
        if (!r.hasOwnProperty('show') || r.show) {
          var items = getItem(r).map(function (c) {
            if (c.name && !c.name.startsWith(v.name)) {
              c.name = "".concat(v.name, "-").concat(c.name);
            }
            return c;
          });
          imgList.push.apply(imgList, _toConsumableArray(items));
        }
      });
    } else if (!v.hasOwnProperty('show') || v.show) {
      imgList.push.apply(imgList, _toConsumableArray(getItem(v)));
    }
  });
  return imgList;
};
exports.getTreeData = getTreeData;
var Content = function Content(props) {
  var _data2, _data3;
  var data = props.data,
    children = props.children,
    column = props.column,
    columLength = props.columLength;
  var _data = [];
  if (data !== null && data !== void 0 && data.length) {
    if (column) {
      _data = (0, _lodash.chunk)(data, Math.ceil(data.length / column));
    } else if ((data === null || data === void 0 ? void 0 : data.length) >= 10) {
      if (columLength) {
        _data = (0, _lodash.chunk)(data, columLength);
      } else {
        // 通过十分位 + 1 得到数组需要分割的数量例如：10 => 2、 20 => 3、 30 => 4
        var num = Number(String(data.length)[0]) + 1;
        _data = (0, _lodash.chunk)(data, Math.ceil(data.length / num));
      }
    } else {
      _data = [data];
    }
  }
  // console.log(111111111, _data);

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-tools-legend-list-wrap')
  }, ((_data2 = _data) === null || _data2 === void 0 ? void 0 : _data2.length) > 0 && /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-tools-legend-list-column'),
    style: ((_data3 = _data) === null || _data3 === void 0 ? void 0 : _data3.length) >= 2 ? {} : {
      maxWidth: 270,
      maxHeight: 270,
      overflowY: 'auto'
    }
  }, _data.map(function (list, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: "".concat(index),
      className: (0, _classnames["default"])('ol-tools-legend-list')
    }, list.map(function (v, i) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        key: "".concat(index, "_").concat(i),
        className: (0, _classnames["default"])('ol-tools-legend-item')
      }, /*#__PURE__*/_react["default"].createElement("img", {
        src: v.src,
        alt: "",
        className: (0, _classnames["default"])('ol-tools-legend-item-img')
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])('ol-tools-legend-item-title')
      }, v.name));
    }));
  })), children);
};
function _default(props) {
  var className = props.className,
    style = props.style,
    extra = props.extra,
    children = props.children,
    content = props.content,
    contentRender = props.contentRender,
    column = props.column,
    columLength = props.columLength;
  var _useProps = (0, _useProps2["default"])(),
    map = _useProps.map;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    treeData = _useState2[0],
    setTreeData = _useState2[1];
  (0, _react.useEffect)(function () {
    var layersChange = function layersChange() {
      var layers = map.getVisibleLayersByKeys();
      setTreeData(getTreeData(layers));
    };
    layersChange();
    map.layers.on('change', layersChange);
    return function () {
      map.layers.un('change', layersChange);
    };
  }, []);
  if (!(treeData !== null && treeData !== void 0 && treeData.length)) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
  }
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, contentRender ? contentRender(treeData) : /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-tools-legend', className),
    style: style
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-tools-legend-content')
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])('ol-tools-legend-title')
  }, /*#__PURE__*/_react["default"].createElement("a", null, "\u56FE\u4F8B")), extra), /*#__PURE__*/_react["default"].createElement(Content, {
    data: treeData,
    column: column,
    columLength: columLength
  }, content), children));
}
//# sourceMappingURL=index.js.map
