var _excluded = ["filter"],
  _excluded2 = ["filter"];
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 _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); }
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';
import { PisellRecordBoard } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { Select } from 'antd';
import { request } from "../../utils";
import useEngineContext from "../../hooks/useEngineContext";
import useActions from "./hooks/useActions";
import { useSalesGridPhoneLayout } from "./hooks/useSalesGridPhoneLayout";
import LookupSearchInput from "../../pro/comprehensiveSearch/components/lookupSearchInput";
import { useReservationPhoneGridInfiniteData } from "../pisellReservation/hooks/useReservationPhoneGridInfiniteData";
import { defaultPaymentStatusKeys, resolveBookingMonitorColumnStorageKey } from "../pisellSalesManagement/config/booking";
import { getOrderList, getBookingList } from "./serve";
import { applySalesPhoneGridColumns, buildSalesPhoneGridScroll, buildSalesPhoneRowSelection, mergeSalesPhoneGridClassName, withDefaultSalesGridInfiniteScroll } from "./mobileTable/applySalesPhoneGridColumns";
import "./PisellSalesGrid.less";
import orderListLocales from "../orderList/locales";

/**
 * 根据 currentPerspective 从 perspectives 中取当前 Perspective 配置，未找到时回退到第一项或空配置。
 */
function getCurrentPerspectiveConfig(perspectives, currentPerspective) {
  var found = perspectives.find(function (p) {
    return p.key === currentPerspective;
  });
  if (found) return found;
  if (perspectives.length > 0) return perspectives[0];
  return undefined;
}
function getDefaultSearchParams(currentPerspective) {
  if (currentPerspective === 'monitor') {
    return {
      filter: {
        values: {
          order_payment_status: defaultPaymentStatusKeys,
          booking_time_start_between: [dayjs().startOf('day'), dayjs().endOf('day')]
        }
      }
    };
  }
  return {
    filter: {
      values: {
        payment_status: defaultPaymentStatusKeys,
        orderDate: [dayjs(), dayjs()]
      }
    },
    sort: 'created_at:desc'
  };
}
var SEARCH_PARAMS_STORAGE_PREFIX = 'pisell_sales_grid_search_params_';

/**
 * 序列化 searchParams，将 dayjs 对象转换为 ISO 字符串
 */
function serializeSearchParams(params) {
  return JSON.stringify(params, function (key, value) {
    if (dayjs.isDayjs(value)) {
      return {
        __isDayjs: true,
        value: value.toISOString()
      };
    }
    return value;
  });
}

/**
 * 反序列化 searchParams，将 ISO 字符串还原为 dayjs 对象
 */
function deserializeSearchParams(str) {
  return JSON.parse(str, function (key, value) {
    if (value && _typeof(value) === 'object' && value.__isDayjs) {
      return dayjs(value.value);
    }
    return value;
  });
}

/**
 * 仅保留 filter 的 values 和 quickFilter 用于存储，不存 otherFilter（label/options 等）。
 * 恢复时用当前 perspective 的 otherFilter（当前语言），只还原 values。
 */
function normalizeFilterForStorage(filter) {
  var _filter$values;
  if (!filter || _typeof(filter) !== 'object') return filter;
  return {
    values: (_filter$values = filter.values) !== null && _filter$values !== void 0 ? _filter$values : {},
    quickFilter: Array.isArray(filter.quickFilter) ? filter.quickFilter : []
  };
}

/**
 * 默认不持久化筛选条件，只持久化排序、关键词等；筛选项恢复时使用 perspective 默认值。
 * 列显示隐藏由 RecordBoard/Grid 通过 getColumnVisibilityFromLocal 单独持久化。
 */
var PERSIST_FILTER_BY_DEFAULT = false;
/**
 * 分页「每页条数」Select：禁用搜索输入，仅允许从下拉选项中选择。
 * antd 5.10 内置 MiniSelect / MiddleSelect 默认 showSearch=true，会让用户在 Select 里键盘输入；
 * 通过 selectComponentClass 覆盖为 showSearch=false 的 Select。
 *
 * 注意：showSearch={false} 写在 {...props} 之后，确保不会被外部覆盖；其余 prop（value/onChange/
 * size/getPopupContainer/options 等）由 antd Pagination 透传，无需再手动透传。
 */
