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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Spin } from 'antd';
import List from 'rc-virtual-list';
// @ts-ignore
import { locales } from '@pisell/utils';
import { PisellConfigProvider } from '@pisell/materials';
import { LocalizationProvider } from '@pisell/date-picker';
import { AdapterDayjs } from '@pisell/date-picker/es/AdapterDayjs';
import PisellSalesGrid from "../../pisellSalesGrid";
import { useOrderPerspective } from "../../pisellSalesManagement/hooks/useOrderPerspective";
import orderListLocales from "../../orderList/locales";
import salesManagementLocales from "../../pisellSalesManagement/locales";
import useEngineContext from "../../../hooks/useEngineContext";
import RefreshableSaleDetail from "../components/RefreshableSaleDetail";
import { getSalesOrderId, mapGridFiltersToEs, parseSortKey } from "../api/searchService";
import { useEsSalesGridData } from "../hooks/useEsSalesGridData";
import { bumpOrderDetailRefreshVersions, getDetailRefreshVersion } from "../utils/detailRefresh";

/**
 * 订单结果区共享视图（salesProvider 使用）。
 *
 * - 管理模式（admin）：OrderAdminGrid → ES 数据驱动的订单表格（滚动加载 + 列筛选/排序）；
 * - 业务模式（business / 精确搜索）：OrderBusinessDetails → 命中订单逐条内联展示 SaleDetail。
 */

/**
 * 兜底：PisellSalesGrid / SaleDetail 依赖 admin engine context（pisell1.* action /
 * request / OS 模块），脱离 admin lowcode 环境单独运行会崩。
 * 用 ErrorBoundary 包一层，崩了显示提示而不是整个搜索面板炸掉。
 */
export var OrderTableFallbackBoundary = /*#__PURE__*/function (_React$Component) {
  _inherits(OrderTableFallbackBoundary, _React$Component);
  var _super = _createSuper(OrderTableFallbackBoundary);
  function OrderTableFallbackBoundary(props) {
    var _this;
    _classCallCheck(this, OrderTableFallbackBoundary);
    _this = _super.call(this, props);
    _this.state = {
      hasError: false
    };
    return _this;
  }
  _createClass(OrderTableFallbackBoundary, [{
    key: "componentDidCatch",
    value: function componentDidCatch(error) {
      if (process.env.NODE_ENV !== 'production') {
        console.warn('[PisellGlobalSearch] 订单结果渲染失败，可能不在 admin engine 环境：', error);
      }
    }
  }, {
    key: "render",
    value: function render() {
      if (this.state.hasError) {
        return /*#__PURE__*/React.createElement("div", {
          style: {
            padding: 24,
            border: '1px dashed #e5e7eb',
            borderRadius: 8,
            background: '#fafafa',
            color: '#6b7280',
            fontSize: 13,
            lineHeight: 1.6
          }
        }, /*#__PURE__*/React.createElement("div", {
          style: {
            fontWeight: 600,
            color: '#111827',
            marginBottom: 4
          }
        }, locales.getText('pisell-global-search.order-result-unavailable.title')), /*#__PURE__*/React.createElement("div", null, locales.getText('pisell-global-search.order-result-unavailable.description')));
      }
      return this.props.children;
    }
  }], [{
    key: "getDerivedStateFromError",
    value: function getDerivedStateFromError() {
      return {
        hasError: true
      };
    }
  }]);
  return OrderTableFallbackBoundary;
}(React.Component);

/**
 * 业务模式（精确搜索）内容区：把命中的订单详情逐条排下去展示。
 *
 * - loading 且暂无结果 → Spin；
 * - 搜了但 0 条 → 空态；
 * - 多条 → 每条用 SaleDetail（renderType='current'）内联展示，竖向排列；
 * - 每条用独立 osKey（按订单 id 区分）隔离 SDK 实例，避免相互覆盖；
 * - 每条用 ErrorBoundary 兜底（脱离 admin engine 环境时优雅降级）。
 */
