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 _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 _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 _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 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); }
import React, { useEffect, useMemo, useRef, useCallback, cloneElement, isValidElement, forwardRef, useImperativeHandle } from 'react';
import { Button } from 'antd';
import classNames from 'classnames';
import Pagination from "./components/Pagination";
import EmptyState from "./components/EmptyState";
import ScrollLoader from "./components/ScrollLoader";
import WaterfallList from "./components/WaterfallList";
import ListItemSkeleton from "./components/ListItemSkeleton";
import TabSkeleton from "./components/TabSkeleton";
import "./List.less";
import { Iconfont, PisellTabbar, PisellTabbarTemplate1 } from '@pisell/materials';
// import { locales } from '@pisell/utils';
import listLocales from "./locales";
import useWaterfall from "./hooks/useWaterfall";
import { useListState } from "./hooks/useListState";
import useEngineContext from "../../hooks/useEngineContext";
import LookupSearchInput from "../../pro/comprehensiveSearch/components/lookupSearchInput";
import { findProductIdsByPath } from "./utils";
// 虚假数据常量，用于loading状态
var MOCK_LIST_DATA = function () {
  var mockData = [];
  // 添加8个模拟项用于骨架屏
  for (var i = 0; i < 8; i++) {
    mockData.push({
      id: "_mock_".concat(i),
      __isSkeleton: true
    });
  }
  return mockData;
}();
var List = function List(props, ref) {
  // 获取应用上下文
  var context = useEngineContext();

  // 创建统一的语言获取函数
  var getCurrentLanguage = function getCurrentLanguage() {
    var _context$appHelper, _context$appHelper$ge, _context$appHelper$ge2, _context$appHelper2;
    var appLocale = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.call(_context$appHelper)) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.locales) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge2 = _context$appHelper$ge.getLocale) === null || _context$appHelper$ge2 === void 0 ? void 0 : _context$appHelper$ge2.call(_context$appHelper$ge);
    var storageLocale = (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.storage) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.get('umi_locale');

    // 尝试多种方式获取语言
    var finalLang = appLocale || storageLocale;

    // 如果上下文方式都失败，尝试直接从 localStorage 获取
    if (!finalLang && typeof window !== 'undefined') {
      finalLang = localStorage.getItem('umi_locale');
    }

    // 最终回退到默认语言
    return finalLang || 'en';
  };

  // 创建本地 getText 函数来处理本地化文案
  var getLocalText = function getLocalText(key, fallback) {
    var _listLocales;
    var currentLang = getCurrentLanguage();
    var localText = (_listLocales = listLocales[currentLang]) === null || _listLocales === void 0 ? void 0 : _listLocales[key];

    // 如果是字符串，返回字符串；否则回退到 fallback
    if (typeof localText === 'string') {
      return localText;
    }
    return fallback || '';
  };

  // 创建获取函数类型文案的函数
  var getLocalTextFunc = function getLocalTextFunc(key) {
    var _listLocales2;
    var currentLang = getCurrentLanguage();
    var localText = (_listLocales2 = listLocales[currentLang]) === null || _listLocales2 === void 0 ? void 0 : _listLocales2[key];

    // 如果是函数类型，直接返回函数；如果是字符串，返回字符串；否则回退
    if (typeof localText === 'function' || typeof localText === 'string') {
      return localText;
    }
    return key; // 简单回退，返回 key 本身
  };
  useImperativeHandle(ref, function () {
    return {
      getTabbarRef: function getTabbarRef() {
        if (isTreeTab) {
          return tabbarRef.current || template1tabbarRef.current;
        }
        return template1tabbarRef.current || tabbarRef.current;
      }
    };
  });
  var _props$className = props.className,
    className = _props$className === void 0 ? '' : _props$className,
    _props$style = props.style,
    style = _props$style === void 0 ? {} : _props$style,
    _props$tabStyle = props.tabStyle,
    tabStyle = _props$tabStyle === void 0 ? 'anchor' : _props$tabStyle,
    _props$tabGroup = props.tabGroup,
    tabGroup = _props$tabGroup === void 0 ? getLocalText('pisell-list-tab-group-default', '字段') : _props$tabGroup,
    _props$displayStyle = props.displayStyle,
    displayStyle = _props$displayStyle === void 0 ? 'grid' : _props$displayStyle,
    _props$width = props.width,
    width = _props$width === void 0 ? 'auto' : _props$width,
    _props$height = props.height,
    height = _props$height === void 0 ? 'auto' : _props$height,
    _props$paginationType = props.paginationType,
    paginationType = _props$paginationType === void 0 ? 'all' : _props$paginationType,
    _props$defaultPageSiz = props.defaultPageSize,
    defaultPageSize = _props$defaultPageSiz === void 0 ? 6 : _props$defaultPageSiz,
    _props$layoutDirectio = props.layoutDirection,
    layoutDirection = _props$layoutDirectio === void 0 ? 'horizontal' : _props$layoutDirectio,
    _props$zoom = props.zoom,
    zoom = _props$zoom === void 0 ? 1 : _props$zoom,
    _props$columns = props.columns,
    columns = _props$columns === void 0 ? 2 : _props$columns,
    _props$rows = props.rows,
    rows = _props$rows === void 0 ? 2 : _props$rows,
    _props$stickyTop = props.stickyTop,
    stickyTop = _props$stickyTop === void 0 ? true : _props$stickyTop,
    _props$columnGap = props.columnGap,
    columnGap = _props$columnGap === void 0 ? 12 : _props$columnGap,
    _props$rowGap = props.rowGap,
    rowGap = _props$rowGap === void 0 ? 12 : _props$rowGap,
    _props$tabData = props.tabData,
    tabData = _props$tabData === void 0 ? [] : _props$tabData,
    _props$data = props.data,
    data = _props$data === void 0 ? [] : _props$data,
    children = props.children,
    onLoadData = props.onLoadData,
    renderItem = props.renderItem,
    _props$emptyConfig = props.emptyConfig,
    emptyConfig = _props$emptyConfig === void 0 ? {
      show: true,
      text: getLocalText('pisell-list-empty-text-default', 'No data available'),
      icon: null,
      description: ''
    } : _props$emptyConfig,
    pagination = props.pagination,
    _props$loading = props.loading,
    loading = _props$loading === void 0 ? false : _props$loading,
    skeletonConfig = props.skeletonConfig,
    renderSearch = props.renderSearch,
    onTabSearch = props.onTabSearch,
    onActiveTabChange = props.onActiveTabChange,
    _props$isTreeTab = props.isTreeTab,
    isTreeTab = _props$isTreeTab === void 0 ? true : _props$isTreeTab;
  console.log('List props', props);
  var tabItems = tabStyle === 'none' ? [] : tabData || [];

  // 统一状态管理
  var _useListState = useListState({
      externalCurrentPage: pagination === null || pagination === void 0 ? void 0 : pagination.current,
      tabItems: tabItems,
      defaultPageSize: defaultPageSize,
      tabStyle: tabStyle,
      onLoadData: onLoadData,
      isTreeTab: isTreeTab
    }),
    listState = _useListState.state,
    currentPage = _useListState.actualCurrentPage,
    handleTabChange = _useListState.handleTabChange,
    handlePageChange = _useListState.handlePageChange,
    handleShowSizeChange = _useListState.handleShowSizeChange,
    handleLoadMore = _useListState.handleLoadMore,
    handleViewLess = _useListState.handleViewLess,
    handleScrollLoad = _useListState.handleScrollLoad,
    setIsStickyActive = _useListState.setStickyActive,
    setActiveTab = _useListState.setActiveTab;

  // 从状态中解构需要的值
  var activeTab = listState.activeTab,
    isStickyActive = listState.isStickyActive;
  var listRef = useRef(null);
  var containerRef = useRef(null);
  var tabbarRef = useRef(null);
  var template1tabbarRef = useRef(null);
  var headerRef = useRef(null);

  /**
   * BigSale 的分类 Tabbar 搜索弹层复用 ComprehensiveSearch 输入栏。
   * 保持 PisellFind 默认的实时搜索模式：不展示搜索按钮，输入变化仍由 Lookup 内部防抖触发。
   */
  var tabbarSearchProps = useMemo(function () {
    return {
      // 开启硬件扫码枪监听：tabbar 搜索是 BigSale 顶部的主要扫码入口。
      // 宿主注入了 acquireScanFocus 焦点栈，多个实例由栈顶协调，不会广播串扰。
      enableScanner: true,
      inputRender: function inputRender(ctx) {
        return /*#__PURE__*/React.createElement(LookupSearchInput, {
          ctx: ctx,
          showSearchButton: false,
          searchSectionProps: {
            className: 'pisell-list-tabbar-search-section',
            style: {
              flex: 1,
              minWidth: 0
            }
          }
        });
      }
    };
  }, []);

  // 辅助函数：判断字段值是否匹配目标值（支持数组包含判断）
  var matchesFieldValue = function matchesFieldValue(fieldValue, targetValue) {
    // 如果字段值是数组，检查是否包含目标值
    if (Array.isArray(fieldValue)) {
      return fieldValue.includes(targetValue);
    }
    // 否则使用严格相等比较
    return fieldValue === targetValue;
  };
  var dataIdMap = useMemo(function () {
    return data.reduce(function (pre, cur) {
      return _objectSpread(_objectSpread({}, pre), {}, _defineProperty({}, cur.id, cur));
    }, {});
  }, [data]);

  // 数据分组处理 - 按tab分组数据
  var processedData = useMemo(function () {
    // 如果正在加载且没有数据，使用模拟数据
    var sourceData = loading ? MOCK_LIST_DATA : data || [];

    // 如果tab样式是anchor，需要按分组显示数据
    if (tabStyle === 'anchor' && tabItems.length > 0) {
      var groupedData = [];

      // 在anchor模式下，始终显示所有分组的数据，完全忽略activeTab的值
      // 获取需要显示的分类tabs（排除"全部"）
      var categoryTabs = tabItems.filter(function (tab) {
        return tab.key !== 'all';
      });
      console.log("categoryTabs: ".concat(JSON.stringify(categoryTabs.map(function (t) {
        return {
          key: t.key,
          label: t.label,
          group: t.group
        };
      }), null, 2)));
      categoryTabs.forEach(function (tab) {
        console.log("Processing tab: ".concat(tab.key, ", label: ").concat(tab.label, ", group: ").concat(tab.group));
        var groupItems = [];

        // 优先使用tab.group字段进行过滤
        if (tab.group) {
          // 使用tabGroup指定的字段名进行过滤
          var filterField = tabGroup && tabGroup !== '字段' ? tabGroup : 'category';
          console.log("Using group filter: ".concat(filterField, " matches ").concat(tab.group));
          groupItems = sourceData.filter(function (item) {
            return matchesFieldValue(item[filterField], tab.group);
          });
          console.log("Found ".concat(groupItems.length, " items for group ").concat(tab.group));
        } else {
          // 如果没有group属性，尝试使用tab.key在多个可能的字段中查找匹配
          var possibleFields = [tabGroup && tabGroup !== '字段' ? tabGroup : null, 'category', 'status', 'type'].filter(Boolean);
          console.log("Trying fields for tab.key ".concat(tab.key, ": ").concat(JSON.stringify(possibleFields)));
          var _iterator = _createForOfIteratorHelper(possibleFields),
            _step;
          try {
            var _loop = function _loop() {
              var field = _step.value;
              if (field && sourceData.some(function (item) {
                return item[field] === tab.key;
              })) {
                groupItems = sourceData.filter(function (item) {
                  return item[field] === tab.key;
                });
                console.log("Found ".concat(groupItems.length, " items using field ").concat(field, " === ").concat(tab.key));
                return 1; // break
              }
            };
            for (_iterator.s(); !(_step = _iterator.n()).done;) {
              if (_loop()) break;
            }
          } catch (err) {
            _iterator.e(err);
          } finally {
            _iterator.f();
          }
        }
        console.log("Tab ".concat(tab.key, " final groupItems count: ").concat(groupItems.length));

        // 在锚点模式下，即使没有数据也要显示分组（用于显示空状态）
        groupedData.push({
          tabKey: tab.key,
          tabLabel: tab.label,
          items: groupItems
        });
        if (groupItems.length > 0) {
          console.log("Added group ".concat(tab.key, " to groupedData with ").concat(groupItems.length, " items"));
        } else {
          console.log("Added empty group ".concat(tab.key, " to groupedData"));
        }
      });

      // 在anchor模式下，总是返回所有分组，不受activeTab影响
      console.log("Anchor mode grouped data: ".concat(JSON.stringify(groupedData.map(function (g) {
        return {
          key: g.tabKey,
          label: g.tabLabel,
          itemCount: g.items.length
        };
      }), null, 2)));
      return groupedData;
    } else {
      // 非anchor模式或无tab，使用原有的过滤逻辑
      var filteredData = sourceData;

      // 如果没有选择任何tab或者选择了"全部"，不进行过滤
      if (!activeTab || activeTab === 'all' || Array.isArray(activeTab) && activeTab.length === 0) {
        return [{
          tabKey: 'all',
          tabLabel: '',
          items: filteredData
        }];
      }
      if (Array.isArray(activeTab)) {
        var productIds = findProductIdsByPath(tabItems, activeTab, 0);
        // 如果选择了"全部"，不进行过滤
        if (activeTab.toString() === '0') {
          return [{
            tabKey: activeTab,
            tabLabel: '',
            items: sourceData
          }];
        }
        var items = productIds.map(function (id) {
          return dataIdMap[id];
        }).filter(Boolean);
        return [{
          tabKey: activeTab,
          tabLabel: "",
          items: items
        }];
      } else {
        // 查找当前选中的tab
        var currentTab = tabItems.find(function (tab) {
          return tab.key === activeTab;
        });
        if (currentTab && currentTab.group) {
          // 如果tab项有group属性，使用group值进行过滤
          var filterField = 'category'; // 固定使用category字段，因为测试数据都使用这个字段
          filteredData = filteredData.filter(function (item) {
            return matchesFieldValue(item[filterField], currentTab.group);
          });
        } else if (currentTab) {
          // 如果没有group属性，假设tab的key就是要过滤的值
          var possibleFields = ['category', 'status', 'type', tabGroup];
          var _loop2 = function _loop2() {
            var field = _possibleFields[_i];
            if (field && field !== '字段' && filteredData.some(function (item) {
              return matchesFieldValue(item[field], activeTab);
            })) {
              filteredData = filteredData.filter(function (item) {
                return matchesFieldValue(item[field], activeTab);
              });
              return 1; // break
            }
          };
          for (var _i = 0, _possibleFields = possibleFields; _i < _possibleFields.length; _i++) {
            if (_loop2()) break;
          }
        }
        return [{
          tabKey: activeTab,
          tabLabel: (currentTab === null || currentTab === void 0 ? void 0 : currentTab.label) || '',
          items: filteredData
        }];
      }
    }
  }, [data, activeTab, tabItems, tabGroup, tabStyle, loading]);

  // 获取用于计算的数据总长度（所有分组的项目总数）
  var totalDataLength = useMemo(function () {
    return processedData.reduce(function (total, group) {
      return total + group.items.length;
    }, 0);
  }, [processedData]);

  // 瀑布流数据：展平所有分组的items
  var waterfallItems = useMemo(function () {
    if (displayStyle !== 'waterfall') return [];
    return processedData.reduce(function (allItems, group) {
      return [].concat(_toConsumableArray(allItems), _toConsumableArray(group.items));
    }, []);
  }, [displayStyle, processedData]);

  // 瀑布流布局Hook - 只在瀑布流模式下传入完整配置
  var waterfallOptions = useMemo(function () {
    if (displayStyle !== 'waterfall') {
      // 非瀑布流模式：使用简化配置避免不必要的计算
      return {
        tracks: 1,
        trackGap: 0,
        itemGap: 0,
        direction: 'vertical'
      };
    }
    return {
      // 垂直滚动使用columns（列数），水平滚动使用rows（行数）
      tracks: layoutDirection === 'vertical' ? columns : rows,
      // 垂直滚动：trackGap是列间距，水平滚动：trackGap是行间距
      trackGap: layoutDirection === 'vertical' ? columnGap : rowGap,
      // 垂直滚动：itemGap是行间距，水平滚动：itemGap是列间距
      itemGap: layoutDirection === 'vertical' ? rowGap : columnGap,
      direction: layoutDirection === 'vertical' ? 'vertical' : 'horizontal'
    };
  }, [displayStyle, layoutDirection, columns, rows, columnGap, rowGap]);
  var _useWaterfall = useWaterfall(waterfallItems, waterfallOptions),
    waterfallLayout = _useWaterfall.layout,
    registerItemRef = _useWaterfall.registerItemRef,
    recalculateLayout = _useWaterfall.recalculateLayout;

  // 处理向下滚动到底部并触发加载更多
  var handleScrollDown = function handleScrollDown() {
    if (!listRef.current) return;
    var element = listRef.current;
    if (layoutDirection === 'vertical') {
      // 垂直滚动：滚动到底部
      var scrollHeight = element.scrollHeight,
        clientHeight = element.clientHeight;
      var maxScroll = scrollHeight - clientHeight;
      element.scrollTo({
        top: maxScroll,
        behavior: 'smooth'
      });
    } else {
      // 水平滚动：滚动到最右边
      var scrollWidth = element.scrollWidth,
        clientWidth = element.clientWidth;
      var _maxScroll = scrollWidth - clientWidth;
      element.scrollTo({
        left: _maxScroll,
        behavior: 'smooth'
      });
    }

    // 滚动完成后检查是否需要加载更多数据
    setTimeout(function () {
      if (!listRef.current || loading || !hasMore) return;
      var element = listRef.current;
      var isAtEnd = false;
      if (layoutDirection === 'vertical') {
        var scrollTop = element.scrollTop,
          _scrollHeight = element.scrollHeight,
          _clientHeight = element.clientHeight;
        isAtEnd = scrollTop + _clientHeight >= _scrollHeight - 5; // 5px容错
      } else {
        var scrollLeft = element.scrollLeft,
          _scrollWidth = element.scrollWidth,
          _clientWidth = element.clientWidth;
        isAtEnd = scrollLeft + _clientWidth >= _scrollWidth - 5; // 5px容错
      }

      // 如果已经滚动到底部且有更多数据，触发加载更多
      if (isAtEnd && hasMore) {
        console.log('List: Triggering load more after scroll to bottom');
        handleScrollLoad();
      }
    }, 500); // 等待滚动动画完成（通常smooth滚动需要约500ms）
  };

  // 根据分页信息判断是否还有更多数据
  var hasMore = useMemo(function () {
    if (!pagination) return false;
    var current = pagination.current || currentPage;
    var total = pagination.total || 0;
    return current < total;
  }, [pagination, currentPage]);

  // 计算滚动加载相关状态
  var scrollLoadState = useMemo(function () {
    if (paginationType !== 'scroll') return null;
    var totalLoaded = totalDataLength;
    return {
      canLoadMore: hasMore,
      totalLoaded: totalLoaded
    };
  }, [paginationType, totalDataLength, hasMore]);

  // 处理滚动加载
  useEffect(function () {
    if (paginationType !== 'scroll') return;
    var scrollTimer = null;
    var lastScrollPosition = {
      top: 0,
      left: 0
    };
    var handleScroll = function handleScroll() {
      if (!listRef.current || loading) return;

      // 清除之前的定时器，实现防抖
      if (scrollTimer) {
        clearTimeout(scrollTimer);
      }
      scrollTimer = setTimeout(function () {
        if (!listRef.current || loading || !hasMore) return;
        var element = listRef.current;
        var currentScrollTop = element.scrollTop;
        var currentScrollLeft = element.scrollLeft;

        // 根据布局方向检查不同的滚动方向和边界
        var isNearEnd = false;
        var isScrollingTowardsEnd = false;
        if (layoutDirection === 'vertical') {
          var scrollTop = element.scrollTop,
            scrollHeight = element.scrollHeight,
            clientHeight = element.clientHeight;
          isScrollingTowardsEnd = currentScrollTop > lastScrollPosition.top;
          isNearEnd = scrollTop + clientHeight >= scrollHeight - 50;
        } else {
          var scrollLeft = element.scrollLeft,
            scrollWidth = element.scrollWidth,
            clientWidth = element.clientWidth;
          isScrollingTowardsEnd = currentScrollLeft > lastScrollPosition.left;
          isNearEnd = scrollLeft + clientWidth >= scrollWidth - 50;
        }
        lastScrollPosition = {
          top: currentScrollTop,
          left: currentScrollLeft
        };
        if (isScrollingTowardsEnd && isNearEnd && hasMore) {
          handleScrollLoad();
        }
      }, 100);
    };
    var listElement = listRef.current;
    if (listElement) {
      lastScrollPosition = {
        top: listElement.scrollTop,
        left: listElement.scrollLeft
      };
      listElement.addEventListener('scroll', handleScroll, {
        passive: true
      });
    }
    return function () {
      if (listElement) {
        listElement.removeEventListener('scroll', handleScroll);
      }
      if (scrollTimer) {
        clearTimeout(scrollTimer);
      }
    };
  }, [paginationType, layoutDirection, loading, hasMore, handleScrollLoad]);

  // 检测sticky状态的滚动监听器
  useEffect(function () {
    if (!stickyTop || layoutDirection !== 'vertical') {
      // 如果不需要sticky效果，重置状态
      if (isStickyActive) {
        setIsStickyActive(false);
      }
      return;
    }
    var handleScroll = null;

    // 等待DOM更新后再添加监听器
    var timer = setTimeout(function () {
      if (!containerRef.current || !headerRef.current) return;
      handleScroll = function handleScroll() {
        if (!listRef.current || !headerRef.current) return;

        // 监听 list-content 的滚动
        var scrollTop = listRef.current.scrollTop;
        var headerHeight = headerRef.current.offsetHeight;

        // 检测是否滚动了足够的距离来激活sticky效果
        var shouldActivate = scrollTop > headerHeight / 2;

        // 避免不必要的状态更新
        if (isStickyActive !== shouldActivate) {
          setIsStickyActive(shouldActivate);
        }
      };

      // 监听 list-content 的滚动
      var listContent = listRef.current;
      if (listContent) {
        listContent.addEventListener('scroll', handleScroll, {
          passive: true
        });

        // 立即检查一次当前状态
        handleScroll();
      }
    }, 0);
    return function () {
      clearTimeout(timer);
      if (handleScroll && listRef.current) {
        listRef.current.removeEventListener('scroll', handleScroll);
      }
    };
  }, [stickyTop, layoutDirection, isStickyActive]);

  // 自动加载检测 - 当内容不足以产生滚动条时自动加载更多数据
  useEffect(function () {
    if (paginationType !== 'scroll' || loading || !hasMore || data.length === 0) {
      return;
    }
    var autoLoadTimer = null;
    var checkAutoLoad = function checkAutoLoad() {
      if (!listRef.current || loading || !hasMore) return;
      var element = listRef.current;
      var needsMoreContent = false;

      // 根据布局方向检查是否需要滚动条
      if (layoutDirection === 'vertical') {
        // 垂直滚动：检查内容高度是否小于等于容器高度
        needsMoreContent = element.scrollHeight <= element.clientHeight;
      } else {
        // 水平滚动：检查内容宽度是否小于等于容器宽度
        needsMoreContent = element.scrollWidth <= element.clientWidth;
      }

      // 如果内容不足以产生滚动条且有更多数据，自动触发加载
      if (needsMoreContent && hasMore) {
        console.log('List: Auto-loading more data due to insufficient content');
        handleScrollLoad();
      }
    };

    // 延迟检测，确保DOM已渲染完成
    autoLoadTimer = setTimeout(function () {
      checkAutoLoad();
    }, 100);
    return function () {
      if (autoLoadTimer) {
        clearTimeout(autoLoadTimer);
      }
    };
  }, [paginationType, layoutDirection, loading, hasMore, totalDataLength, handleScrollLoad]);

  // 计算容器样式 - 使用useMemo优化响应式更新
  var containerStyle = useMemo(function () {
    // 处理width值：数字或数字字符串加px，其他直接使用
    var processedWidth = typeof width === 'number' ? "".concat(width, "px") : typeof width === 'string' && /^\d+(\.\d+)?$/.test(width.trim()) ? "".concat(width, "px") : width;

    // 处理height值：数字或数字字符串加px，其他直接使用
    var processedHeight = typeof height === 'number' ? "".concat(height, "px") : typeof height === 'string' && /^\d+(\.\d+)?$/.test(height.trim()) ? "".concat(height, "px") : height;
    return _objectSpread(_objectSpread({}, style), {}, {
      width: processedWidth,
      height: processedHeight,
      transform: "scale(".concat(zoom, ")"),
      transformOrigin: 'top left'
    });
  }, [style, width, height, zoom]);

  // 计算列表项样式 - 使用useMemo优化
  var listStyle = useMemo(function () {
    var baseStyle = {
      columnGap: "".concat(columnGap, "px"),
      rowGap: "".concat(rowGap, "px")
    };
    if (displayStyle === 'grid') {
      return _objectSpread(_objectSpread({}, baseStyle), {}, {
        display: 'grid',
        gridTemplateColumns: "repeat(".concat(columns, ", 1fr)")
      });
      /*
      if (layoutDirection === 'vertical') {
          return {
              ...baseStyle,
              display: 'grid',
              gridTemplateColumns: `repeat(${columns}, 1fr)`,
          };
      } else {
          return {
              ...baseStyle,
              display: 'grid',
              gridTemplateRows: `repeat(${rows}, 1fr)`,
              gridAutoFlow: 'column',
          };
      }
      */
    } else {
      // 瀑布流布局 - 使用新的瀑布流实现
      return _objectSpread(_objectSpread({}, baseStyle), {}, {
        display: 'flex',
        flexDirection: layoutDirection === 'vertical' ? 'row' : 'row',
        alignItems: 'flex-start',
        gap: layoutDirection === 'vertical' ? "0 ".concat(columnGap, "px") : "".concat(rowGap, "px ").concat(columnGap, "px"),
        width: '100%'
      }, layoutDirection === 'horizontal' && {
        flexWrap: 'wrap'
      });
    }
  }, [displayStyle, layoutDirection, columns, rows, columnGap, rowGap]);

  // 滚动到指定标题的函数
  var scrollToTitle = function scrollToTitle(tabKey) {
    var titleElement = document.getElementById("list-title-".concat(tabKey));
    if (titleElement && listRef.current) {
      var container = listRef.current;
      var titleOffsetTop = titleElement.offsetTop;
      container.scrollTo({
        top: titleOffsetTop - 20,
        // 留一些上边距
        behavior: 'smooth'
      });
    }
  };

  // 处理tab变化
  var handleTabChangeWithScroll = function handleTabChangeWithScroll(key) {
    if (tabStyle === 'anchor') {
      // 锚点模式：只更新activeTab状态，不触发数据加载
      console.log('Anchor mode tab change:', key, '- skipping data load');
      onActiveTabChange === null || onActiveTabChange === void 0 || onActiveTabChange(key);
      setActiveTab(key);

      // 滚动到对应位置
      if (key === 'all') {
        setTimeout(function () {
          if (listRef.current) {
            listRef.current.scrollTo({
              top: 0,
              behavior: 'smooth'
            });
          }
        }, 100);
      } else {
        // 滚动到对应的分组标题
        setTimeout(function () {
          scrollToTitle(key);
        }, 100);
      }
    } else {
      // 非锚点模式：正常处理tab切换，包括数据加载
      console.log('Non-anchor mode tab change:', key, '- triggering data load');
      onActiveTabChange === null || onActiveTabChange === void 0 || onActiveTabChange(key);
      handleTabChange(key);
    }
  };

  // 渲染Tab栏 - 简化为普通函数
  var renderTabs = function renderTabs() {
    // 检查是否应该显示tab
    // if (tabStyle === 'none' || tabItems.length === 0) return null;

    // 只有在垂直排版且开启顶部固定时才应用sticky效果
    var shouldSticky = layoutDirection === 'vertical' && stickyTop;

    // 构建header类名
    var headerClasses = classNames('pisell-list-header', {
      'pisell-list-header-sticky': shouldSticky,
      'sticky-active': shouldSticky && isStickyActive
    });

    // 如果正在加载，显示骨架屏
    if (loading) {
      return /*#__PURE__*/React.createElement("div", {
        ref: headerRef,
        className: headerClasses,
        style: {
          padding: '0 12px'
        }
      }, /*#__PURE__*/React.createElement(TabSkeleton, {
        tabStyle: tabStyle
      }));
    }
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      id: "level1-wrap"
    }), /*#__PURE__*/React.createElement("div", {
      ref: headerRef,
      className: headerClasses
    }, isTreeTab ? /*#__PURE__*/React.createElement(PisellTabbar, {
      levelConfig: {
        level1: {
          positionId: "#level1-wrap"
        },
        level2: {
          positionId: "#level2-wrap"
        }
      },
      style: {
        height: "100%"
      },
      dataSource: tabItems,
      value: activeTab,
      onChange: handleTabChangeWithScroll,
      onSearch: onTabSearch,
      searchProps: tabbarSearchProps,
      ref: tabbarRef
    }) : /*#__PURE__*/React.createElement(PisellTabbarTemplate1, {
      dataSource: tabItems,
      value: activeTab,
      onChange: handleTabChangeWithScroll,
      onSearch: onTabSearch,
      searchProps: tabbarSearchProps,
      ref: template1tabbarRef
    })));
  };

  // 渲染列表内容
  var renderContent = useCallback(function () {
    // 检查是否有子组件
    var hasChildren = children && React.Children.count(children) > 0;

    // 计算列表内容区域的高度
    var getContentHeight = function getContentHeight() {
      // 如果是scroll模式，需要确保有固定高度才能滚动
      if (paginationType === 'scroll') {
        // 如果容器有明确的高度设置，让内容区域自动填充（使用flex: 1）
        if (height !== 'auto') {
          return undefined; // 不设置具体高度，让CSS的flex: 1生效
        }
        // 如果容器高度是auto，给一个默认的滚动高度
        return '400px';
      }
      // 非scroll模式：如果外部设置了高度，让内容区域填充；否则使用auto
      if (height !== 'auto') {
        return undefined; // 不设置具体高度，让CSS的flex: 1生效
      }
      return 'auto';
    };
    var contentHeight = getContentHeight();
    return /*#__PURE__*/React.createElement("div", {
      ref: listRef,
      className: classNames('list-content', "list-content-".concat(displayStyle), "list-content-".concat(layoutDirection)),
      style: _objectSpread(_objectSpread({
        background: 'transparent'
      }, contentHeight !== undefined && {
        height: contentHeight
      }), paginationType === 'scroll' && {
        overflow: layoutDirection === 'horizontal' ? 'auto hidden' : 'hidden auto'
      })
    }, renderSearch === null || renderSearch === void 0 ? void 0 : renderSearch(), layoutDirection === 'vertical' && renderTabs(), totalDataLength === 0 && !loading ? /*#__PURE__*/React.createElement(EmptyState, {
      config: emptyConfig,
      hasData: totalDataLength > 0
    }) : /*#__PURE__*/React.createElement("div", {
      className: classNames('list-items'),
      style: _objectSpread({}, layoutDirection === 'vertical' && {
        padding: undefined
      })
    }, displayStyle === 'waterfall' ?
    /*#__PURE__*/
    // 瀑布流渲染 - 使用独立组件
    React.createElement(WaterfallList, {
      layout: waterfallLayout,
      layoutDirection: layoutDirection,
      columnGap: columnGap,
      rowGap: rowGap,
      columns: columns,
      rows: rows,
      registerItemRef: registerItemRef,
      renderItem: renderItem
    }, children) :
    /*#__PURE__*/
    // 分组渲染逻辑
    React.createElement(React.Fragment, null, processedData.map(function (group, groupIndex) {
      return /*#__PURE__*/React.createElement(React.Fragment, {
        key: group.tabKey
      }, (tabStyle === 'anchor' || processedData.length > 1) && group.tabLabel && /*#__PURE__*/React.createElement("div", {
        id: "list-title-".concat(group.tabKey),
        className: "pisell-list-group-title"
      }, /*#__PURE__*/React.createElement("h2", {
        className: "pisell-list-group-title-text"
      }, group.tabLabel)), /*#__PURE__*/React.createElement("div", {
        className: classNames('list-group-items'),
        style: displayStyle === 'grid' ? listStyle : undefined
      }, hasChildren ?
      // 如果有子组件，循环渲染子组件
      group.items.map(function (item, itemIndex) {
        var _item$id;
        if (!item) return null;
        return /*#__PURE__*/React.createElement("div", {
          key: (_item$id = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id !== void 0 ? _item$id : itemIndex,
          className: classNames('list-item')
        }, item.__isSkeleton ? /*#__PURE__*/React.createElement(ListItemSkeleton, _extends({
          displayStyle: displayStyle,
          showImage: true
        }, skeletonConfig)) : React.Children.map(children, function (child, childIndex) {
          if ( /*#__PURE__*/isValidElement(child)) {
            var _item$id2;
            return /*#__PURE__*/cloneElement(child, _objectSpread(_objectSpread({}, child.props), {}, {
              // 传递数据项给子组件
              item: item,
              index: itemIndex,
              // 为每个子组件添加唯一key
              key: "".concat(group.tabKey, "-").concat((_item$id2 = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id2 !== void 0 ? _item$id2 : itemIndex, "-").concat(childIndex)
            }));
          }
          return child;
        }));
      }) :
      // 没有子组件时使用原有逻辑
      group.items.map(function (item, itemIndex) {
        var _item$id3;
        if (!item) return null;
        return /*#__PURE__*/React.createElement("div", {
          key: (_item$id3 = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id3 !== void 0 ? _item$id3 : itemIndex,
          className: classNames('list-item')
        }, item.__isSkeleton ? /*#__PURE__*/React.createElement(ListItemSkeleton, _extends({
          displayStyle: displayStyle,
          showImage: true
        }, skeletonConfig)) : renderItem ? renderItem(item, itemIndex) : /*#__PURE__*/React.createElement("div", {
          className: classNames('default-item')
        }, _typeof(item) === 'object' ? JSON.stringify(item) : item));
      })));
    })), /*#__PURE__*/React.createElement(ScrollLoader, {
      loading: loading,
      scrollLoadState: scrollLoadState,
      layoutDirection: layoutDirection,
      paginationType: paginationType
    })));
  }, [displayStyle, layoutDirection, paginationType, listStyle, processedData, renderItem, loading, children, height, scrollLoadState, emptyConfig, totalDataLength, tabStyle, renderSearch, skeletonConfig]);

  // 渲染底部工具栏
  var renderFooter = function renderFooter() {
    if (paginationType === 'all' || paginationType === 'scroll') return null;
    if (paginationType === 'more') {
      var canLoadMore = hasMore;
      if (canLoadMore) {
        return /*#__PURE__*/React.createElement("div", {
          className: classNames('list-footer')
        }, /*#__PURE__*/React.createElement(Button, {
          onClick: handleLoadMore,
          loading: loading
        }, getLocalText('pisell-list-load-more', '查看更多')));
      } else if (currentPage > 1) {
        // 当已经显示超过初始数量的数据时，显示查看更少按钮
        return /*#__PURE__*/React.createElement("div", {
          className: classNames('list-footer')
        }, /*#__PURE__*/React.createElement(Button, {
          onClick: handleViewLess,
          className: classNames('view-less-btn')
        }, getLocalText('pisell-list-view-less', '查看更少')));
      }
      return null;
    }
    if (paginationType === 'pager') {
      var _pagination$totalCoun;
      // 优先使用传入的总数据条数，否则使用当前数据长度
      var total = (_pagination$totalCoun = pagination === null || pagination === void 0 ? void 0 : pagination.totalCount) !== null && _pagination$totalCoun !== void 0 ? _pagination$totalCoun : totalDataLength;
      var showTotal = function showTotal(total, range) {
        var totalFunc = getLocalTextFunc('pisell-list-pagination-total');
        if (typeof totalFunc === 'function') {
          return totalFunc(range[0], range[1], total);
        }
        // 使用 i18n 回退函数
        var fallbackFunc = getLocalTextFunc('pisell-list-pagination-total-fallback');
        if (typeof fallbackFunc === 'function') {
          return fallbackFunc(range[0], range[1], total);
        }

        // 最终回退（理论上不会执行到这里）
        return "\u663E\u793A\u7B2C ".concat(range[0], "-").concat(range[1], " \u6761\uFF0C\u5171 ").concat(total, " \u6761");
      };
      return /*#__PURE__*/React.createElement("div", {
        className: classNames('list-footer')
      }, /*#__PURE__*/React.createElement(Pagination, {
        current: currentPage,
        pageSize: defaultPageSize,
        total: total,
        totalPages: pagination === null || pagination === void 0 ? void 0 : pagination.total,
        onChange: handlePageChange,
        onShowSizeChange: handleShowSizeChange,
        showTotal: showTotal,
        showSizeChanger: true,
        pageSizeOptions: ['6', '10', '20', '50']
      }));
    }
    return null;
  };

  // 渲染滚动悬浮按钮
  var renderScrollButton = function renderScrollButton() {
    // 只在滚动加载模式下且有数据时显示滚动按钮
    if (paginationType !== 'scroll' || totalDataLength === 0) {
      return null;
    }
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('list-scroll-float-button')
    }, /*#__PURE__*/React.createElement("button", {
      className: classNames('scroll-down-button'),
      onClick: handleScrollDown,
      title: layoutDirection === 'vertical' ? getLocalText('pisell-list-scroll-to-bottom', '滚动到底部并加载更多') : getLocalText('pisell-list-scroll-to-end', '滚动到末尾并加载更多'),
      style: _objectSpread(_objectSpread({
        padding: '16px',
        position: 'absolute',
        background: 'rgba(255, 255, 255, 0.75)',
        boxShadow: '0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
        borderRadius: '100px',
        outline: '1px #D0D5DD solid',
        outlineOffset: '-1px',
        backdropFilter: 'blur(6px)',
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'flex-start',
        gap: '16px',
        display: 'inline-flex',
        cursor: 'pointer'
      }, layoutDirection === 'horizontal' ? {
        right: '20px',
        top: '50%',
        transform: 'translateY(-50%)'
      } : {
        left: '50%',
        bottom: '20px',
        transform: 'translateX(-50%)'
      }), {}, {
        zIndex: 1000,
        border: 'none'
      })
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        width: '32px',
        height: '32px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: layoutDirection === 'horizontal' ? "pisell2-chevron-right" : "pisell2-chevron-down",
      style: {
        fontSize: '20px',
        color: '#101828'
      }
    }))));
  };

  // 计算容器类名 - 直接计算，无需memo
  var containerClassName = classNames('pisell-list', className, "pisell-list-".concat(layoutDirection), {
    'pisell-list-sticky-enabled': layoutDirection === 'vertical' && stickyTop
  });

  // 计算容器样式 - 直接计算，无需memo
  var finalContainerStyle = _objectSpread(_objectSpread(_objectSpread({}, containerStyle), {}, {
    position: 'relative'
  }, layoutDirection === 'vertical' && height !== 'auto' && {
    overflowY: 'hidden'
  }), layoutDirection === 'horizontal' && {
    display: 'flex',
    flexDirection: "row"
  });

  // 渲染主要内容区域
  var renderMainContent = function renderMainContent() {
    if (layoutDirection === 'vertical') {
      // 上下排版：header 和内容都在一个滚动容器内
      return renderContent();
    } else {
      // 左右排版：保持原有结构
      return /*#__PURE__*/React.createElement(React.Fragment, null, renderContent(), renderTabs());
    }
  };
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    className: containerClassName,
    style: finalContainerStyle
  }, renderMainContent(), renderFooter(), renderScrollButton());
};
export default /*#__PURE__*/forwardRef(List);