var _excluded = ["searchDebounce"],
  _excluded2 = ["trigger", "triggerType", "displayType", "triggerText", "triggerIcon", "buttonText"],
  _excluded3 = ["resourceWallSortFieldKeys", "list"];
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 _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 _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; }
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; }
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 _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); }
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';
import { Button, Space, Segmented, Popover } from 'antd';
import { SettingOutlined, SearchOutlined } from '@ant-design/icons';
import SwitchVertical01 from '@pisell/icon/es/SwitchVertical01';
import PisellToolBar from "../../../pisellGridPro/ToolBar";
import { PisellFind } from "../../../pisellFind";
import PisellFilter from "../../../pisellFilter";
import Sort from "../../../sort";
import ToolBarReset from "../ToolBarReset";
import ToolBarQuickFilter from "../ToolBarQuickFilter";
import RecordBoardColumnSetting from "../ColumnSetting";
import { useRecordBoardShellBodyMeta } from "../ShellBodyMetaContext";
import { useRecordBoardContext } from "../../hooks/useRecordBoardContext";
import { getText } from "../../../../locales";
import { deriveFilterFromColumns, deriveSortFromColumns } from "../../utils/recordBoardColumns";
import { DEFAULT_RESOURCE_WALL_STATUS_SORT_FIELD_KEYS, matchesResourceWallStatusSortField } from "../ResourceWall/venueWallUtils";
import { DEFAULT_SEARCH_FIELD, FILTER_PARAMS_FIELD, RESOURCE_WALL_QUICK_FILTER_KEY, SORT_PARAMS_FIELD } from "./recordBoardToolBarConstants";
import { buildResourceWallStatusSortFallbackItem, getDefaultFilterValue, getSortButtonText, getViewCalendarLabel, getViewFloorMapLabel, getViewGridLabel, getViewResourceWallLabel } from "./recordBoardToolBarI18n";
import "./ToolBarFilter.less";
import "./recordBoardToolbar.less";

/**
 * RecordBoard 下的工具栏：使用 PisellToolBar。
 * 左侧默认 PisellFind（inline）；右侧默认 PisellFilter。通过 childComponentProps.toolBar.search / toolBar.filter 为对象时透传对应组件 props，为 false 时不渲染。
 * 可透传 topLeft、topRight、bottomLeft、bottomRight、tabs。
 */