export var OrderBusinessDetails = function OrderBusinessDetails(_ref) {
  var items = _ref.items,
    loading = _ref.loading,
    keyword = _ref.keyword,
    _ref$detailRefreshVer = _ref.detailRefreshVersions,
    detailRefreshVersions = _ref$detailRefreshVer === void 0 ? {} : _ref$detailRefreshVer;
  var detailItems = items.map(function (item) {
    return {
      item: item,
      id: getSalesOrderId(item)
    };
  }).filter(function (entry) {
    return entry.id !== undefined;
  });
  if (loading && detailItems.length === 0) {
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-global-search-order-business__status"
    }, /*#__PURE__*/React.createElement(Spin, null));
  }

  // 空 keyword 的 idle 提示由外层壳层处理；这里只处理「搜了但 0 条」
  if (keyword && detailItems.length === 0) {
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-global-search-order-business__status pisell-global-search__empty"
    }, locales.getText('pisell-global-search.empty'));
  }
  if (detailItems.length === 0) return null;
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business"
  }, detailItems.map(function (_ref2) {
    var item = _ref2.item,
      id = _ref2.id;
    var refreshVersion = getDetailRefreshVersion(detailRefreshVersions, 'order', id);
    // key / osKey 保持稳定（仅按订单 id），避免实时刷新版本变化导致 SaleDetail 整块 remount 闪烁；
    // refreshVersion 通过 ref 命令式刷新（RefreshableSaleDetail）就地更新详情。
    var osKey = "global-search-business-detail-".concat(id);
    return /*#__PURE__*/React.createElement("div", {
      key: osKey,
      className: "pisell-global-search-order-business__item"
    }, /*#__PURE__*/React.createElement(OrderTableFallbackBoundary, null, /*#__PURE__*/React.createElement(RefreshableSaleDetail, {
      refreshVersion: refreshVersion,
      renderType: "current"
      // 与右栏详情统一：固定模板 A + 平板变体（覆盖 withResponsive 注入的 desktop）。
      ,
      tmpl: "B",
      variant: "tablet"
      // 业务模式详情够宽时也走两栏（金额明细 + 操作按钮抽到右列、按钮一行一个）。
      ,
      summaryTwoColumn: true,
      osProps: {
        osKey: osKey,
        orderId: Number(id),
        preloadedSalesDetail: item,
        autoBootstrap: true,
        destroyOnUnmount: true
      }
    })));
  }));
};

/** 业务列表虚拟滚动：单行预估高度（SaleDetail 较高，仅作初值，实际高度由 rc-virtual-list 自动测量）。 */
var BUSINESS_ROW_ESTIMATED_HEIGHT = 360;
/** 业务列表每页条数。 */
var BUSINESS_PAGE_SIZE = 5;
/** 触底阈值：距底部小于这个像素就预加载下一页。 */
var BUSINESS_LOAD_MORE_THRESHOLD = BUSINESS_ROW_ESTIMATED_HEIGHT;
/** 底部「加载下一页」提示条的高度（加载时从列表高度里让出，避免覆盖最后一条详情）。 */
var BUSINESS_LOADER_HEIGHT = 44;
/**
 * 虚拟滚动开关（业务单 tab 订单列表）。
 *
 * - `true`：开启虚拟滚动（只渲染可视区行；屏幕外行会卸载、滚回来重拉详情）；
 * - `false`：关闭虚拟化，改为真实滚动**渲染全部已加载行**（不卸载、不重复拉详情），
 *   触底翻页（无限加载）依旧保留。
 *
 * 已开启：单 tab 可能累积加载多页详情，虚拟滚动可控制 DOM 规模。
 */
var BUSINESS_LIST_VIRTUAL_SCROLL = true;

/**
 * 业务模式（精确搜索）**单 Orders tab** 的订单列表（自包含分页 + 触底翻页 + 虚拟滚动）。
 *
 * 与 OrderBusinessDetails（All 分组里的轻量预览）不同，这里：
 * - **自管分页**：用共享 hook `useEsSalesGridData`（search_mode='identifier'，单模块
 *   `/shop/es/search/sales`）自己拉数据并累积，不依赖 provider.search 写入的 state.list；
 * - **触底翻页**：滚到接近底部自动加载下一页并追加；
 * - **虚拟滚动**：用 `rc-virtual-list` 只渲染可视区行，避免一次性渲染大量 SaleDetail 卡顿；
 *   列高动态（SaleDetail 异步 bootstrap 后高度会变），由 rc-virtual-list 自动测量。
 *
 * 注：仅在单 tab 使用（需要确定高度做虚拟滚动）；All 分组仍用 OrderBusinessDetails 预览。
 */
