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); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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(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 : String(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; }
import React, { useRef, useState, useEffect, useMemo } from 'react';
import { Row, Col } from 'antd';
import classNames from 'classnames';
import "./index.less";
var ARow = Row;
var ACol = Col;
/**
 * 标准化断点配置
 * 将简写形式 { 420: 2 } 转换为完整形式 { 420: { columns: 2 } }
 */
function normalizeBreakpoints(breakpoints, defaultGap) {
  var normalized = {};
  for (var _i = 0, _Object$entries = Object.entries(breakpoints); _i < _Object$entries.length; _i++) {
    var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
      width = _Object$entries$_i[0],
      config = _Object$entries$_i[1];
    var widthNum = Number(width);
    if (typeof config === 'number') {
      // 简写形式：数字表示列数
      normalized[widthNum] = {
        columns: config,
        gap: defaultGap
      };
    } else {
      var _config$gap;
      // 完整形式
      normalized[widthNum] = _objectSpread(_objectSpread({}, config), {}, {
        gap: (_config$gap = config.gap) !== null && _config$gap !== void 0 ? _config$gap : defaultGap
      });
    }
  }
  return normalized;
}

/**
 * 根据 minWidth 和 maxColumns 自动生成断点配置
 */
function generateBreakpoints(minWidth, maxColumns) {
  var gap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16;
  var gapNum = typeof gap === 'number' ? gap : parseInt(gap, 10) || 16;
  var breakpoints = {
    0: {
      columns: 1,
      gap: gap
    }
  };
  for (var cols = 2; cols <= maxColumns; cols++) {
    // 计算需要的最小容器宽度：cols * minWidth + (cols - 1) * gap
    var breakpoint = cols * minWidth + (cols - 1) * gapNum;
    breakpoints[breakpoint] = {
      columns: cols,
      gap: gap
    };
  }
  return breakpoints;
}

/**
 * 根据容器宽度计算当前应该使用的断点配置
 */
function getActiveBreakpoint(width, breakpoints) {
  var defaultColumns = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  var defaultGap = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 16;
  // 获取所有断点并按宽度降序排序
  var sortedBreakpoints = Object.keys(breakpoints).map(Number).sort(function (a, b) {
    return b - a;
  });

  // 找到第一个小于等于当前宽度的断点
  var _iterator = _createForOfIteratorHelper(sortedBreakpoints),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var breakpoint = _step.value;
      if (width >= breakpoint) {
        return breakpoints[breakpoint];
      }
    }

    // 如果没有匹配的断点，返回默认配置
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return {
    columns: defaultColumns,
    gap: defaultGap
  };
}

/**
 * 解析响应式配置，生成最终的断点映射
 */
function parseResponsiveConfig(responsive) {
  var minWidth = responsive.minWidth,
    maxColumns = responsive.maxColumns,
    breakpoints = responsive.breakpoints,
    _responsive$gap = responsive.gap,
    gap = _responsive$gap === void 0 ? 16 : _responsive$gap;
  var finalBreakpoints = {};

  // 方式一：自动计算断点
  if (minWidth && maxColumns) {
    finalBreakpoints = generateBreakpoints(minWidth, maxColumns, gap);
  }

  // 方式二：显式断点定义（会覆盖自动计算的断点）
  if (breakpoints) {
    var normalizedBreakpoints = normalizeBreakpoints(breakpoints, gap);
    finalBreakpoints = _objectSpread(_objectSpread({}, finalBreakpoints), normalizedBreakpoints);
  }

  // 确保至少有默认断点
  if (Object.keys(finalBreakpoints).length === 0) {
    var _responsive$defaultCo;
    finalBreakpoints = {
      0: {
        columns: (_responsive$defaultCo = responsive.defaultColumns) !== null && _responsive$defaultCo !== void 0 ? _responsive$defaultCo : 1,
        gap: gap
      }
    };
  }
  return finalBreakpoints;
}

/**
 * 自定义 Hook：使用 ResizeObserver 监听容器宽度变化
 */