var RecordBoardToolBar = function RecordBoardToolBar(props) {
  var _ctx$resourceWallProp, _ctx$resourceWallProp2, _shellMeta$hasGridCon, _shellMeta$hasFloorMa, _shellMeta$hasCalenda, _shellMeta$hasResourc, _shellMeta$effectiveF, _ctx$childComponentPr, _ctx$childComponentPr2, _slots$toolbarDensity, _searchParams$DEFAULT, _ctx$childComponentPr3, _formFiltersPrefix, _filterResetKey, _slots$topRight;
  var ctx = useRecordBoardContext({
    displayName: 'toolBar'
  });
  var shellMeta = useRecordBoardShellBodyMeta();
  var searchParams = ctx.searchParams,
    onSearch = ctx.onSearch,
    bodyView = ctx.bodyView,
    setBodyView = ctx.setBodyView;
  var resourceWallFilterFieldKey = (_ctx$resourceWallProp = (_ctx$resourceWallProp2 = ctx.resourceWallProps) === null || _ctx$resourceWallProp2 === void 0 ? void 0 : _ctx$resourceWallProp2.filterFieldKey) !== null && _ctx$resourceWallProp !== void 0 ? _ctx$resourceWallProp : RESOURCE_WALL_QUICK_FILTER_KEY;
  /** ShellFrame 内解析：多子视图（表格 / 平面图 / 日历）时渲染 Segmented */
  var hasGridInShell = (_shellMeta$hasGridCon = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.hasGridContent) !== null && _shellMeta$hasGridCon !== void 0 ? _shellMeta$hasGridCon : true;
  var hasFloorInShell = (_shellMeta$hasFloorMa = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.hasFloorMapSlot) !== null && _shellMeta$hasFloorMa !== void 0 ? _shellMeta$hasFloorMa : ctx.floorMapProps != null;
  var hasCalendarInShell = (_shellMeta$hasCalenda = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.hasCalendarSlot) !== null && _shellMeta$hasCalenda !== void 0 ? _shellMeta$hasCalenda : ctx.calendarProps != null;
  var hasResourceWallInShell = (_shellMeta$hasResourc = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.hasResourceWallSlot) !== null && _shellMeta$hasResourc !== void 0 ? _shellMeta$hasResourc : ctx.resourceWallProps != null;
  var floorForToggle = (_shellMeta$effectiveF = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.effectiveFloorMapProps) !== null && _shellMeta$effectiveF !== void 0 ? _shellMeta$effectiveF : ctx.floorMapProps;
  var canFloor = hasFloorInShell && floorForToggle != null;
  var canCalendar = hasCalendarInShell;
  var canResourceWall = hasResourceWallInShell;
  var canGrid = hasGridInShell;
  var bodyViewOptionCount = (canGrid ? 1 : 0) + (canFloor ? 1 : 0) + (canCalendar ? 1 : 0) + (canResourceWall ? 1 : 0);
  /** 至少两种主区时出现切换器（兼容原「仅表格+平面图」） */
  var showTableFloorToggle = bodyViewOptionCount >= 2;
  /** 业务可关闭多视图切换（如场控仅平面图），此时不渲染 Segmented */
  var allowBodyViewToggle = showTableFloorToggle && ctx.bodyViewSwitchable !== false;
  var slots = (_ctx$childComponentPr = (_ctx$childComponentPr2 = ctx.childComponentProps) === null || _ctx$childComponentPr2 === void 0 ? void 0 : _ctx$childComponentPr2.toolBar) !== null && _ctx$childComponentPr !== void 0 ? _ctx$childComponentPr : {};
  var toolbarDensity = (_slots$toolbarDensity = slots.toolbarDensity) !== null && _slots$toolbarDensity !== void 0 ? _slots$toolbarDensity : 'default';
  var isCompactNarrow = toolbarDensity === 'compact-narrow';
  /**
   * compact 用 middle：比 50px Figma 略紧凑，又比 small 更易点按；与下方 Less 中 ~38px 工具栏样式一致。
   * compact-narrow 进一步缩到 small：极窄抽屉内顶栏右侧为 search 图标 + 齿轮（列/排序/筛选/重置在齿轮内）。
   */
  var barSize = isCompactNarrow ? 'small' : toolbarDensity === 'compact' ? 'middle' : 'large';
  var filterConfig = slots.filter;
  /** 与 PisellFilter 一致：用于顶栏快筛内 FilterItem（如手机端 orderDate 换 antd-mobile） */
  var filterPhoneLayout = _typeof(filterConfig) === 'object' && filterConfig !== null && 'phoneLayout' in filterConfig ? Boolean(filterConfig.phoneLayout) : isCompactNarrow;
  var keyword = (_searchParams$DEFAULT = searchParams === null || searchParams === void 0 ? void 0 : searchParams[DEFAULT_SEARCH_FIELD]) !== null && _searchParams$DEFAULT !== void 0 ? _searchParams$DEFAULT : '';
  var handleSearch = useCallback(function (value) {
    onSearch(_objectSpread(_objectSpread({}, searchParams), {}, _defineProperty({}, DEFAULT_SEARCH_FIELD, value || undefined)));
  }, [onSearch, searchParams]);
  var gridColumns = (_ctx$childComponentPr3 = ctx.childComponentProps) === null || _ctx$childComponentPr3 === void 0 || (_ctx$childComponentPr3 = _ctx$childComponentPr3.grid) === null || _ctx$childComponentPr3 === void 0 ? void 0 : _ctx$childComponentPr3.columns;
  var derivedFilterFromColumns = useMemo(function () {
    return Array.isArray(gridColumns) && gridColumns.length > 0 ? deriveFilterFromColumns(gridColumns) : null;
  }, [gridColumns]);
  var derivedSortFromColumnsList = useMemo(function () {
    return Array.isArray(gridColumns) && gridColumns.length > 0 ? deriveSortFromColumns(gridColumns) : [];
  }, [gridColumns]);
  var searchConfig = slots.search;
  var hideSearch = searchConfig === false;

  /**
   * 搜索防抖：search 配置中 `searchDebounce` 为正数（毫秒）时启用。
   * 启用后：输入框本地即时回显（localKeyword），提交（onSearch -> 拉数）按 searchDebounce 防抖；
   * 复用 PisellFind / PisellLookup 内置的 realtime 防抖（debounceTime）作为唯一防抖来源，
   * 因此输入变化只更新本地回显、不直接提交，避免与内置防抖重复触发请求。
   * 未启用时（默认）：保持历史「每次输入即时触发」的行为，零影响其他 RecordBoard 使用方。
   */
  var searchConfigObj = _typeof(searchConfig) === 'object' && searchConfig !== null ? searchConfig : null;
  var searchDebounceMs = searchConfigObj && typeof searchConfigObj.searchDebounce === 'number' && searchConfigObj.searchDebounce > 0 ? searchConfigObj.searchDebounce : 0;
  var searchDebounceEnabled = searchDebounceMs > 0;

  /** 启用防抖时由 search 配置剔除自定义字段，避免作为未知 prop 透传给 PisellFind */
  var searchConfigRest = useMemo(function () {
    if (!searchConfigObj) return null;
    var _omit = searchConfigObj.searchDebounce,
      rest = _objectWithoutProperties(searchConfigObj, _excluded);
    return rest;
  }, [searchConfigObj]);

  /** 启用防抖时输入框使用本地即时回显值；外部 searchParams.keyword 变化（reset / 扫码）时同步 */
  var _useState = useState(keyword),
    _useState2 = _slicedToArray(_useState, 2),
    localKeyword = _useState2[0],
    setLocalKeyword = _useState2[1];
  useEffect(function () {
    setLocalKeyword(keyword);
  }, [keyword]);
  var searchInputValue = searchDebounceEnabled ? localKeyword : keyword;
  /** 启用防抖：onChange 仅更新本地回显，提交交给内置防抖；未启用：onChange 即时提交 */
  var handleSearchChange = useCallback(function (value) {
    if (searchDebounceEnabled) {
      setLocalKeyword(value);
      return;
    }
    handleSearch(value);
  }, [searchDebounceEnabled, handleSearch]);

  /**
   * - 默认：inline 模式（triggerType="input" + displayType="inline"），常驻输入框
   * - compact-narrow：仅图标触发器（无 Find 文案），放在顶栏右侧与齿轮并排；
   *   Reset 收入齿轮 Popover。传 `trigger={<Button .../>}` 由 PisellLookup 注入 onClick。
   */
  var searchButtonText = getText('pisell2.recordBoard.toolbar.find') || 'Find';
  /**
   * compact-narrow：业务侧 `toolBar.search` 常带 `triggerType=input` / `displayType=inline`，
   * 整对象 spread 在 `triggerType=icon` 之后会把它覆盖回输入框；这里剔除会劫持展示形态的字段。
   */
  var compactNarrowSearchRest = searchConfigRest ? function () {
    var _ref = searchConfigRest,
      _tr = _ref.trigger,
      _tt = _ref.triggerType,
      _dt = _ref.displayType,
      _tx = _ref.triggerText,
      _ti = _ref.triggerIcon,
      _btn = _ref.buttonText,
      rest = _objectWithoutProperties(_ref, _excluded2);
    return rest;
  }() : {};

  /** 业务侧 toolBar.search.enableScanner；compact-narrow 仅在 Find 弹层打开时真正订阅 */
  var searchEnableScannerConfigured = searchConfigRest && _typeof(searchConfigRest) === 'object' && searchConfigRest.enableScanner === true;
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isFindSearchOpen = _useState4[0],
    setIsFindSearchOpen = _useState4[1];
  var searchConfigOnOpen = searchConfigRest === null || searchConfigRest === void 0 ? void 0 : searchConfigRest.onOpen;
  var searchConfigOnClose = searchConfigRest === null || searchConfigRest === void 0 ? void 0 : searchConfigRest.onClose;
  var searchNode = hideSearch ? null : isCompactNarrow ? /*#__PURE__*/React.createElement(PisellFind, _extends({}, compactNarrowSearchRest, searchDebounceEnabled ? {
    debounceTime: searchDebounceMs
  } : {}, {
    value: searchInputValue,
    onChange: handleSearchChange,
    onSearch: handleSearch,
    size: barSize,
    triggerType: "icon",
    className: "record-board-toolbar-find-icon",
    triggerIcon: /*#__PURE__*/React.createElement(SearchOutlined, {
      "aria-label": searchButtonText
    }),
    enableScanner: searchEnableScannerConfigured && isFindSearchOpen,
    onOpen: function onOpen() {
      searchConfigOnOpen === null || searchConfigOnOpen === void 0 || searchConfigOnOpen();
      setIsFindSearchOpen(true);
    },
    onClose: function onClose() {
      searchConfigOnClose === null || searchConfigOnClose === void 0 || searchConfigOnClose();
      setIsFindSearchOpen(false);
    }
  })) : /*#__PURE__*/React.createElement(PisellFind, _extends({
    triggerType: "input",
    displayType: "inline",
    showConfirmButton: searchConfigObj && 'showConfirmButton' in searchConfigObj ? searchConfigObj.showConfirmButton : true
  }, searchDebounceEnabled ? {
    debounceTime: searchDebounceMs
  } : {}, {
    value: searchInputValue,
    onChange: handleSearchChange,
    onSearch: handleSearch
  }, searchConfigRest !== null && searchConfigRest !== void 0 ? searchConfigRest : {}, {
    size: toolbarDensity === 'compact' ? barSize : _typeof(searchConfig) === 'object' && searchConfig !== null && 'size' in searchConfig && searchConfig.size != null ? searchConfig.size : barSize
  }));

  // 快筛统一放在左侧 QuickFilter；右侧 Filter 弹层只保留高级筛选，不展示快筛
  var quickFilterConfig = slots.quickFilter;
  var quickFilterList = useMemo(function () {
    var _ref2;
    if (quickFilterConfig === false) return [];
    var fromConfig = _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null && Array.isArray(quickFilterConfig.filterList) ? quickFilterConfig.filterList : null;
    var list = (_ref2 = fromConfig !== null && fromConfig !== void 0 ? fromConfig : derivedFilterFromColumns === null || derivedFilterFromColumns === void 0 ? void 0 : derivedFilterFromColumns.quickFilter) !== null && _ref2 !== void 0 ? _ref2 : [];
    var hideNames = _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null && Array.isArray(quickFilterConfig.hideFilterNamesOnFloorMap) ? quickFilterConfig.hideFilterNamesOnFloorMap : null;
    if ((bodyView === 'floorMap' || bodyView === 'calendar' || bodyView === 'resourceWall') && showTableFloorToggle && hideNames != null && hideNames.length > 0) {
      var hideSet = new Set(hideNames.map(String));
      list = list.filter(function (item) {
        var _item$name;
        var n = (_item$name = item.name) !== null && _item$name !== void 0 ? _item$name : item.key;
        return n == null || !hideSet.has(String(n));
      });
    }
    return list;
  }, [quickFilterConfig, derivedFilterFromColumns === null || derivedFilterFromColumns === void 0 ? void 0 : derivedFilterFromColumns.quickFilter, bodyView, showTableFloorToggle]);
  /**
   * 资源墙专用快筛不占用顶栏；resourceWall 时顶栏快筛整行收起（改走右侧 Filter）。
   * 资源墙顶栏仅保留 Sort + Filter（Find / Reset 隐藏）。
   * 其它视图从顶栏剔除该字段，避免与表格/平面图等共用 toolBar.quickFilter 时误展示。
   */
  var leftBarQuickFilterList = useMemo(function () {
    var withoutWall = quickFilterList.filter(function (item) {
      var _ref3, _item$key;
      return ((_ref3 = (_item$key = item.key) !== null && _item$key !== void 0 ? _item$key : item.name) !== null && _ref3 !== void 0 ? _ref3 : '') !== resourceWallFilterFieldKey;
    });
    if (bodyView === 'resourceWall') return [];
    return withoutWall;
  }, [bodyView, quickFilterList, resourceWallFilterFieldKey]);
  var showQuickFilterLeft = leftBarQuickFilterList.length > 0;
  var quickFilterNode = showQuickFilterLeft ? /*#__PURE__*/React.createElement(ToolBarQuickFilter, {
    filterList: leftBarQuickFilterList,
    formFiltersPrefix: _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null ? (_formFiltersPrefix = quickFilterConfig.formFiltersPrefix) !== null && _formFiltersPrefix !== void 0 ? _formFiltersPrefix : '' : '',
    size: _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null ? quickFilterConfig.size : undefined,
    phoneLayout: filterPhoneLayout
  }) : null;
  var bodyViewSegmentedOptions = useMemo(function () {
    var opts = [];
    if (canFloor) opts.push({
      label: getViewFloorMapLabel(),
      value: 'floorMap'
    });
    if (canCalendar) opts.push({
      label: getViewCalendarLabel(),
      value: 'calendar'
    });
    if (canResourceWall) {
      opts.push({
        label: getViewResourceWallLabel(),
        value: 'resourceWall'
      });
    }
    if (canGrid) opts.push({
      label: getViewGridLabel(),
      value: 'grid'
    });
    return opts;
  }, [canFloor, canCalendar, canResourceWall, canGrid]);
  var bodyViewToggle = allowBodyViewToggle ? /*#__PURE__*/React.createElement(Segmented, {
    className: "record-board-toolbar-body-view-segmented",
    size: barSize,
    value: bodyView,
    onChange: function onChange(v) {
      return setBodyView(v);
    },
    options: bodyViewSegmentedOptions
  }) : null;

  /** 平面图 / 日历模式：第二行工具（搜索/筛选等）收起；切换器在业务方 tabs 内（如预约 ScheduleBand） */
  var compactFloorMapToolbar = (bodyView === 'floorMap' || bodyView === 'calendar') && showTableFloorToggle;

  /**
   * 仅非表格且 tabs 内含 ScheduleBand（平面图 / 日历）时隐藏顶行切换器；表格 / 资源墙 tabs 无 ScheduleBand，
   * 切换器回到 Find 左侧（与 PisellReservation 表格态一致）。
   */
  var hideBodyViewToggleInToolbarRow = slots.hideBodyViewToggle === true || allowBodyViewToggle && Boolean(slots.tabs) && (bodyView === 'floorMap' || bodyView === 'calendar');
  var sortConfig = slots.sort;
  var hideSort = sortConfig === false;
  var sortValue = searchParams === null || searchParams === void 0 ? void 0 : searchParams[SORT_PARAMS_FIELD];
  var handleSortChange = useCallback(function (val) {
    onSearch(_objectSpread(_objectSpread({}, searchParams), {}, _defineProperty({}, SORT_PARAMS_FIELD, val || undefined)));
  }, [onSearch, searchParams]);
  var sortList = useMemo(function () {
    /** `list: []` 若为 `??` 左值会得到空数组，无法回落到列派生；此处显式在非空时使用配置项 */
    var configuredList = _typeof(sortConfig) === 'object' && sortConfig !== null && Array.isArray(sortConfig.list) ? sortConfig.list : null;
    var base = configuredList != null && configuredList.length > 0 ? configuredList : derivedSortFromColumnsList;
    if (bodyView !== 'resourceWall') {
      return base;
    }
    var extraWallKeys = _typeof(sortConfig) === 'object' && sortConfig !== null && Array.isArray(sortConfig.resourceWallSortFieldKeys) ? sortConfig.resourceWallSortFieldKeys.map(String) : [];
    var allowedKeys = [].concat(_toConsumableArray(DEFAULT_RESOURCE_WALL_STATUS_SORT_FIELD_KEYS.map(String)), _toConsumableArray(extraWallKeys));
    var filtered = base.filter(function (item) {
      return item.name != null && matchesResourceWallStatusSortField(String(item.name), allowedKeys);
    });
    if (filtered.length > 0) return filtered;
    return [buildResourceWallStatusSortFallbackItem(sortConfig)];
  }, [sortConfig, derivedSortFromColumnsList, bodyView]);
  var sortSpreadRest = _typeof(sortConfig) === 'object' && sortConfig !== null ? function () {
    var _ref4 = sortConfig,
      _w = _ref4.resourceWallSortFieldKeys,
      _omitList = _ref4.list,
      rest = _objectWithoutProperties(_ref4, _excluded3);
    return rest;
  }() : {};
  var sortNode = hideSort ? null : /*#__PURE__*/React.createElement(Sort, _extends({}, sortSpreadRest, {
    list: sortList,
    value: sortValue,
    onChange: handleSortChange,
    placement: "bottomLeft",
    button: /*#__PURE__*/React.createElement(Button, {
      className: "record-board-toolbar-filter-btn",
      icon: /*#__PURE__*/React.createElement(SwitchVertical01, null),
      size: barSize
    }, getSortButtonText())
  }));
  var hideFilter = filterConfig === false;
  var filterValue = searchParams === null || searchParams === void 0 ? void 0 : searchParams[FILTER_PARAMS_FIELD];
  var hasFilterList = Array.isArray(filterValue === null || filterValue === void 0 ? void 0 : filterValue.quickFilter) && filterValue.quickFilter.length > 0 || Array.isArray(filterValue === null || filterValue === void 0 ? void 0 : filterValue.otherFilter) && filterValue.otherFilter.length > 0;
  var hasFilterValues = _typeof(filterValue === null || filterValue === void 0 ? void 0 : filterValue.values) === 'object' && filterValue.values !== null && Object.keys(filterValue.values).length > 0;
  var hasFilterItems = hasFilterList || hasFilterValues;
  var defaultFilterFromConfig = _typeof(filterConfig) === 'object' && filterConfig !== null && filterConfig.defaultFilterValue ? filterConfig.defaultFilterValue : null;
  var effectiveFilterValue = useMemo(function () {
    var _defaultFilterFromCon, _defaultFilterFromCon2, _base$values;
    var base = filterValue != null && hasFilterItems ? filterValue : defaultFilterFromConfig ? defaultFilterFromConfig : derivedFilterFromColumns && (derivedFilterFromColumns.quickFilter.length > 0 || derivedFilterFromColumns.otherFilter.length > 0) ? derivedFilterFromColumns : getDefaultFilterValue();
    var quickFilter = Array.isArray(base.quickFilter) && base.quickFilter.length > 0 ? base.quickFilter : (_defaultFilterFromCon = defaultFilterFromConfig === null || defaultFilterFromConfig === void 0 ? void 0 : defaultFilterFromConfig.quickFilter) !== null && _defaultFilterFromCon !== void 0 ? _defaultFilterFromCon : [];
    var otherFilter = Array.isArray(base.otherFilter) && base.otherFilter.length > 0 ? base.otherFilter : (_defaultFilterFromCon2 = defaultFilterFromConfig === null || defaultFilterFromConfig === void 0 ? void 0 : defaultFilterFromConfig.otherFilter) !== null && _defaultFilterFromCon2 !== void 0 ? _defaultFilterFromCon2 : [];
    // 若 otherFilter 来自 base（如 sessionStorage 恢复），JSON 会丢失函数（如 other.component），导致 custom 项空白；用 config 同 key 项补回 component/label 等
    if (otherFilter === base.otherFilter && Array.isArray(defaultFilterFromConfig === null || defaultFilterFromConfig === void 0 ? void 0 : defaultFilterFromConfig.otherFilter) && defaultFilterFromConfig.otherFilter.length > 0) {
      var configMap = new Map(defaultFilterFromConfig.otherFilter.map(function (c) {
        var _ref5, _c$key;
        return [(_ref5 = (_c$key = c.key) !== null && _c$key !== void 0 ? _c$key : c.name) !== null && _ref5 !== void 0 ? _ref5 : '', c];
      }));
      otherFilter = otherFilter.map(function (item) {
        var _ref6, _item$key2, _configItem$label, _configItem$other$pla, _configItem$other, _item$other;
        var key = (_ref6 = (_item$key2 = item.key) !== null && _item$key2 !== void 0 ? _item$key2 : item.name) !== null && _ref6 !== void 0 ? _ref6 : '';
        var configItem = configMap.get(key);
        if (!configItem) return item;
        // 优先用 config 的 label/placeholder（当前语言），避免 session 恢复的旧语言覆盖
        return _objectSpread(_objectSpread(_objectSpread({}, configItem), item), {}, {
          label: (_configItem$label = configItem.label) !== null && _configItem$label !== void 0 ? _configItem$label : item.label,
          other: _objectSpread(_objectSpread(_objectSpread({}, configItem === null || configItem === void 0 ? void 0 : configItem.other), item === null || item === void 0 ? void 0 : item.other), {}, {
            placeholder: (_configItem$other$pla = configItem === null || configItem === void 0 || (_configItem$other = configItem.other) === null || _configItem$other === void 0 ? void 0 : _configItem$other.placeholder) !== null && _configItem$other$pla !== void 0 ? _configItem$other$pla : item === null || item === void 0 || (_item$other = item.other) === null || _item$other === void 0 ? void 0 : _item$other.placeholder
          })
        });
      });
    }
    var outQuick = quickFilter;
    var outOther = otherFilter;
    /**
     * 资源墙：Filter 弹层只保留「大屏资源多选」一项（与顶栏 quickFilter.filterList 中
     * `resource_wall_resource_ids` 对应），不混入日期快筛 / 业务 otherFilter。
     */
    if (bodyView === 'resourceWall') {
      outQuick = [];
      outOther = quickFilterList.filter(function (item) {
        var _ref7, _item$key3;
        return ((_ref7 = (_item$key3 = item.key) !== null && _item$key3 !== void 0 ? _item$key3 : item.name) !== null && _ref7 !== void 0 ? _ref7 : '') === resourceWallFilterFieldKey;
      }).map(function (item) {
        return _objectSpread({}, item);
      });
    }
    return _objectSpread(_objectSpread({}, base), {}, {
      quickFilter: outQuick,
      otherFilter: outOther,
      values: (_base$values = base.values) !== null && _base$values !== void 0 ? _base$values : {}
    });
  }, [filterValue, hasFilterItems, defaultFilterFromConfig, derivedFilterFromColumns, bodyView, quickFilterList]);

  // 右侧 Filter 只展示高级筛选，快筛全部在左侧
  var filterValueForPisellFilter = useMemo(function () {
    return _objectSpread(_objectSpread({}, effectiveFilterValue), {}, {
      quickFilter: []
    });
  }, [effectiveFilterValue]);
  var handleFilterChange = useCallback(function (value) {
    var _currentFilter$values, _value$values;
    var currentFilter = searchParams === null || searchParams === void 0 ? void 0 : searchParams[FILTER_PARAMS_FIELD];
    var currentValues = (_currentFilter$values = currentFilter === null || currentFilter === void 0 ? void 0 : currentFilter.values) !== null && _currentFilter$values !== void 0 ? _currentFilter$values : {};
    var incomingValues = (_value$values = value === null || value === void 0 ? void 0 : value.values) !== null && _value$values !== void 0 ? _value$values : {};
    var nextFilter = _objectSpread(_objectSpread({}, value), {}, {
      values: _objectSpread(_objectSpread({}, currentValues), incomingValues)
    });
    onSearch(_objectSpread(_objectSpread({}, searchParams), {}, _defineProperty({}, FILTER_PARAMS_FIELD, nextFilter)));
  }, [onSearch, searchParams]);
  var filterResetKey = (_filterResetKey = ctx.filterResetKey) !== null && _filterResetKey !== void 0 ? _filterResetKey : 0;
  var filterNode = hideFilter ? null : /*#__PURE__*/React.createElement(PisellFilter, _extends({
    key: "record-board-filter-".concat(filterResetKey),
    value: filterValueForPisellFilter,
    onChange: handleFilterChange,
    hasForm: true,
    quickFilterMaxLength: 100,
    formFiltersPrefix: "",
    hiddenQuickFilter: true,
    placement: "bottomLeft"
  }, _typeof(filterConfig) === 'object' && filterConfig !== null ? filterConfig : {}, {
    phoneLayout: filterPhoneLayout,
    size: barSize,
    buttonClassName: "record-board-toolbar-filter-btn"
  }));
  var showColumnSetting = slots.columnSetting !== false && bodyView !== 'resourceWall' && Array.isArray(gridColumns) && gridColumns.length > 0;

  /**
   * 收纳到齿轮：compact-narrow 始终收纳；桌面在 `collapseActions==='gear'` 时 opt-in 收纳。
   */
  var collapseActionsToGear = slots.collapseActions === 'gear';
  var shouldCollapseToGear = isCompactNarrow || collapseActionsToGear;

  /**
   * compact-narrow / opt-in：列显示 / 排序 / 筛选 / 重置 收入齿轮 Popover；顶栏右侧仅保留（搜索图标 +）齿轮。
   */
  var settingsGearPopoverContent = shouldCollapseToGear ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-settings-gear-popover"
  }, showColumnSetting ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-settings-gear-row"
  }, /*#__PURE__*/React.createElement(RecordBoardColumnSetting, null)) : null, sortNode ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-settings-gear-row"
  }, sortNode) : null, filterNode ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-settings-gear-row"
  }, filterNode) : null, bodyView !== 'resourceWall' ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-settings-gear-row"
  }, /*#__PURE__*/React.createElement(ToolBarReset, {
    size: barSize
  })) : null) : null;
  var settingsGearTrigger = settingsGearPopoverContent != null ? /*#__PURE__*/React.createElement(Popover, {
    content: settingsGearPopoverContent,
    trigger: "click",
    placement: "bottomRight",
    arrow: false,
    overlayClassName: classNames('record-board-toolbar-settings-gear-overlay', isCompactNarrow && 'record-board-toolbar-settings-gear-overlay--compact-narrow', !isCompactNarrow && collapseActionsToGear && 'record-board-toolbar-settings-gear-overlay--collapsed-actions')
  }, /*#__PURE__*/React.createElement(Button, {
    className: "record-board-toolbar-settings-gear-btn",
    icon: /*#__PURE__*/React.createElement(SettingOutlined, null),
    size: barSize,
    type: "text",
    "aria-label": getText('pisell2.recordBoard.toolbar.moreSettings') || 'More settings'
  })) : null;
  var mergeQuickFilterWithCompactTrailing = isCompactNarrow && slots.mergeCompactNarrowTrailingWithQuickFilterRow === true && showQuickFilterLeft;
  var compactNarrowTrailingCluster = isCompactNarrow ? /*#__PURE__*/React.createElement(Space, {
    className: classNames('record-board-toolbar-right-actions', mergeQuickFilterWithCompactTrailing && 'record-board-toolbar-hud-trailing-cluster'),
    size: 4
  }, bodyView !== 'resourceWall' && searchNode ? searchNode : null, settingsGearTrigger) : null;
  var topLeft = compactFloorMapToolbar ? null : /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-top-left"
  }, !hideBodyViewToggleInToolbarRow ? bodyViewToggle : null, mergeQuickFilterWithCompactTrailing && quickFilterNode ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-hud-unified-quick-filter-row"
  }, /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-quick-filter-slot"
  }, quickFilterNode), compactNarrowTrailingCluster) : quickFilterNode ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-quick-filter-slot"
  }, quickFilterNode) : null, searchNode && bodyView !== 'resourceWall' && !isCompactNarrow ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-find-wrap"
  }, searchNode) : null, slots.topLeft ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-extra-top-left"
  }, slots.topLeft) : null);
  var topRight = compactFloorMapToolbar ? null : isCompactNarrow ? mergeQuickFilterWithCompactTrailing ? (_slots$topRight = slots.topRight) !== null && _slots$topRight !== void 0 ? _slots$topRight : null : /*#__PURE__*/React.createElement(Space, {
    className: "record-board-toolbar-right-actions",
    size: 4
  }, bodyView !== 'resourceWall' && searchNode ? searchNode : null, settingsGearTrigger, slots.topRight) : collapseActionsToGear && settingsGearTrigger ? /*#__PURE__*/React.createElement(Space, {
    className: "record-board-toolbar-right-actions",
    size: 8
  }, settingsGearTrigger, slots.topRight) : /*#__PURE__*/React.createElement(Space, {
    className: "record-board-toolbar-right-actions"
  }, showColumnSetting ? /*#__PURE__*/React.createElement(RecordBoardColumnSetting, null) : null, sortNode, filterNode, bodyView !== 'resourceWall' ? /*#__PURE__*/React.createElement(ToolBarReset, {
    size: barSize
  }) : null, slots.topRight);
  return /*#__PURE__*/React.createElement(PisellToolBar, {
    className: classNames(bodyView === 'floorMap' && 'pisell-record-board-toolbar--floor-map', bodyView === 'calendar' && 'pisell-record-board-toolbar--calendar', bodyView === 'resourceWall' && 'pisell-record-board-toolbar--resource-wall', bodyView === 'grid' && 'pisell-record-board-toolbar--grid', toolbarDensity === 'compact' && 'pisell-record-board-toolbar--compact', isCompactNarrow && 'pisell-record-board-toolbar--compact pisell-record-board-toolbar--compact-narrow', slots.className),
    style: slots.style,
    tabs: slots.tabs,
    topLeft: topLeft,
    topRight: topRight,
    bottomLeft: compactFloorMapToolbar ? null : slots.bottomLeft,
    bottomRight: compactFloorMapToolbar ? null : slots.bottomRight
  });
};
RecordBoardToolBar.displayName = 'RecordBoard.ToolBar';
export default RecordBoardToolBar;