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 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 classNames from 'classnames';
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import { getText } from "../../locales";
import PisellCards from "../PisellCards";
import SuperTabs from "../PisellSuperTabs";
import Iconfont from "../iconfont";
import { PisellFind } from "../pisellFind";
import "./PisellTabbar.less";
import { DEFAULT_LEVEL_CONFIG, LEVEL_ADD_ITEMS, getExpandConfig } from "./constants";
import { useActiveKey, useExpand } from "./hooks";
import mock from "./mock";
import { addDataSourceItemsByKey, getDefaultActiveKey } from "./utils";
/**
 * PisellTabbar - 多层级 Tabbar 组件
 *
 * 支持最多 3 层级的 Tab 导航，每层级可独立展开/收起
 *
 * @component
 * @example
 * ```tsx
 * <PisellTabbar
 *   dataSource={categoryData}
 *   value={[1, 10, 100]}
 *   onChange={(value) => console.log('当前选中:', value)}
 * />
 * ```
 */
var PisellTabbar = /*#__PURE__*/forwardRef(function (props, ref) {
  var _props$dataSource = props.dataSource,
    dataSource = _props$dataSource === void 0 ? props !== null && props !== void 0 && props.__designMode ? mock : mock : _props$dataSource,
    value = props.value,
    onChange = props.onChange,
    className = props.className,
    style = props.style,
    customLevelConfig = props.levelConfig,
    customExpandConfig = props.expandConfig,
    _props$maxLevel = props.maxLevel,
    maxLevel = _props$maxLevel === void 0 ? 3 : _props$maxLevel,
    _onSearch = props.onSearch;
  var containerRef = useRef(null);
  var searchRef = useRef(null);
  console.log('searchRef', searchRef.current);
  // 激活的 key 管理
  var _useActiveKey = useActiveKey({
      initialActiveKey: value || getDefaultActiveKey(dataSource, 'id'),
      onChange: onChange
    }),
    activeKey = _useActiveKey.activeKey,
    setActiveKey = _useActiveKey.setActiveKey,
    getActiveKey = _useActiveKey.getActiveKey,
    _setActiveKey = _useActiveKey._setActiveKey,
    setCacheActiveKey = _useActiveKey.setCacheActiveKey,
    resetActiveKey = _useActiveKey.resetActiveKey,
    getCacheActiveKey = _useActiveKey.getCacheActiveKey;
  var level1Value = useMemo(function () {
    return getActiveKey(0);
  }, [activeKey]);
  var level2Value = useMemo(function () {
    return getActiveKey(1);
  }, [activeKey]);
  var level3Value = useMemo(function () {
    return getActiveKey(2);
  }, [activeKey]);

  // 展开状态管理
  var _useExpand = useExpand(),
    expand = _useExpand.expand,
    toggleExpand = _useExpand.toggleExpand,
    getExpand = _useExpand.getExpand;

  // 展开配置
  var expandConfigData = customExpandConfig || getExpandConfig();

  /**
   * 打开搜索模式
   */
  var openSearchMode = function openSearchMode() {
    setCacheActiveKey(activeKey);
    _setActiveKey([]);
    onChange === null || onChange === void 0 || onChange([]);
  };

  /**
   * 关闭搜索模式
   */
  var closeSearchMode = function closeSearchMode() {
    _onSearch === null || _onSearch === void 0 || _onSearch('');
    resetActiveKey();
  };

  //@ts-ignore
  useImperativeHandle(ref, function () {
    var _searchRef$current;
    if (props !== null && props !== void 0 && props.__designMode) {
      return containerRef.current;
    }
    return {
      closeSearchMode: searchRef === null || searchRef === void 0 || (_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 ? void 0 : _searchRef$current.close
    };
  });

  /**
   * 同步外部 value 到内部状态
   */
  useEffect(function () {
    if (value) {
      _setActiveKey(value);
    }
  }, [JSON.stringify(value)]);

  /**
   * 获取层级配置
   */
  var getLevelConfig = useCallback(function (level) {
    return _objectSpread(_objectSpread({}, DEFAULT_LEVEL_CONFIG[level]), customLevelConfig === null || customLevelConfig === void 0 ? void 0 : customLevelConfig[level]);
  }, [customLevelConfig]);

  /**
   * 处理一级 Tab 切换
   */
  var handleLevel1Change = useCallback(function (key, item) {
    var _item$children;
    setActiveKey(0, key, item !== null && item !== void 0 && (_item$children = item.children) !== null && _item$children !== void 0 && _item$children.length ? 0 : undefined);
  }, [setActiveKey]);

  /**
   * 处理二级 Tab 切换
   */
  var handleLevel2Change = useCallback(function (key, item) {
    var _item$children2;
    setActiveKey(1, key, item !== null && item !== void 0 && (_item$children2 = item.children) !== null && _item$children2 !== void 0 && _item$children2.length ? 0 : undefined);
  }, [setActiveKey]);

  /**
   * 处理三级 Tab 切换
   */
  var handleLevel3Change = useCallback(function (key) {
    setActiveKey(2, key);
  }, [setActiveKey]);

  /**
   * 渲染 level2/level3 自定义点击卡片（如展开按钮）
   */
  var renderLevelNCard = useCallback(function (cardProps, level) {
    var _cardProps$active;
    var itemData = cardProps.dataSource;
    var levelConfig = getLevelConfig(level);
    return /*#__PURE__*/React.createElement(PisellCards.TextCard, _extends({
      text: itemData.text
    }, cardProps, {
      variant: "outlined",
      widthMode: "fixed",
      textConfig: {
        textAlign: 'center',
        color: '#FFF',
        flex: 'none'
      },
      style: {
        borderRadius: '8px',
        background: 'rgba(0, 0, 0, 0.50)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: levelConfig.cardHeight
      },
      width: levelConfig.cardWidth,
      active: _objectSpread(_objectSpread({}, cardProps.active), {}, {
        style: _objectSpread(_objectSpread({}, (_cardProps$active = cardProps.active) === null || _cardProps$active === void 0 ? void 0 : _cardProps$active.style), {}, {
          color: '#000000',
          background: '#ffffff'
        })
      })
    }));
  }, [activeKey, getLevelConfig, getExpand, expandConfigData]);

  /**
   * 渲染 level2/level3 普通卡片
   */
  var renderLevelNNormalCard = useCallback(function (cardProps, level) {
    var _cardProps$active2;
    var itemData = cardProps.dataSource;
    var levelConfig = getLevelConfig(level);
    return /*#__PURE__*/React.createElement(PisellCards.TextCard, _extends({}, cardProps, {
      text: itemData.name,
      variant: "outlined",
      widthMode: "fixed",
      textConfig: {
        textAlign: 'center',
        color: '#FFF',
        maxLines: 2,
        ellipsis: true
      },
      style: {
        height: levelConfig.cardHeight,
        borderRadius: '8px',
        background: 'rgba(0, 0, 0, 0.50)'
      },
      width: levelConfig.cardWidth,
      active: _objectSpread(_objectSpread({}, cardProps.active), {}, {
        style: _objectSpread(_objectSpread({}, (_cardProps$active2 = cardProps.active) === null || _cardProps$active2 === void 0 ? void 0 : _cardProps$active2.style), {}, {
          color: '#000000',
          background: '#ffffff'
        })
      })
    }));
  }, [activeKey, getLevelConfig]);

  /**
   * 一级数据源
   */
  var level1DataSource = useMemo(function () {
    return addDataSourceItemsByKey(dataSource, LEVEL_ADD_ITEMS.level1);
  }, [dataSource]);

  /**
   * 渲染三级 Tabbar
   */
  var renderLevel3 = useCallback(function (panelProps2) {
    if (maxLevel < 3) return null;
    var _dataSource2 = panelProps2.dataSource.children || [];
    if (_dataSource2.length) {
      _dataSource2 = addDataSourceItemsByKey(_dataSource2, LEVEL_ADD_ITEMS.level3);
    }
    var level3Config = getLevelConfig('level3');
    var level3Expand = getExpand('level3');

    /**
     * 渲染三级 Tab 项
     */
    var renderLevel3Item = function renderLevel3Item(itemProps) {
      var itemData = itemProps.dataSource;

      // 处理自定义点击事件的项（如展开按钮）
      if (itemData !== null && itemData !== void 0 && itemData.customClick) {
        if (itemProps.dataSource.key === 'expand') {
          return renderExpand(itemProps, 'level3');
        }
      }

      // 普通项
      return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
        card: function card(cardProps) {
          return renderLevelNNormalCard(cardProps, 'level3');
        },
        panelContainer: function panelContainer() {
          return document.querySelector(".pisell-super-tabs-slot-bottom-sku-list-tabbar-".concat(panelProps2.dataSource.id));
        }
      }));
    };
    return /*#__PURE__*/React.createElement(SuperTabs, {
      id: "sku-list-tabbar-".concat(panelProps2.dataSource.id),
      tabItemStyle: {},
      isControlled: true,
      dataSource: _dataSource2,
      value: level3Value,
      onChange: handleLevel3Change,
      rowKey: "id",
      style: {
        flex: 1,
        background: level3Config.superTabsBg
      },
      gridProps: {
        direction: 'horizontal',
        gap: 4,
        wrap: level3Expand ? 'wrap' : 'nowrap',
        startSlot: /*#__PURE__*/React.createElement("div", {
          style: {
            paddingLeft: level3Config.paddingLeft
          }
        }, /*#__PURE__*/React.createElement(Iconfont, {
          type: "pisell2-trend-down-01",
          style: {
            color: '#fff',
            fontSize: 24,
            marginRight: 8
          }
        }))
      },
      scrollViewProps: {
        style: {
          padding: '4px 8px'
        },
        overflow: !level3Expand ? 'x' : 'hidden',
        scrollbarStyle: 'none',
        scrollActionsConfig: {
          type: 'lrArrows',
          show: true
        }
      },
      renderItem: renderLevel3Item
    });
  }, [activeKey, maxLevel, getActiveKey, handleLevel3Change, getExpand, toggleExpand, getLevelConfig, renderLevelNCard, renderLevelNNormalCard]);

  /**
   * 渲染二级 Tabbar
   */
  var renderLevel2 = useCallback(function (panelProps) {
    if (maxLevel < 2) return null;
    var _dataSource = panelProps.dataSource.children || [];
    if (_dataSource.length) {
      _dataSource = addDataSourceItemsByKey(_dataSource, LEVEL_ADD_ITEMS.level2);
    }
    var level2Config = getLevelConfig('level2');
    var level2Expand = getExpand('level2');

    /**
     * 渲染二级 Tab 项
     */
    var renderLevel2Item = function renderLevel2Item(itemProps) {
      var itemData = itemProps.dataSource;

      // 处理自定义点击事件的项（如展开按钮）
      if (itemData !== null && itemData !== void 0 && itemData.customClick) {
        if (itemProps.dataSource.key === 'expand') {
          return renderExpand(itemProps, 'level2');
        }
      }

      // 普通项
      return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
        card: function card(cardProps) {
          return renderLevelNNormalCard(cardProps, 'level2');
        },
        panel: function panel(innerPanelProps) {
          var _innerPanelProps$data;
          if (innerPanelProps !== null && innerPanelProps !== void 0 && (_innerPanelProps$data = innerPanelProps.dataSource) !== null && _innerPanelProps$data !== void 0 && (_innerPanelProps$data = _innerPanelProps$data.children) !== null && _innerPanelProps$data !== void 0 && _innerPanelProps$data.length) {
            return renderLevel3(innerPanelProps);
          }
          return null;
        },
        panelContainer: function panelContainer() {
          return document.querySelector(".pisell-super-tabs-slot-bottom-sku-list-tabbar-".concat(panelProps.dataSource.id));
        }
      }));
    };
    return /*#__PURE__*/React.createElement(SuperTabs, {
      id: "sku-list-tabbar-".concat(panelProps.dataSource.id),
      tabItemStyle: {},
      dataSource: _dataSource,
      value: level2Value,
      isControlled: true,
      onChange: handleLevel2Change,
      rowKey: "id",
      style: {
        flex: 1,
        background: level2Config.superTabsBg
      },
      gridProps: {
        direction: 'horizontal',
        gap: 4,
        wrap: level2Expand ? 'wrap' : 'nowrap',
        startSlot: /*#__PURE__*/React.createElement("div", {
          style: {
            paddingLeft: level2Config.paddingLeft
          }
        }, /*#__PURE__*/React.createElement(Iconfont, {
          type: "pisell2-trend-down-01",
          style: {
            color: '#fff',
            fontSize: 24,
            marginRight: 8
          }
        }))
      },
      scrollViewProps: {
        style: {
          padding: '4px 8px'
        },
        overflow: !level2Expand ? 'x' : 'hidden',
        scrollbarStyle: 'none',
        scrollActionsConfig: {
          type: 'lrArrows',
          show: true
        }
      },
      renderItem: renderLevel2Item
    });
  }, [activeKey, maxLevel, getActiveKey, handleLevel2Change, getExpand, toggleExpand, getLevelConfig, renderLevelNCard, renderLevelNNormalCard, renderLevel3]);
  var renderExpand = useCallback(function (itemProps, level) {
    return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
      card: function card(cardProps) {
        var _cardProps = _objectSpread({}, cardProps);
        var isExpand = getExpand(level);
        _cardProps.text = expandConfigData[isExpand ? 'active' : 'inactive'].text;
        _cardProps.prefixIcon = /*#__PURE__*/React.createElement(Iconfont, {
          type: expandConfigData[isExpand ? 'active' : 'inactive'].icon,
          style: {
            color: '#fff',
            fontSize: 20
          }
        });
        return renderLevelNCard(_cardProps, level);
      },
      onClick: function onClick() {
        toggleExpand(level);
      }
    }));
  }, [expand]);
  var renderSearch = useCallback(function (itemProps, level) {
    return /*#__PURE__*/React.createElement(PisellFind, {
      showHistory: false,
      modalWidth: '100%',
      ref: searchRef,
      onSearch: function onSearch(e) {
        _onSearch === null || _onSearch === void 0 || _onSearch(e);
      },
      getContainer: function getContainer() {
        return document.querySelector('#sku-list-tabbar') || document.body;
      },
      modalStyle: {
        width: '100%'
      },
      onOpen: openSearchMode,
      onClose: closeSearchMode,
      trigger: /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
        card: function card(cardProps) {
          var _cardProps = _objectSpread(_objectSpread({}, cardProps), {}, {
            text: /*#__PURE__*/React.createElement("div", {
              style: {
                display: 'flex',
                alignItems: 'center',
                gap: 4
              }
            }, /*#__PURE__*/React.createElement(Iconfont, {
              type: "pisell2-search-lg",
              style: {
                color: '#fff',
                fontSize: 20
              }
            }), /*#__PURE__*/React.createElement(Iconfont, {
              type: "pisell2-scan",
              style: {
                color: '#fff',
                fontSize: 20
              }
            }), /*#__PURE__*/React.createElement("span", null, getText('table-filter-find')))
          });
          return renderLevelNCard(_cardProps, level);
        }
      }))
    });
  }, [activeKey]);
  /**
   * 渲染一级 Tab 项
   */
  var renderLevel1Item = useCallback(function (itemProps) {
    var itemData = itemProps.dataSource;
    // 处理自定义点击事件的项（如展开按钮）
    if (itemData !== null && itemData !== void 0 && itemData.customClick) {
      if (itemProps.dataSource.key === 'search') {
        return renderSearch(itemProps, 'level1');
      }
      if (itemProps.dataSource.key === 'expand') {
        return renderExpand(itemProps, 'level1');
      }
      return null;
    }

    // 普通项
    return /*#__PURE__*/React.createElement(PisellCards.MultilevelCard, _extends({}, itemProps, {
      card: function card(cardProps) {
        return renderLevelNNormalCard(cardProps, 'level1');
      },
      panel: function panel(panelProps) {
        var _panelProps$dataSourc;
        if (panelProps !== null && panelProps !== void 0 && (_panelProps$dataSourc = panelProps.dataSource) !== null && _panelProps$dataSourc !== void 0 && (_panelProps$dataSourc = _panelProps$dataSourc.children) !== null && _panelProps$dataSourc !== void 0 && _panelProps$dataSourc.length) {
          return renderLevel2(panelProps);
        }
        return null;
      },
      panelContainer: function panelContainer() {
        return document.querySelector(".pisell-super-tabs-slot-bottom-sku-list-tabbar");
      }
    }));
  }, [activeKey, getLevelConfig, getExpand, toggleExpand, renderLevelNCard, renderLevelNNormalCard, renderLevel2]);

  // 获取一级配置
  var level1Config = getLevelConfig('level1');
  var level1Expand = getExpand('level1');
  return dataSource.length ? /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-tabbar', className),
    style: style,
    ref: containerRef
  }, /*#__PURE__*/React.createElement(SuperTabs, {
    isControlled: true,
    id: "sku-list-tabbar",
    tabItemStyle: {},
    dataSource: level1DataSource,
    value: level1Value,
    onChange: handleLevel1Change,
    rowKey: "id",
    style: {
      flex: 1,
      background: level1Config.superTabsBg
    },
    gridProps: {
      direction: 'horizontal',
      gap: 4,
      wrap: level1Expand ? 'wrap' : 'nowrap'
    },
    scrollViewProps: {
      style: {
        padding: '4px 8px'
      },
      overflow: !level1Expand ? 'x' : 'hidden',
      scrollbarStyle: 'none',
      scrollActionsConfig: {
        type: 'lrArrows',
        show: true
      }
    },
    renderItem: renderLevel1Item
  })) : null;
});
PisellTabbar.displayName = 'PisellTabbar';
export default PisellTabbar;