var PaginationSizeChangerSelect = /*#__PURE__*/React.forwardRef(function (props, ref) {
  return /*#__PURE__*/React.createElement(Select, _extends({}, props, {
    ref: ref,
    showSearch: false
  }));
});
PaginationSizeChangerSelect.Option = Select.Option;

/** 默认的 SalesGrid 分页透传配置：去掉 Select 输入 + 给出明确的可选条数 */
var DEFAULT_PAGINATION_CONFIG = {
  selectComponentClass: PaginationSizeChangerSelect,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
};

/**
 * 从存储还原的 searchParams：filter 只保留 values 和 quickFilter，不保留 otherFilter。
 * 仅当 PERSIST_FILTER_BY_DEFAULT 为 true 时用于还原；否则不还原 filter。
 */
function normalizeRestoredSearchParams(params) {
  if (!params || _typeof(params) !== 'object') return params;
  var filter = params.filter;
  if (!filter || _typeof(filter) !== 'object') return params;
  return _objectSpread(_objectSpread({}, params), {}, {
    filter: normalizeFilterForStorage(filter)
  });
}

/**
 * 从 sessionStorage 获取存储的 searchParams。
 * 默认不还原 filter（仅还原 sort、keyword 等），调用方需与 getDefaultSearchParams 合并以得到默认筛选项。
 */
function getStoredSearchParams(id) {
  try {
    var stored = sessionStorage.getItem("".concat(SEARCH_PARAMS_STORAGE_PREFIX).concat(id));
    if (stored) {
      var parsed = deserializeSearchParams(stored);
      var normalized = PERSIST_FILTER_BY_DEFAULT ? normalizeRestoredSearchParams(parsed) : parsed;
      if (!PERSIST_FILTER_BY_DEFAULT && normalized && _typeof(normalized) === 'object') {
        var _ref = normalized,
          _f = _ref.filter,
          rest = _objectWithoutProperties(_ref, _excluded);
        return rest;
      }
      return normalized;
    }
  } catch (e) {
    console.warn('Failed to get stored search params:', e);
  }
  return null;
}

/**
 * 将 searchParams 存储到 sessionStorage。
 * 默认只存排序、关键词等，不存 filter；列显示隐藏由 RecordBoard 侧单独持久化。
 */
function saveSearchParams(id, params) {
  try {
    var toStore;
    if (PERSIST_FILTER_BY_DEFAULT) {
      toStore = _objectSpread(_objectSpread({}, params), {}, {
        filter: params.filter ? normalizeFilterForStorage(params.filter) : params.filter
      });
    } else {
      var _f = params.filter,
        rest = _objectWithoutProperties(params, _excluded2);
      toStore = rest;
    }
    sessionStorage.setItem("".concat(SEARCH_PARAMS_STORAGE_PREFIX).concat(id), serializeSearchParams(toStore));
  } catch (e) {
    console.warn('Failed to save search params:', e);
  }
}

/**
 * 将 columnRenderers 按列 type 合并进 grid.columns（同 type 覆盖原有 render）。
 */