var OrderBusinessListImpl = function OrderBusinessListImpl(_ref3) {
  var keyword = _ref3.keyword;
  var _useState = useState({}),
    _useState2 = _slicedToArray(_useState, 2),
    detailRefreshVersions = _useState2[0],
    setDetailRefreshVersions = _useState2[1];
  // 防止一次触底事件连发多页（loading 翻为 false 后由下方 effect 解锁）。
  var loadingMoreRef = useRef(false);

  /** 实时 delta 命中已加载项后：bump 对应订单的详情刷新版本（列表浅合并已在 hook 内完成）。 */
  var handleDelta = useCallback(function (deltaItems) {
    setDetailRefreshVersions(function (prev) {
      return bumpOrderDetailRefreshVersions(prev, deltaItems);
    });
  }, []);
  var _useEsSalesGridData = useEsSalesGridData({
      keyword: keyword,
      searchMode: 'identifier',
      perPage: BUSINESS_PAGE_SIZE,
      subscriberPrefix: 'global-search-order-business',
      onDelta: handleDelta
    }),
    items = _useEsSalesGridData.items,
    total = _useEsSalesGridData.total,
    loading = _useEsSalesGridData.loading,
    error = _useEsSalesGridData.error,
    page = _useEsSalesGridData.page,
    hasMore = _useEsSalesGridData.hasMore,
    fetchPage = _useEsSalesGridData.fetchPage;

  // 新搜索（keyword 变化）时重置详情刷新版本，避免沿用旧订单的版本。
  useEffect(function () {
    setDetailRefreshVersions({});
  }, [keyword]);

  // 每轮加载结束（loading 翻 false）解除触底连发锁。
  useEffect(function () {
    if (!loading) loadingMoreRef.current = false;
  }, [loading]);

  // 虚拟滚动需要确定的视口高度（px）：用 ResizeObserver 实时测量容器可用高度。
  var containerRef = useRef(null);
  var _useState3 = useState(0),
    _useState4 = _slicedToArray(_useState3, 2),
    viewportHeight = _useState4[0],
    setViewportHeight = _useState4[1];
  useEffect(function () {
    var el = containerRef.current;
    if (!el) return undefined;
    var measure = function measure() {
      return setViewportHeight(el.clientHeight);
    };
    measure();
    var ro = new ResizeObserver(measure);
    ro.observe(el);
    return function () {
      return ro.disconnect();
    };
  }, []);
  var handleScroll = useCallback(function (e) {
    var _e$currentTarget = e.currentTarget,
      scrollTop = _e$currentTarget.scrollTop,
      clientHeight = _e$currentTarget.clientHeight,
      scrollHeight = _e$currentTarget.scrollHeight;
    if (!loading && !loadingMoreRef.current && hasMore && scrollHeight - scrollTop - clientHeight < BUSINESS_LOAD_MORE_THRESHOLD) {
      loadingMoreRef.current = true;
      fetchPage(page + 1, true);
    }
  }, [loading, hasMore, fetchPage, page]);
  var isFirstLoading = loading && items.length === 0;
  var isFirstError = !!error && items.length === 0;
  // 搜了但 0 条（空 keyword 的 idle 提示由外层壳层处理）。
  var isEmpty = !loading && !error && items.length === 0;

  // 注：容器**始终渲染**（带 ref），保证 ResizeObserver 第一时间绑定、量到确定高度；
  // 各状态（首屏 loading / 错误 / 空 / 列表）都放在容器内部，避免「容器延迟挂载导致测不到高度、
  // List 永远不渲染」的坑。
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    className: "pisell-global-search-order-business pisell-global-search-order-business--virtual"
  }, isFirstLoading && /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business__status"
  }, /*#__PURE__*/React.createElement(Spin, null)), !isFirstLoading && isFirstError && /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business__status pisell-global-search__empty"
  }, locales.getText('pisell-global-search.error')), !isFirstLoading && !isFirstError && isEmpty && /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business__status pisell-global-search__empty"
  }, locales.getText('pisell-global-search.empty')), items.length > 0 && viewportHeight === 0 && /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business__status"
  }, /*#__PURE__*/React.createElement(Spin, {
    size: "small"
  })), items.length > 0 && viewportHeight > 0 && /*#__PURE__*/React.createElement(List, {
    data: items
    // 追加加载时从列表高度让出底部提示条的空间，避免提示覆盖最后一条详情
    ,
    height: loading && items.length > 0 ? Math.max(viewportHeight - BUSINESS_LOADER_HEIGHT, 0) : viewportHeight,
    itemHeight: BUSINESS_ROW_ESTIMATED_HEIGHT
    // 开启虚拟化：只渲染可视区行，仍支持触底翻页。
    ,
    virtual: BUSINESS_LIST_VIRTUAL_SCROLL,
    itemKey: function itemKey(item) {
      var _ref4, _getSalesOrderId;
      // 行 key 仅按订单 id 稳定，避免实时刷新版本变化导致整行（SaleDetail）remount 闪烁。
      var id = (_ref4 = (_getSalesOrderId = getSalesOrderId(item)) !== null && _getSalesOrderId !== void 0 ? _getSalesOrderId : item.order_id) !== null && _ref4 !== void 0 ? _ref4 : '';
      return "".concat(id);
    },
    onScroll: handleScroll
  }, function (item) {
    var id = getSalesOrderId(item);
    var refreshVersion = getDetailRefreshVersion(detailRefreshVersions, 'order', id);
    // key / osKey 保持稳定（仅按订单 id），实时刷新通过 ref 命令式就地刷新，避免整块 remount 闪烁。
    var osKey = "global-search-business-detail-".concat(id);
    return /*#__PURE__*/React.createElement("div", {
      key: osKey,
      className: "pisell-global-search-order-business__item",
      style: {
        marginBottom: 6
      }
    }, /*#__PURE__*/React.createElement(OrderTableFallbackBoundary, null, /*#__PURE__*/React.createElement(RefreshableSaleDetail, {
      refreshVersion: refreshVersion,
      renderType: "current"
      // 与右栏详情统一：固定模板 A + 平板变体（覆盖 withResponsive 注入的 desktop）。
      ,
      tmpl: "B",
      variant: "tablet"
      // 业务模式详情够宽时也走两栏（金额明细 + 操作按钮抽到右列、按钮一行一个）。
      ,
      summaryTwoColumn: true,
      osProps: {
        osKey: osKey,
        orderId: Number(id),
        preloadedSalesDetail: item,
        autoBootstrap: true,
        destroyOnUnmount: true
      }
    })));
  }), loading && items.length > 0 && /*#__PURE__*/React.createElement("div", {
    style: {
      flex: '0 0 auto',
      height: BUSINESS_LOADER_HEIGHT,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center'
    }
  }, /*#__PURE__*/React.createElement(Spin, {
    size: "small"
  })));
};
export var OrderBusinessList = /*#__PURE__*/React.memo(OrderBusinessListImpl);