function useContainerWidth(ref) {
  var debounceMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    width = _useState2[0],
    setWidth = _useState2[1];
  var timeoutRef = useRef(null);
  useEffect(function () {
    var element = ref.current;
    if (!element) return;
    var updateWidth = function updateWidth(newWidth) {
      if (debounceMs > 0) {
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
        timeoutRef.current = setTimeout(function () {
          setWidth(newWidth);
        }, debounceMs);
      } else {
        setWidth(newWidth);
      }
    };
    var observer = new ResizeObserver(function (entries) {
      var entry = entries[0];
      if (entry) {
        updateWidth(entry.contentRect.width);
      }
    });
    observer.observe(element);

    // 初始化宽度
    setWidth(element.getBoundingClientRect().width);
    return function () {
      observer.disconnect();
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [ref, debounceMs]);
  return width;
}
var baseClassName = 'pisell-pro-selector_layout';

/**
 * 统一的布局容器组件
 *
 * 支持三种布局模式：
 * 1. 响应式布局（推荐）：通过 responsive 配置，使用 ResizeObserver 实现容器级响应式
 * 2. Custom 布局：通过 className 使用预设样式
 * 3. Ant Design Grid 布局：基础的栅格布局，用于简单场景
 */
function LayoutContainer(_ref) {
  var _responsiveConfig$deb;
  var containerClassName = _ref.className,
    config = _ref.config,
    children = _ref.children;
  var containerRef = useRef(null);

  // 解析响应式配置
  var responsiveConfig = config === null || config === void 0 ? void 0 : config.responsive;
  var hasResponsive = !!responsiveConfig;

  // 解析断点配置
  var breakpoints = useMemo(function () {
    if (!responsiveConfig) return null;
    return parseResponsiveConfig(responsiveConfig);
  }, [responsiveConfig]);

  // 监听容器宽度
  var containerWidth = useContainerWidth(containerRef, (_responsiveConfig$deb = responsiveConfig === null || responsiveConfig === void 0 ? void 0 : responsiveConfig.debounce) !== null && _responsiveConfig$deb !== void 0 ? _responsiveConfig$deb : 0);

  // 计算当前激活的断点配置
  var activeConfig = useMemo(function () {
    if (!breakpoints) return null;
    return getActiveBreakpoint(containerWidth, breakpoints, responsiveConfig === null || responsiveConfig === void 0 ? void 0 : responsiveConfig.defaultColumns, responsiveConfig === null || responsiveConfig === void 0 ? void 0 : responsiveConfig.gap);
  }, [containerWidth, breakpoints, responsiveConfig]);

  // 无配置时使用默认布局
  if (!config) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames(baseClassName, containerClassName)
    }, children);
  }
  var type = config.type,
    className = config.className,
    _config$containerStyl = config.containerStyle,
    containerStyle = _config$containerStyl === void 0 ? {} : _config$containerStyl;

  // 1. 响应式布局（优先级最高）
  if (hasResponsive) {
    var _activeConfig$columns, _activeConfig$gap;
    // 通过 CSS 变量传递动态值，实际布局样式在 Less 文件中定义
    var cssVariables = {
      '--layout-columns': (_activeConfig$columns = activeConfig === null || activeConfig === void 0 ? void 0 : activeConfig.columns) !== null && _activeConfig$columns !== void 0 ? _activeConfig$columns : 1,
      '--layout-gap': typeof (activeConfig === null || activeConfig === void 0 ? void 0 : activeConfig.gap) === 'number' ? "".concat(activeConfig.gap, "px") : (_activeConfig$gap = activeConfig === null || activeConfig === void 0 ? void 0 : activeConfig.gap) !== null && _activeConfig$gap !== void 0 ? _activeConfig$gap : '16px'
    };
    return /*#__PURE__*/React.createElement("div", {
      ref: containerRef,
      className: classNames(baseClassName, "".concat(baseClassName, "-responsive"), containerClassName, className),
      style: _objectSpread(_objectSpread(_objectSpread({}, cssVariables), containerStyle), activeConfig === null || activeConfig === void 0 ? void 0 : activeConfig.style)
    }, children);
  }

  // 2. 自定义样式布局
  if (type !== 'antdGrid') {
    var layoutClassName = classNames(baseClassName, containerClassName, className);
    return /*#__PURE__*/React.createElement("div", {
      className: layoutClassName,
      style: containerStyle
    }, children);
  }

  // 3. Ant Design Grid 布局（基础场景）
  var _config$columns = config.columns,
    columns = _config$columns === void 0 ? 1 : _config$columns,
    align = config.align,
    justify = config.justify,
    gutter = config.gutter,
    wrap = config.wrap,
    _config$colConfig = config.colConfig,
    colConfig = _config$colConfig === void 0 ? {} : _config$colConfig;
  return /*#__PURE__*/React.createElement(ARow, {
    gutter: gutter,
    justify: justify,
    align: align,
    wrap: wrap
  }, children.map(function (child, index) {
    return /*#__PURE__*/React.createElement(ACol, _extends({
      key: index,
      span: columns ? 24 / columns : undefined
    }, colConfig), child);
  }));
}
export default LayoutContainer;