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 _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 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, { useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { Button, Space, Segmented } from 'antd';
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 { locales as utilsLocales } from '@pisell/utils';
import { getText } from "../../../../locales";
import "./ToolBarFilter.less";
import "./recordBoardToolbar.less";

/** 与 Quick Filter 同源：优先 utils，若 utils 返回 key（未命中）则用 materials 再回退 */
function getSortButtonText() {
  var key = 'pisell2.recordBoard.toolbar.sort';
  var u = utilsLocales.getText(key);
  return u && u !== key ? u : getText(key) || getText('sort-button-text');
}
function getFilterButtonText() {
  var key = 'pisell2.recordBoard.toolbar.filter';
  var u = utilsLocales.getText(key);
  return u && u !== key ? u : getText(key) || getText('table-action-filter-button');
}
function getViewGridLabel() {
  var key = 'pisell2.recordBoard.toolbar.viewGrid';
  var u = utilsLocales.getText(key);
  return u && u !== key ? u : getText(key) || 'Table';
}
function getViewFloorMapLabel() {
  var key = 'pisell2.recordBoard.toolbar.viewFloorMap';
  var u = utilsLocales.getText(key);
  return u && u !== key ? u : getText(key) || 'Floor map';
}
import { deriveFilterFromColumns, deriveSortFromColumns } from "../../utils/recordBoardColumns";

/** 默认搜索参数字段名，与 context.searchParams 对应 */
var DEFAULT_SEARCH_FIELD = 'keyword';

/** 筛选在 searchParams 中的字段名 */
var FILTER_PARAMS_FIELD = 'filter';

/** 排序在 searchParams 中的字段名 */
var SORT_PARAMS_FIELD = 'sort';

/** 筛选无值时使用的默认筛选项，避免点开为空；业务可通过 childComponentProps.toolBar.filter.defaultFilterValue 覆盖。文案通过 getText 多语言。 */
function getDefaultFilterValue() {
  return {
    quickFilter: [],
    otherFilter: []
  };
}

/**
 * RecordBoard 下的工具栏：使用 PisellToolBar。
 * 左侧默认 PisellFind（inline）；右侧默认 PisellFilter。通过 childComponentProps.toolBar.search / toolBar.filter 为对象时透传对应组件 props，为 false 时不渲染。
 * 可透传 topLeft、topRight、bottomLeft、bottomRight、tabs。
 */
var RecordBoardToolBar = function RecordBoardToolBar(props) {
  var _shellMeta$hasGridCon, _shellMeta$hasFloorMa, _shellMeta$effectiveF, _ctx$childComponentPr, _ctx$childComponentPr2, _searchParams$DEFAULT, _ctx$childComponentPr3, _formFiltersPrefix, _size, _filterResetKey;
  var ctx = useRecordBoardContext({
    displayName: 'toolBar'
  });
  var shellMeta = useRecordBoardShellBodyMeta();
  var searchParams = ctx.searchParams,
    onSearch = ctx.onSearch,
    bodyView = ctx.bodyView,
    setBodyView = ctx.setBodyView;
  /** ShellFrame 内解析：双视图（表格区 + FloorMap）才出现切换器；根级 floorMap 无子组件时仍兼容 */
  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 floorForToggle = (_shellMeta$effectiveF = shellMeta === null || shellMeta === void 0 ? void 0 : shellMeta.effectiveFloorMapProps) !== null && _shellMeta$effectiveF !== void 0 ? _shellMeta$effectiveF : ctx.floorMapProps;
  var showTableFloorToggle = hasGridInShell && hasFloorInShell && floorForToggle != null;
  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 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;

  /** 默认 inline：triggerType="input" + displayType="inline"，放在 toolbar 左侧。showConfirmButton 优先取 toolBar.search，未配置时默认 true。 */
  var searchNode = hideSearch ? null : /*#__PURE__*/React.createElement(PisellFind, _extends({
    triggerType: "input",
    displayType: "inline",
    showConfirmButton: _typeof(searchConfig) === 'object' && searchConfig !== null && 'showConfirmButton' in searchConfig ? searchConfig.showConfirmButton : true,
    value: keyword,
    onChange: function onChange(v) {
      return handleSearch(v);
    },
    onSearch: handleSearch
  }, _typeof(searchConfig) === 'object' && searchConfig !== null ? searchConfig : {}));

  // 快筛统一放在左侧 QuickFilter；右侧 Filter 弹层只保留高级筛选，不展示快筛
  var quickFilterConfig = slots.quickFilter;
  var quickFilterList = useMemo(function () {
    var _ref;
    if (quickFilterConfig === false) return [];
    var fromConfig = _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null && Array.isArray(quickFilterConfig.filterList) ? quickFilterConfig.filterList : null;
    var list = (_ref = fromConfig !== null && fromConfig !== void 0 ? fromConfig : derivedFilterFromColumns === null || derivedFilterFromColumns === void 0 ? void 0 : derivedFilterFromColumns.quickFilter) !== null && _ref !== void 0 ? _ref : [];
    var hideNames = _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null && Array.isArray(quickFilterConfig.hideFilterNamesOnFloorMap) ? quickFilterConfig.hideFilterNamesOnFloorMap : null;
    if (bodyView === 'floorMap' && 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]);
  var showQuickFilterLeft = quickFilterList.length > 0;
  var quickFilterNode = showQuickFilterLeft ? /*#__PURE__*/React.createElement(ToolBarQuickFilter, {
    filterList: quickFilterList,
    formFiltersPrefix: _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null ? (_formFiltersPrefix = quickFilterConfig.formFiltersPrefix) !== null && _formFiltersPrefix !== void 0 ? _formFiltersPrefix : '' : '',
    size: _typeof(quickFilterConfig) === 'object' && quickFilterConfig !== null ? (_size = quickFilterConfig.size) !== null && _size !== void 0 ? _size : 'large' : 'large'
  }) : null;
  var bodyViewToggle = showTableFloorToggle ? /*#__PURE__*/React.createElement(Segmented, {
    className: "record-board-toolbar-body-view-segmented",
    size: "large",
    value: bodyView,
    onChange: function onChange(v) {
      return setBodyView(v);
    },
    options: [{
      label: getViewFloorMapLabel(),
      value: 'floorMap'
    }, {
      label: getViewGridLabel(),
      value: 'grid'
    }],
    style: {
      marginRight: 8
    }
  }) : null;

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

  /**
   * 仅平面图且 tabs 内含 ScheduleBand 时隐藏顶行切换器；表格视图 tabs 无 ScheduleBand，
   * 切换器回到 Find 左侧（与 PisellReservation 表格态一致）。
   */
  var hideBodyViewToggleInToolbarRow = showTableFloorToggle && Boolean(slots.tabs) && bodyView === 'floorMap';
  var topLeft = compactFloorMapToolbar ? null : /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-top-left"
  }, !hideBodyViewToggleInToolbarRow ? bodyViewToggle : null, quickFilterNode, searchNode ? /*#__PURE__*/React.createElement("div", {
    className: "record-board-toolbar-find-wrap"
  }, searchNode) : null, slots.topLeft);
  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 () {
    var fromConfig = _typeof(sortConfig) === 'object' && sortConfig !== null && Array.isArray(sortConfig.list) ? sortConfig.list : null;
    return fromConfig !== null && fromConfig !== void 0 ? fromConfig : derivedSortFromColumnsList;
  }, [sortConfig, derivedSortFromColumnsList]);
  var sortNode = hideSort ? null : /*#__PURE__*/React.createElement(Sort, _extends({}, _typeof(sortConfig) === 'object' && sortConfig !== null ? sortConfig : {}, {
    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: "large"
    }, getSortButtonText())
  }));
  var filterConfig = slots.filter;
  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 _ref2, _c$key;
        return [(_ref2 = (_c$key = c.key) !== null && _c$key !== void 0 ? _c$key : c.name) !== null && _ref2 !== void 0 ? _ref2 : '', c];
      }));
      otherFilter = otherFilter.map(function (item) {
        var _ref3, _item$key, _configItem$label, _configItem$other$pla, _configItem$other, _item$other;
        var key = (_ref3 = (_item$key = item.key) !== null && _item$key !== void 0 ? _item$key : item.name) !== null && _ref3 !== void 0 ? _ref3 : '';
        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
          })
        });
      });
    }
    return _objectSpread(_objectSpread({}, base), {}, {
      quickFilter: quickFilter,
      otherFilter: otherFilter,
      values: (_base$values = base.values) !== null && _base$values !== void 0 ? _base$values : {}
    });
  }, [filterValue, hasFilterItems, defaultFilterFromConfig, derivedFilterFromColumns]);

  // 右侧 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: "",
    size: "large",
    buttonClassName: "record-board-toolbar-filter-btn",
    hiddenQuickFilter: true,
    placement: "bottomLeft"
  }, _typeof(filterConfig) === 'object' && filterConfig !== null ? filterConfig : {}));
  var showColumnSetting = slots.columnSetting !== false && Array.isArray(gridColumns) && gridColumns.length > 0;
  var topRight = compactFloorMapToolbar ? null : /*#__PURE__*/React.createElement(Space, null, showColumnSetting ? /*#__PURE__*/React.createElement(RecordBoardColumnSetting, null) : null, sortNode, filterNode, /*#__PURE__*/React.createElement(ToolBarReset, {
    size: "large"
  }), slots.topRight);
  return /*#__PURE__*/React.createElement(PisellToolBar, {
    className: classNames(bodyView === 'floorMap' && 'pisell-record-board-toolbar--floor-map', bodyView === 'grid' && 'pisell-record-board-toolbar--grid', 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;