/** 管理模式表格初始查询条件：不带订单默认的「今天 + 默认支付状态」限制，
 * 否则会把全局搜索的命中结果按今天过滤掉。排序默认按创建时间倒序。
 * 用工厂返回新对象，避免模块级可变常量被原地 mutate 污染。 */
var getAdminGridDefaultSearchParams = function getAdminGridDefaultSearchParams() {
  return {
    filter: {
      values: {}
    },
    sort: 'created_at:desc'
  };
};

/**
 * 管理模式订单表格（**真实 ES 数据驱动，自带查询控制器**）。
 *
 * 直接用底层 `PisellSalesGrid` 受控渲染，数据源是 ES `/shop/es/search/sales`，并**自己掌管
 * 筛选 / 排序 / 翻页**：每次变化都按接口文档重新发单模块搜索，带上 `filters` / `sort` / `page` / `per_page`。
 *
 * 设计要点：
 * - **列不变**：复用 `useOrderPerspective` 的原列配置，列按各自逻辑「正常取值」；
 *   ES 没返回的字段（customer 对象 / payments / tags / 备注 / 商品数 / 渠道）由列自身回退为 '-' / 0；
 * - **toolbar**：隐藏 search（keyword 由全局搜索框统一驱动，避免里外重复），
 *   保留并启用 filter / sort / quickFilter —— 变化时映射成 ES `filters` / `sort` 重新查询；
 * - **筛选映射**：1:1 透传（`mapGridFiltersToEs`），仅日期范围 / 金额范围 / 排序做形状适配；
 * - **search_mode='fuzzy'**：管理模式走模糊匹配；
 * - **locale**：列头依赖 orderList / salesManagement 多语言，这里 `locales.init`（合并语义，
 *   不冲掉全局搜索文案）补齐；
 * - 行点击：注入 onOpenDetail 时交给外层就地内联展示详情。
 */