function mergeColumnRenderersIntoGrid(gridConfig, columnRenderers) {
  if (!(columnRenderers !== null && columnRenderers !== void 0 && columnRenderers.length) || !Array.isArray(gridConfig.columns)) {
    return gridConfig;
  }
  var byType = new Map(columnRenderers.map(function (r) {
    return [r.type, r.render];
  }));
  return _objectSpread(_objectSpread({}, gridConfig), {}, {
    columns: gridConfig.columns.map(function (col) {
      var t = col === null || col === void 0 ? void 0 : col.type;
      if (t != null && byType.has(t)) {
        var renderCell = byType.get(t);
        return _objectSpread(_objectSpread({}, col), {}, {
          render: function render(value, record, index) {
            return renderCell(value, record, index);
          }
        });
      }
      return col;
    })
  });
}
var PisellSalesGrid = function PisellSalesGrid(props) {
  var _context$appHelper, _context$engine, _getBookingList$data2, _getOrderList$data2, _getBookingList$data3, _getOrderList$data3, _currentConfig$childC5, _recordBoardGridProps, _recordBoardGridProps2, _currentConfig$childC6, _currentConfig$childC7, _currentConfig$childC8, _currentConfig$childC9;
  var perspectives = props.perspectives,
    currentPerspective = props.currentPerspective,
    className = props.className,
    style = props.style,
    extParams = props.extParams,
    __id = props.__id,
    propsData = props.data,
    propsLoading = props.loading,
    propsTotal = props.total,
    propsPagination = props.pagination,
    propsOnPageChange = props.onPageChange,
    propsSearchParams = props.searchParams,
    propsOnSearch = props.onSearch,
    propsOnReset = props.onReset,
    propsSelectedKeys = props.selectedKeys,
    propsSelectedRows = props.selectedRows,
    propsOnSelectionChange = props.onSelectionChange,
    propsRowKey = props.rowKey,
    propsOnRefresh = props.onRefresh,
    propsRefreshAsync = props.refreshAsync,
    columnRenderers = props.columnRenderers,
    enableScanner = props.enableScanner;
  var context = useEngineContext();
  var utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
  locales.init(orderListLocales, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en');
  request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
  var isControlledData = propsData !== undefined;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    selectedKeys = _useState2[0],
    setSelectedKeys = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedRows = _useState4[0],
    setSelectedRows = _useState4[1];
  var _useState5 = useState({
      pageNumber: 1,
      pageSize: 20
    }),
    _useState6 = _slicedToArray(_useState5, 2),
    pagination = _useState6[0],
    setPagination = _useState6[1];
  var _useState7 = useState(function () {
      var defaultParams = getDefaultSearchParams(currentPerspective);
      if (__id) {
        var stored = getStoredSearchParams(__id);
        if (stored) {
          return _objectSpread(_objectSpread({}, defaultParams), stored);
        }
      }
      return defaultParams;
    }),
    _useState8 = _slicedToArray(_useState7, 2),
    searchParams = _useState8[0],
    setSearchParams = _useState8[1];
  var _useState9 = useState(null),
    _useState10 = _slicedToArray(_useState9, 2),
    pendingScanSearch = _useState10[0],
    setPendingScanSearch = _useState10[1];
  var onSelectionChange = useCallback(function (keys, rows) {
    setSelectedKeys(keys);
    setSelectedRows(rows);
  }, []);
  var onPageChange = useCallback(function (pageNumber, pageSize) {
    if (pageNumber < 1 || pageSize < 1) return;
    setPagination({
      pageNumber: pageNumber,
      pageSize: pageSize
    });
  }, []);
  var onSearch = useCallback(function (params) {
    setSearchParams(params || {});
    setPagination(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        pageNumber: 1
      });
    });
  }, []);
  var onReset = useCallback(function () {
    setSearchParams(getDefaultSearchParams(currentPerspective));
    setPagination(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        pageNumber: 1
      });
    });
  }, [currentPerspective]);

  // 当 searchParams 改变时，存储到 sessionStorage
  useEffect(function () {
    if (__id) {
      saveSearchParams(__id, searchParams);
    }
  }, [__id, searchParams]);
  useEffect(function () {
    document.body.id = 'body';
  }, []);
  var _getBookingList = useRequest(getBookingList, {
    manual: true
  });
  var _getOrderList = useRequest(getOrderList, {
    manual: true
  });
  var requestParams = useMemo(function () {
    var keyword = searchParams.keyword,
      filter = searchParams.filter,
      sort = searchParams.sort;
    var filterVals = (filter === null || filter === void 0 ? void 0 : filter.values) || {};
    return _objectSpread(_objectSpread({
      keyword: keyword,
      sort: sort
    }, filterVals), {}, {
      skip: pagination.pageNumber,
      num: pagination.pageSize
    });
  }, [searchParams, pagination.pageNumber, pagination.pageSize]);
  var initLoad = useCallback(function (keys) {
    if (propsOnRefresh) {
      propsOnRefresh(keys);
      return;
    }
    if (currentPerspective === 'monitor') {
      _getBookingList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
      return;
    }
    _getOrderList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
  }, [currentPerspective, requestParams, _getBookingList, _getOrderList, propsOnRefresh]);
  var onClearSelection = useCallback(function () {
    setSelectedKeys([]);
    setSelectedRows([]);
    propsOnSelectionChange === null || propsOnSelectionChange === void 0 || propsOnSelectionChange([], []);
  }, [propsOnSelectionChange]);
  var actions = useActions({
    onRefresh: initLoad,
    onClearSelection: onClearSelection
  });
  var isPhoneLayout = useSalesGridPhoneLayout();
  var gridPagination = useMemo(function () {
    return isControlledData && propsPagination ? propsPagination : pagination;
  }, [isControlledData, propsPagination, pagination]);
  var gridSearchParams = useMemo(function () {
    return isControlledData && propsSearchParams !== undefined ? propsSearchParams : searchParams;
  }, [isControlledData, propsSearchParams, searchParams]);
  var rawGridData = useMemo(function () {
    var _getBookingList$data, _getOrderList$data;
    if (isControlledData) {
      return propsData !== null && propsData !== void 0 ? propsData : [];
    }
    return currentPerspective === 'monitor' ? ((_getBookingList$data = _getBookingList.data) === null || _getBookingList$data === void 0 ? void 0 : _getBookingList$data.list) || [] : ((_getOrderList$data = _getOrderList.data) === null || _getOrderList$data === void 0 ? void 0 : _getOrderList$data.list) || [];
  }, [isControlledData, propsData, currentPerspective, (_getBookingList$data2 = _getBookingList.data) === null || _getBookingList$data2 === void 0 ? void 0 : _getBookingList$data2.list, (_getOrderList$data2 = _getOrderList.data) === null || _getOrderList$data2 === void 0 ? void 0 : _getOrderList$data2.list]);
  var phoneGridInfiniteData = useReservationPhoneGridInfiniteData({
    enabled: isPhoneLayout,
    isInternalListData: true,
    rowKey: propsRowKey !== null && propsRowKey !== void 0 ? propsRowKey : 'id',
    data: rawGridData,
    pagination: gridPagination,
    searchParams: gridSearchParams
  });
  var recordBoardListData = isPhoneLayout ? phoneGridInfiniteData : rawGridData;
  var isRecordBoardLoading = isControlledData ? propsLoading !== null && propsLoading !== void 0 ? propsLoading : false : currentPerspective === 'monitor' ? _getBookingList.loading : _getOrderList.loading;
  var recordBoardTotal = isControlledData ? propsTotal : currentPerspective === 'monitor' ? (_getBookingList$data3 = _getBookingList.data) === null || _getBookingList$data3 === void 0 ? void 0 : _getBookingList$data3.count : (_getOrderList$data3 = _getOrderList.data) === null || _getOrderList$data3 === void 0 ? void 0 : _getOrderList$data3.count;
  var batchActionConfig = useMemo(function () {
    return {
      actions: actions
    };
  }, [actions]);
  useEffect(function () {
    if (isControlledData) return;
    if (currentPerspective === 'monitor') {
      _getBookingList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
    } else {
      _getOrderList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
    }
  }, [isControlledData, currentPerspective, requestParams, extParams === null || extParams === void 0 ? void 0 : extParams.list, _getBookingList, _getOrderList]);

  /**
   * 运行时上下文：根据当前 perspective 绑定对应的 refresh / refreshAsync，
   * 传入 perspective 的 getChildComponentProps 工厂函数。
   * 受控数据时优先使用父组件传入的 onRefresh / refreshAsync。
   */
  var runtimeContext = useMemo(function () {
    if (isControlledData && propsOnRefresh) {
      return {
        refresh: propsOnRefresh,
        refreshAsync: propsRefreshAsync !== null && propsRefreshAsync !== void 0 ? propsRefreshAsync : function () {
          return Promise.resolve();
        },
        currentPerspective: currentPerspective
      };
    }
    return {
      refresh: currentPerspective === 'monitor' ? function () {
        return _getBookingList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
      } : function () {
        return _getOrderList.run(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
      },
      refreshAsync: currentPerspective === 'monitor' ? function () {
        return _getBookingList.runAsync(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
      } : function () {
        return _getOrderList.runAsync(_objectSpread(_objectSpread({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
      },
      currentPerspective: currentPerspective
    };
  }, [isControlledData, propsOnRefresh, propsRefreshAsync, currentPerspective, _getBookingList, _getOrderList, requestParams, extParams]);

  /**
   * 解析当前 perspective 配置：
   * - 若 perspective 提供了 getChildComponentProps 工厂，调用它并注入 runtimeContext；
   * - 否则回退到静态 childComponentProps（向后兼容）。
   */
  var currentConfig = useMemo(function () {
    var raw = getCurrentPerspectiveConfig(perspectives, currentPerspective);
    if (!raw) return undefined;
    if (typeof raw.getChildComponentProps === 'function') {
      return _objectSpread(_objectSpread({}, raw), {}, {
        childComponentProps: raw.getChildComponentProps(runtimeContext)
      });
    }
    return raw;
  }, [perspectives, currentPerspective, runtimeContext]);
  var recordBoardGridProps = useMemo(function () {
    var _currentConfig$childC, _currentConfig$childC2;
    var gridConfig = mergeColumnRenderersIntoGrid((_currentConfig$childC = currentConfig === null || currentConfig === void 0 || (_currentConfig$childC2 = currentConfig.childComponentProps) === null || _currentConfig$childC2 === void 0 ? void 0 : _currentConfig$childC2.grid) !== null && _currentConfig$childC !== void 0 ? _currentConfig$childC : {}, columnRenderers);
    var scrollBase = gridConfig.scroll != null && _typeof(gridConfig.scroll) === 'object' ? _objectSpread({}, gridConfig.scroll) : {};
    var keys = isControlledData && propsSelectedKeys !== undefined ? propsSelectedKeys : selectedKeys;
    var rows = isControlledData && propsSelectedRows !== undefined ? propsSelectedRows : selectedRows;
    var onSel = isControlledData && propsOnSelectionChange ? propsOnSelectionChange : onSelectionChange;
    var phoneScroll = isPhoneLayout ? buildSalesPhoneGridScroll(scrollBase) : undefined;
    var phoneGridOverrides = isPhoneLayout ? {
      size: 'small',
      tableLayout: 'fixed',
      infiniteScroll: gridConfig.infiniteScroll !== false,
      scroll: phoneScroll,
      rowSelection: buildSalesPhoneRowSelection(gridConfig.rowSelection),
      className: mergeSalesPhoneGridClassName(typeof gridConfig.className === 'string' ? gridConfig.className : undefined),
      columns: applySalesPhoneGridColumns(gridConfig.columns)
    } : {};

    /**
     * 默认开启虚拟滚动：perspective 未显式配置 virtual，且能确定数值 scroll.y
     *（autoCalc 或显式数值 y）时生效。手机端触底无限滚动不影响表体虚拟滚动。
     */
    var scrollForVirtual = phoneScroll !== null && phoneScroll !== void 0 ? phoneScroll : scrollBase;
    var hasResolvableHeight = scrollForVirtual.autoCalc === true || typeof scrollForVirtual.y === 'number';
    var virtualOverride = gridConfig.virtual == null && hasResolvableHeight ? {
      virtual: true
    } : {};
    return withDefaultSalesGridInfiniteScroll(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, gridConfig), phoneGridOverrides), virtualOverride), {}, {
      selectedKeys: keys,
      selectedRows: rows,
      onSelectionChange: onSel
    }));
  }, [currentConfig, isControlledData, propsSelectedKeys, propsSelectedRows, propsOnSelectionChange, selectedKeys, selectedRows, onSelectionChange, columnRenderers, isPhoneLayout]);
  var mergedToolBar = useMemo(function () {
    var _currentConfig$childC3;
    var base = currentConfig === null || currentConfig === void 0 || (_currentConfig$childC3 = currentConfig.childComponentProps) === null || _currentConfig$childC3 === void 0 ? void 0 : _currentConfig$childC3.toolBar;
    var wrapSearchConfig = function wrapSearchConfig(searchConfig) {
      if (searchConfig === false) return false;
      var searchProps = _typeof(searchConfig) === 'object' && searchConfig !== null ? searchConfig : {};
      var originalOnScan = typeof searchProps.onScan === 'function' ? searchProps.onScan : undefined;
      var originalOnScannerData = typeof searchProps.onScannerData === 'function' ? searchProps.onScannerData : undefined;
      var originalInputRender = typeof searchProps.inputRender === 'function' ? searchProps.inputRender : undefined;

      /** 上层（如 PisellSalesManagement 基于 context.isActive）覆盖 enableScanner；显式 false 时上层关闭，否则尊重 search 配置原值 */
      var mergedEnableScanner = typeof enableScanner === 'boolean' ? enableScanner : searchProps.enableScanner;
      return _objectSpread(_objectSpread({
        /** 默认搜索防抖 300ms（输入即时回显、防抖提交）；perspective 的 search.searchDebounce 可覆盖 */
        searchDebounce: 300
      }, searchProps), {}, {
        enableScanner: mergedEnableScanner,
        onScan: function onScan(code) {
          setPendingScanSearch({
            keyword: code,
            hasRequested: false
          });
          originalOnScan === null || originalOnScan === void 0 || originalOnScan(code);
        },
        /** 扫码枪事件（nativeScanResult）：把 code 作为关键词触发后续「命中唯一行自动进入」流程 */
        onScannerData: function onScannerData(payload) {
          var keyword = typeof (payload === null || payload === void 0 ? void 0 : payload.data) === 'string' ? payload.data : '';
          if (keyword) {
            setPendingScanSearch({
              keyword: keyword,
              hasRequested: false
            });
          }
          originalOnScannerData === null || originalOnScannerData === void 0 || originalOnScannerData(payload);
        },
        inputRender: originalInputRender !== null && originalInputRender !== void 0 ? originalInputRender : function (ctx) {
          return /*#__PURE__*/React.createElement(LookupSearchInput, {
            ctx: ctx,
            showSearchButton: searchProps.showConfirmButton !== false
          });
        }
      });
    };
    if (!base) {
      return {
        search: wrapSearchConfig(undefined)
      };
    }
    if (!isPhoneLayout) {
      return _objectSpread(_objectSpread({}, base), {}, {
        search: wrapSearchConfig(base.search)
      });
    }
    var baseClass = typeof base.className === 'string' ? base.className : undefined;
    var narrowClasses = classNames(baseClass, 'pisell-record-board-toolbar--narrow-stack', 'pisell-sales-grid-mobile-toolbar');
    if (base.filter === false) {
      return _objectSpread(_objectSpread({}, base), {}, {
        search: wrapSearchConfig(base.search),
        toolbarDensity: 'compact-narrow',
        className: narrowClasses
      });
    }
    var baseFilter = _typeof(base.filter) === 'object' && base.filter !== null ? base.filter : {};
    return _objectSpread(_objectSpread({}, base), {}, {
      search: wrapSearchConfig(base.search),
      toolbarDensity: 'compact-narrow',
      filter: _objectSpread(_objectSpread({}, baseFilter), {}, {
        phoneLayout: true
      }),
      className: narrowClasses
    });
  }, [currentConfig, isPhoneLayout, enableScanner]);
  useEffect(function () {
    if (!pendingScanSearch) return;
    if (isRecordBoardLoading) {
      if (!pendingScanSearch.hasRequested) {
        setPendingScanSearch(_objectSpread(_objectSpread({}, pendingScanSearch), {}, {
          hasRequested: true
        }));
      }
      return;
    }
    if (!pendingScanSearch.hasRequested) return;
    var currentKeyword = gridSearchParams === null || gridSearchParams === void 0 ? void 0 : gridSearchParams.keyword;
    if (currentKeyword !== pendingScanSearch.keyword) {
      setPendingScanSearch(null);
      return;
    }
    var list = Array.isArray(recordBoardListData) ? recordBoardListData : [];
    var total = typeof recordBoardTotal === 'number' ? recordBoardTotal : list.length;
    if (list.length !== 1 || total !== 1) {
      setPendingScanSearch(null);
      return;
    }
    var onRow = recordBoardGridProps.onRow;
    if (typeof onRow !== 'function') {
      setPendingScanSearch(null);
      return;
    }
    var rowHandlers = onRow(list[0], 0);
    if (typeof (rowHandlers === null || rowHandlers === void 0 ? void 0 : rowHandlers.onClick) === 'function') {
      rowHandlers.onClick({});
    }
    setPendingScanSearch(null);
  }, [pendingScanSearch, isRecordBoardLoading, gridSearchParams === null || gridSearchParams === void 0 ? void 0 : gridSearchParams.keyword, recordBoardListData, recordBoardTotal, recordBoardGridProps]);

  /**
   * 分页透传配置：默认禁用每页条数 Select 的搜索输入；保留 perspective.childComponentProps.pagination 的可覆盖能力。
   */
  var paginationConfig = useMemo(function () {
    var _currentConfig$childC4;
    return _objectSpread(_objectSpread({}, DEFAULT_PAGINATION_CONFIG), currentConfig === null || currentConfig === void 0 || (_currentConfig$childC4 = currentConfig.childComponentProps) === null || _currentConfig$childC4 === void 0 ? void 0 : _currentConfig$childC4.pagination);
  }, [currentConfig === null || currentConfig === void 0 || (_currentConfig$childC5 = currentConfig.childComponentProps) === null || _currentConfig$childC5 === void 0 ? void 0 : _currentConfig$childC5.pagination]);

  /** 预约 Monitor 列序变更时 bump 专用 key，避免沿用旧 `column_order`；订单视角仍用 `__id` */
  var recordBoardColumnStorageKey = useMemo(function () {
    if (currentPerspective === 'monitor') {
      var _resolveBookingMonito;
      return (_resolveBookingMonito = resolveBookingMonitorColumnStorageKey(__id)) !== null && _resolveBookingMonito !== void 0 ? _resolveBookingMonito : __id;
    }
    return __id;
  }, [__id, currentPerspective]);
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-sales-grid', isPhoneLayout && 'pisell-sales-grid--phone', className),
    style: _objectSpread({
      height: '100%',
      minHeight: 0,
      display: 'flex',
      flexDirection: 'column'
    }, style)
  }, /*#__PURE__*/React.createElement(PisellRecordBoard, {
    key: currentPerspective,
    __id: __id,
    columnVisibilityStorageKey: recordBoardColumnStorageKey,
    layoutType: "grid",
    layoutVariant: isPhoneLayout ? 'phone' : 'default',
    rowKey: propsRowKey !== null && propsRowKey !== void 0 ? propsRowKey : 'id',
    data: recordBoardListData,
    loading: isRecordBoardLoading,
    total: recordBoardTotal !== null && recordBoardTotal !== void 0 ? recordBoardTotal : 0,
    pagination: gridPagination,
    onPageChange: isControlledData && propsOnPageChange ? propsOnPageChange : onPageChange,
    searchParams: gridSearchParams,
    onSearch: isControlledData && propsOnSearch ? propsOnSearch : onSearch,
    onReset: isControlledData && propsOnReset ? propsOnReset : onReset,
    fillHeight: (_recordBoardGridProps = (_recordBoardGridProps2 = recordBoardGridProps.scroll) === null || _recordBoardGridProps2 === void 0 ? void 0 : _recordBoardGridProps2.autoCalc) !== null && _recordBoardGridProps !== void 0 ? _recordBoardGridProps : true,
    grid: recordBoardGridProps,
    toolBar: mergedToolBar,
    paginationConfig: paginationConfig,
    search: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC6 = currentConfig.childComponentProps) === null || _currentConfig$childC6 === void 0 ? void 0 : _currentConfig$childC6.search,
    batchActionBar: _objectSpread(_objectSpread({}, batchActionConfig), currentConfig === null || currentConfig === void 0 || (_currentConfig$childC7 = currentConfig.childComponentProps) === null || _currentConfig$childC7 === void 0 ? void 0 : _currentConfig$childC7.batchActionBar),
    floorMap: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC8 = currentConfig.childComponentProps) === null || _currentConfig$childC8 === void 0 ? void 0 : _currentConfig$childC8.floorMap,
    defaultBodyView: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC9 = currentConfig.childComponentProps) === null || _currentConfig$childC9 === void 0 ? void 0 : _currentConfig$childC9.defaultBodyView
  }, /*#__PURE__*/React.createElement(PisellRecordBoard.ShellFrame, null, /*#__PURE__*/React.createElement(PisellRecordBoard.GridLayout, null))));
};
PisellSalesGrid.displayName = 'PisellSalesGrid';
export default PisellSalesGrid;