var OrderAdminGridImpl = function OrderAdminGridImpl(_ref5) {
  var _context$engine;
  var keyword = _ref5.keyword,
    onOpenDetail = _ref5.onOpenDetail,
    onRealtimePatchItems = _ref5.onRealtimePatchItems,
    previewLimit = _ref5.previewLimit,
    onReportTotal = _ref5.onReportTotal,
    _ref5$providerKey = _ref5.providerKey,
    providerKey = _ref5$providerKey === void 0 ? 'order' : _ref5$providerKey;
  var context = useEngineContext();
  var localeProp = 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;

  // 列头文案：补齐 orderList + salesManagement 多语言（init 为合并语义，幂等且不冲掉全局搜索文案）
  var mergedLocales = {
    en: _objectSpread(_objectSpread({}, orderListLocales.en), salesManagementLocales.en),
    'zh-CN': _objectSpread(_objectSpread({}, orderListLocales['zh-CN']), salesManagementLocales['zh-CN']),
    'zh-HK': _objectSpread(_objectSpread({}, orderListLocales['zh-HK']), salesManagementLocales['zh-HK'])
  };
  locales.init(mergedLocales, localeProp || 'en');

  // ---------- 表格筛选 / 排序状态 ----------
  var _useState5 = useState(getAdminGridDefaultSearchParams),
    _useState6 = _slicedToArray(_useState5, 2),
    searchParams = _useState6[0],
    setSearchParams = _useState6[1];
  var onSearch = useCallback(function (params) {
    setSearchParams(params || {});
  }, []);
  var onReset = useCallback(function () {
    setSearchParams(getAdminGridDefaultSearchParams());
  }, []);

  // ---------- 滚动翻页（累积加载） ----------
  // PisellSalesGrid 开启 infiniteScroll 后，触底会调用 onPageChange(pageNumber+1)；
  // 受控 data 模式下 RecordBoard 不会自动切片，需由本组件把下一页结果【追加】到 data。
  // 预览模式（previewLimit，「全部」分组）：只取这么多条、不翻页。
  var isPreview = typeof previewLimit === 'number' && previewLimit > 0;
  var PAGE_SIZE = isPreview ? previewLimit : 20;
  // 除页码外的查询要素；变化时清空累积、回到第 1 页。
  var filters = useMemo(function () {
    var _searchParams$filter;
    return mapGridFiltersToEs(searchParams === null || searchParams === void 0 || (_searchParams$filter = searchParams.filter) === null || _searchParams$filter === void 0 ? void 0 : _searchParams$filter.values);
  }, [searchParams]);
  var sort = useMemo(function () {
    return parseSortKey(searchParams === null || searchParams === void 0 ? void 0 : searchParams.sort);
  }, [searchParams]);

  // 当前被点击展示详情的行 id（右侧详情对应那条）：用于行高亮（选中态）。
  var _useState7 = useState(undefined),
    _useState8 = _slicedToArray(_useState7, 2),
    activeId = _useState8[0],
    setActiveId = _useState8[1];

  /** 实时 delta 命中已加载行后：通知外层刷新已打开的详情（列表浅合并已在 hook 内完成）。 */
  var handleDelta = useCallback(function (deltaItems) {
    onRealtimePatchItems === null || onRealtimePatchItems === void 0 || onRealtimePatchItems('order', deltaItems);
  }, [onRealtimePatchItems]);
  var _useEsSalesGridData2 = useEsSalesGridData({
      keyword: keyword,
      searchMode: 'fuzzy',
      perPage: PAGE_SIZE,
      filters: filters,
      sort: sort,
      subscriberPrefix: 'global-search-order-admin',
      onDelta: handleDelta
    }),
    items = _useEsSalesGridData2.items,
    total = _useEsSalesGridData2.total,
    loading = _useEsSalesGridData2.loading,
    error = _useEsSalesGridData2.error,
    page = _useEsSalesGridData2.page,
    fetchPage = _useEsSalesGridData2.fetchPage;

  // 受控 data 模式下传给 PisellSalesGrid 的分页对象（页码由 hook 维护）。
  var pagination = useMemo(function () {
    return {
      pageNumber: page,
      pageSize: PAGE_SIZE
    };
  }, [page, PAGE_SIZE]);

  // 上报总数给外层分组头（替代 provider.search 的「只取数量」计数请求）。
  // 用 ref 持有最新回调，effect 仅随 total 变化触发，避免回调身份变更引发多余上报。
  var reportTotalRef = useRef(onReportTotal);
  reportTotalRef.current = onReportTotal;
  useEffect(function () {
    var _reportTotalRef$curre;
    (_reportTotalRef$curre = reportTotalRef.current) === null || _reportTotalRef$curre === void 0 || _reportTotalRef$curre.call(reportTotalRef, providerKey, total);
  }, [total, providerKey]);

  // 搜索词变化：把表格的筛选 / 排序全部重置为默认空（清掉用户之前设的日期等筛选）。
  // 仅在当前非默认时才重置：避免「纯打字、从未动过筛选」也创建新对象触发多余重查。
  // 重置后 filters/sort 变 → hook 内部以 fetchPage 引用变化为信号自然带新词 + 空筛选重查。
  var prevKeywordRef = useRef(keyword);
  useEffect(function () {
    if (prevKeywordRef.current === keyword) return;
    prevKeywordRef.current = keyword;
    setSearchParams(function (prev) {
      var _prev$filter;
      var next = getAdminGridDefaultSearchParams();
      var isDefault = !!prev && prev.sort === next.sort && !!((_prev$filter = prev.filter) !== null && _prev$filter !== void 0 && _prev$filter.values) && Object.keys(prev.filter.values).length === 0;
      return isDefault ? prev : next;
    });
  }, [keyword]);

  // 重新查询（改 keyword / 筛选 / 排序）：清掉旧的选中高亮，避免高亮到已不在列表的行。
  useEffect(function () {
    setActiveId(undefined);
  }, [keyword, filters, sort]);

  // 滚动触底加载下一页（PisellSalesGrid 传 pageNumber+1）：仅向后翻、追加。
  var onPageChange = useCallback(function (pageNumber) {
    // 预览模式（「全部」分组，仅 5 条）：不翻页、不加载下一页（保险，防触底加载）。
    if (isPreview) return;
    if (pageNumber > page) {
      fetchPage(pageNumber, true);
    }
  }, [isPreview, fetchPage, page]);

  // ES 命中项（扁平 Sales 协议）→ 表格 record：补 id / order_id 供 rowKey 与行点击使用
  var records = useMemo(function () {
    return items.map(function (item) {
      var orderId = getSalesOrderId(item);
      if (orderId === undefined) return null;
      return _objectSpread(_objectSpread({}, item), {}, {
        id: orderId,
        order_id: orderId
      });
    }).filter(function (r) {
      return r !== null;
    });
  }, [items]);
  var recordById = useMemo(function () {
    var map = new Map();
    records.forEach(function (record) {
      if ((record === null || record === void 0 ? void 0 : record.id) !== undefined && (record === null || record === void 0 ? void 0 : record.id) !== null) {
        map.set(String(record === null || record === void 0 ? void 0 : record.id), record);
      }
    });
    return map;
  }, [records]);

  // 行点击回调：memo 化，避免每次渲染都生成新引用 → useOrderPerspective 重算 → 表格列重建
  var handleRowOpenDetail = useCallback(function (_ref6) {
    var orderId = _ref6.orderId;
    // 记录被点击行用于高亮，并通知外层在右侧/抽屉展示详情。
    setActiveId(orderId);
    onOpenDetail === null || onOpenDetail === void 0 || onOpenDetail({
      providerKey: 'order',
      id: orderId,
      record: recordById.get(String(orderId))
    });
  }, [onOpenDetail, recordById]);
  var perspectiveBase = useOrderPerspective({
    onOpenDetail: onOpenDetail ? handleRowOpenDetail : undefined
  });

  // 列宽 / 筛选等重配置：仅随 perspectiveBase 变化重建，避免点行高亮时整表重算。
  var perspectiveCore = useMemo(function () {
    var originalGet = perspectiveBase.getChildComponentProps;
    var COLUMN_WIDTH_SCALE = 0.8;
    var COLUMN_MIN_WIDTH = 88;
    var COLUMN_SCALE_OVERRIDES = {
      sale_brief: 0.7,
      // 金额两行（Paid/Total/Due）较宽，缩到 0.8 会把数字挤断，单独放宽一点
      payment_info: 1,
      // 支付方式（CASHMANUAL: $x + 时间）较长，放宽避免折断
      payment_method: 1.3,
      // 订单来源（渠道 + 创建人 + 时间）较长，放宽避免折断
      order_origin: 1.2,
      // Updated（编辑人 + 渠道 + 时间）较长，放宽避免折断
      last_edit_account: 1.2
    };
    // 这些列内容是「多行堆叠的文本」（payment 方式/金额、付款汇总等），且 render 里
    // 用了 align-items: flex-start 的嵌套 flex 列。我们把 render 输出整体包一层自己可控的
    // class，CSS 只认这层 class、用 :has() 自动区分布局容器与文本叶子行，使「超出列宽单行省略」
    // 不再依赖 antd 单元格内部结构 / 是否虚拟表 / 固定嵌套深度。
    var ELLIPSIS_COLUMN_KEYS = new Set(['payment_method', 'payment_info',
    // order_origin / last_edit_account 同为多行堆叠文本，且本表恒为虚拟表，
    // 旧的 cell-content 选择器在虚拟单元格里不稳，统一走自有 wrapper 才可靠省略。
    'order_origin', 'last_edit_account']);
    var wrapEllipsisRender = function wrapEllipsisRender(col) {
      var originalRender = col.render;
      if (typeof originalRender !== 'function') return col;
      return _objectSpread(_objectSpread({}, col), {}, {
        render: function render(value, record, index) {
          return /*#__PURE__*/React.createElement("div", {
            className: "pisell-global-search-ellipsis-cell"
          }, originalRender(value, record, index));
        }
      });
    };
    var shrinkColumns = function shrinkColumns(columns) {
      return Array.isArray(columns) ? columns.map(function (col) {
        var _COLUMN_SCALE_OVERRID;
        if (!col) return col;
        var scaled = typeof col.width === 'number' ? _objectSpread(_objectSpread({}, col), {}, {
          width: Math.max(Math.round(col.width * ((_COLUMN_SCALE_OVERRID = COLUMN_SCALE_OVERRIDES[col.key]) !== null && _COLUMN_SCALE_OVERRID !== void 0 ? _COLUMN_SCALE_OVERRID : COLUMN_WIDTH_SCALE)), COLUMN_MIN_WIDTH)
        }) : col;
        // Payment Status 列：标签放不下时在标签内换行（而非省略），打上专属 class 供样式定位
        if (col.key === 'payment_status') {
          return _objectSpread(_objectSpread({}, scaled), {}, {
            className: [scaled.className, 'pisell-global-search-col-payment-status'].filter(Boolean).join(' ')
          });
        }
        // 文本堆叠列：包一层省略容器
        if (ELLIPSIS_COLUMN_KEYS.has(col.key)) {
          return wrapEllipsisRender(scaled);
        }
        return scaled;
      }) : columns;
    };
    return _objectSpread(_objectSpread({}, perspectiveBase), {}, {
      getChildComponentProps: function getChildComponentProps(ctx) {
        var result = (originalGet ? originalGet(ctx) : perspectiveBase.childComponentProps) || {};
        var grid = result.grid || {};
        var toolBar = result.toolBar || {};
        var filter = toolBar.filter && _typeof(toolBar.filter) === 'object' ? toolBar.filter : {};
        return _objectSpread(_objectSpread({}, result), {}, {
          grid: _objectSpread(_objectSpread({}, grid), {}, {
            columns: shrinkColumns(grid.columns),
            // 始终开启无限滚动：RecordBoard 据此隐藏底部翻页器
            // （showGridPagination = showGrid && gridInfiniteScroll !== true）。
            // 预览模式不翻页是靠 onPageChange 里拦截，而非关掉 infiniteScroll，
            // 否则翻页器会重新出现。
            infiniteScroll: true,
            virtual: true
          }),
          toolBar: _objectSpread(_objectSpread({}, toolBar), {}, {
            search: false,
            filter: _objectSpread(_objectSpread({}, filter), {}, {
              defaultFilterValue: _objectSpread(_objectSpread({}, filter.defaultFilterValue || {}), {}, {
                quickFilter: [],
                values: {}
              })
            })
          })
        });
      }
    });
  }, [perspectiveBase]);

  // 行高亮：单独薄包装 getChildComponentProps，仅 activeId 变化时更新 perspectives 引用。
  var perspectives = useMemo(function () {
    var coreGet = perspectiveCore.getChildComponentProps;
    return [_objectSpread(_objectSpread({}, perspectiveCore), {}, {
      getChildComponentProps: function getChildComponentProps(ctx) {
        var result = coreGet ? coreGet(ctx) : {};
        var grid = result.grid || {};
        var baseRowClassName = grid.rowClassName;
        return _objectSpread(_objectSpread({}, result), {}, {
          grid: _objectSpread(_objectSpread({}, grid), {}, {
            rowClassName: function rowClassName(record, index, indent) {
              var prev = typeof baseRowClassName === 'function' ? baseRowClassName(record, index, indent) : baseRowClassName || '';
              var isActive = activeId !== undefined && (record === null || record === void 0 ? void 0 : record.id) != null && String(record.id) === String(activeId);
              return [prev, isActive ? 'pisell-global-search-order-row--active' : ''].filter(Boolean).join(' ');
            }
          })
        });
      }
    })];
  }, [perspectiveCore, activeId]);

  // 与 PisellSalesManagement 一致的 locale 适配
  var adapterLocale = localeProp === 'zh-CN' || localeProp === 'zh-HK' ? 'zh-cn' : localeProp === 'en' || localeProp === 'en-US' ? 'en' : 'zh-cn';
  var rawLocale = localeProp || (typeof localStorage !== 'undefined' ? localStorage.getItem('umi_locale') : null) || 'en-US';
  var materialsLocale = rawLocale === 'zh' ? 'zh-CN' : rawLocale;
  return /*#__PURE__*/React.createElement(OrderTableFallbackBoundary, null, /*#__PURE__*/React.createElement(PisellConfigProvider, {
    locale: materialsLocale
  }, /*#__PURE__*/React.createElement(LocalizationProvider, {
    dateAdapter: AdapterDayjs,
    adapterLocale: adapterLocale
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-table"
  }, error && items.length === 0 && !loading ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-global-search-order-business__status pisell-global-search__empty"
  }, locales.getText('pisell-global-search.error')) : /*#__PURE__*/React.createElement(PisellSalesGrid, {
    perspectives: perspectives,
    currentPerspective: "handle",
    data: records,
    loading: loading,
    total: total,
    pagination: pagination,
    onPageChange: onPageChange,
    searchParams: searchParams,
    onSearch: onSearch,
    onReset: onReset,
    rowKey: "id"
  })))));
};

/**
 * 管理模式订单表格（对外）。用 React.memo 包裹：
 * 壳层输入框受控 → 每次敲键壳层重渲染并内联调用 renderResults，
 * memo 在 committed keyword / onOpenDetail 未变时跳过整块重渲染。
 */
export var OrderAdminGrid = /*#__PURE__*/React.memo(OrderAdminGridImpl);
OrderAdminGrid.displayName = 'OrderAdminGrid';