var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/pisellGlobalSearch/PisellGlobalSearchFullPage.tsx
var PisellGlobalSearchFullPage_exports = {};
__export(PisellGlobalSearchFullPage_exports, {
  PisellGlobalSearchFullPage: () => PisellGlobalSearchFullPage,
  default: () => PisellGlobalSearchFullPage_default
});
module.exports = __toCommonJS(PisellGlobalSearchFullPage_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_utils2 = require("../../utils");
var import_responsive = require("../../responsive");
var import_RefreshableSaleDetail = __toESM(require("./components/RefreshableSaleDetail"));
var import_GlobalSearchFind = __toESM(require("./components/GlobalSearchFind"));
var import_types = require("./types");
var import_hooks = require("./hooks");
var import_GroupedResults = __toESM(require("./components/GroupedResults"));
var import_SingleProviderResults = __toESM(require("./components/SingleProviderResults"));
var import_ScopeBar = __toESM(require("./components/ScopeBar"));
var import_ScopeBar2 = require("./components/ScopeBar.less");
var import_getLocaleLabel = require("./utils/getLocaleLabel");
var import_i18nText = require("./utils/i18nText");
var import_locales = __toESM(require("./locales"));
var import_providers = require("./providers");
var import_detailRefresh = require("./utils/detailRefresh");
var import_PisellGlobalSearchFullPage = require("./PisellGlobalSearchFullPage.less");
var PisellGlobalSearchFullPageInner = ({
  placeholder,
  // searchButtonText,
  providers,
  permissionContext,
  navigate,
  showModeSwitch = true,
  defaultMode = "business",
  mode: modeProp,
  onModeChange,
  modeOptions,
  // showAllTab 已 deprecated：组件强制始终展示 All；这里不再解构，避免误用
  allModePageSize = 5,
  singleModePageSize = 20,
  enableScanner = true,
  historyKey = "pisell_global_search_history",
  maxHistoryCount = 10,
  variant,
  className,
  style
}) => {
  var _a, _b, _c, _d, _e, _f;
  const ctx = (0, import_useEngineContext.default)();
  const locale = (0, import_i18nText.normalizeGlobalSearchLocale)((_b = (_a = import_utils.locales).getLocale) == null ? void 0 : _b.call(_a));
  import_utils.locales.init(import_locales.default, locale);
  if ((_d = (_c = ctx == null ? void 0 : ctx.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.request) {
    import_utils2.request.setRequest(ctx.appHelper.utils.request);
    (0, import_utils2.setOsQueryWebPos)(ctx.appHelper.utils.isWebPos);
  }
  const effectiveProviders = (0, import_react.useMemo)(() => {
    if (Array.isArray(providers) && providers.length > 0) return providers;
    return import_providers.allProviders;
  }, [providers]);
  const enabledProviders = (0, import_react.useMemo)(() => {
    const list = effectiveProviders.filter(
      (p) => p && p.enabledWhen ? p.enabledWhen(permissionContext ?? {}) : Boolean(p)
    );
    return [...list].sort(
      (a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER)
    );
  }, [effectiveProviders, permissionContext]);
  const [inputValue, setInputValue] = (0, import_react.useState)("");
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const useDrawerDetail = variant === "phone" || variant === "smallTablet" || variant === "tablet";
  const [selectedDetail, setSelectedDetail] = (0, import_react.useState)(
    null
  );
  const detailRefreshFingerprintsRef = (0, import_react.useRef)({});
  const [detailRefreshVersions, setDetailRefreshVersions] = (0, import_react.useState)({});
  const handleOpenDetail = (0, import_react.useCallback)(({ providerKey, id, record }) => {
    if (id === void 0 || id === null || id === "") return;
    setSelectedDetail({ providerKey, id, record });
  }, []);
  const effectiveOpenDetail = useDrawerDetail ? void 0 : handleOpenDetail;
  (0, import_react.useEffect)(() => {
    setSelectedDetail(null);
    detailRefreshFingerprintsRef.current = {};
    setDetailRefreshVersions({});
  }, [keyword]);
  const handleRealtimePatchItems = (0, import_react.useCallback)(
    (providerKey, items) => {
      if (providerKey !== "order") return;
      setSelectedDetail((prevDetail) => {
        if (!prevDetail || prevDetail.providerKey !== "order") return prevDetail;
        const match = Array.isArray(items) ? items.find(
          (it) => String((it == null ? void 0 : it.order_id) ?? (it == null ? void 0 : it.id) ?? (it == null ? void 0 : it.key)) === String(prevDetail.id)
        ) : void 0;
        if (!match) return prevDetail;
        const prevRecord = prevDetail.record && typeof prevDetail.record === "object" ? prevDetail.record : {};
        return { ...prevDetail, record: { ...prevRecord, ...match } };
      });
      setDetailRefreshVersions((prev) => {
        const fingerprints = (0, import_detailRefresh.buildOrderDetailRefreshFingerprints)(items);
        const nextFingerprints = { ...detailRefreshFingerprintsRef.current };
        const changedFingerprintIds = Object.entries(fingerprints).filter(([id, fingerprint]) => nextFingerprints[id] !== fingerprint).map(([id, fingerprint]) => {
          nextFingerprints[id] = fingerprint;
          return id;
        });
        detailRefreshFingerprintsRef.current = nextFingerprints;
        const effectiveItems = Array.isArray(items) ? items.filter(
          (item) => changedFingerprintIds.includes(
            String((item == null ? void 0 : item.order_id) ?? (item == null ? void 0 : item.id) ?? (item == null ? void 0 : item.key))
          )
        ) : [];
        const next = (0, import_detailRefresh.bumpOrderDetailRefreshVersions)(prev, effectiveItems);
        return next;
      });
    },
    []
  );
  const {
    rightWidth,
    containerRef: bodyRef,
    onResizerMouseDown,
    resizing
  } = (0, import_hooks.useResizablePane)({ initialRatio: 0.36 });
  const [innerMode, setInnerMode] = (0, import_react.useState)(defaultMode);
  const mode = modeProp ?? innerMode;
  const handleModeChange = (0, import_react.useCallback)(
    (next) => {
      if (modeProp === void 0) setInnerMode(next);
      onModeChange == null ? void 0 : onModeChange(next);
    },
    [modeProp, onModeChange]
  );
  const effectiveShowAllTab = enabledProviders.length >= 1;
  const [innerActiveTab, setInnerActiveTab] = (0, import_react.useState)(
    // 初始 Tab 固定为 All（只要展示 All）；不再受外部 defaultActiveTab 控制，
    // 避免 lowcode schema 里固化的旧值（如 order）覆盖默认。
    effectiveShowAllTab ? import_types.ALL_TAB_KEY : ((_e = enabledProviders[0]) == null ? void 0 : _e.key) ?? import_types.ALL_TAB_KEY
  );
  const resolvedInnerActiveTab = !effectiveShowAllTab && innerActiveTab === import_types.ALL_TAB_KEY ? ((_f = enabledProviders[0]) == null ? void 0 : _f.key) ?? import_types.ALL_TAB_KEY : innerActiveTab;
  const activeTab = resolvedInnerActiveTab;
  const { stateMap, reportProviderTotal } = (0, import_hooks.useProviderSearch)({
    keyword,
    activeTab,
    providers: enabledProviders,
    allModePageSize,
    singleModePageSize,
    mode,
    onRealtimePatchItems: handleRealtimePatchItems
  });
  const handleSubmit = (0, import_react.useCallback)(
    (raw) => {
      setKeyword((raw ?? inputValue).trim());
    },
    [inputValue]
  );
  const modeSegmentOptions = (0, import_react.useMemo)(() => {
    const adminLabel = (modeOptions == null ? void 0 : modeOptions.admin) ? (0, import_getLocaleLabel.getLocaleLabel)(modeOptions.admin, locale) : (0, import_i18nText.getGlobalSearchText)("pisell-global-search.mode.admin");
    const businessLabel = (modeOptions == null ? void 0 : modeOptions.business) ? (0, import_getLocaleLabel.getLocaleLabel)(modeOptions.business, locale) : (0, import_i18nText.getGlobalSearchText)("pisell-global-search.mode.business");
    return [
      { label: businessLabel, value: "business" },
      { label: adminLabel, value: "admin" }
    ];
  }, [modeOptions, locale]);
  const scopeOptions = (0, import_react.useMemo)(() => {
    const items = enabledProviders.map((p) => ({
      value: p.key,
      label: /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-global-search-scope-bar__option" }, p.icon, (0, import_getLocaleLabel.getLocaleLabel)(p.label, locale))
    }));
    if (effectiveShowAllTab) {
      items.unshift({
        value: import_types.ALL_TAB_KEY,
        label: /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-global-search-scope-bar__option" }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.tab.all"))
      });
    }
    return items;
  }, [enabledProviders, effectiveShowAllTab, locale]);
  const isAll = activeTab === import_types.ALL_TAB_KEY;
  const close = (0, import_react.useCallback)(() => {
  }, []);
  const isCustomSingleResults = (0, import_react.useMemo)(() => {
    if (!keyword || isAll) return false;
    const provider = enabledProviders.find((p) => p.key === activeTab);
    return !!(provider == null ? void 0 : provider.renderResults);
  }, [keyword, isAll, enabledProviders, activeTab]);
  const renderResultsBody = () => {
    if (!keyword) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search-fp__empty" }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.empty.idle"));
    }
    if (isAll) {
      return /* @__PURE__ */ import_react.default.createElement(
        import_GroupedResults.default,
        {
          providers: enabledProviders,
          stateMap,
          keyword,
          mode,
          locale,
          onJumpTab: (tab) => setInnerActiveTab(tab),
          onClose: close,
          navigate,
          onOpenDetail: effectiveOpenDetail,
          onRealtimePatchItems: handleRealtimePatchItems,
          detailRefreshVersions,
          onReportTotal: reportProviderTotal
        }
      );
    }
    const provider = enabledProviders.find((p) => p.key === activeTab);
    if (!provider) return null;
    const state = stateMap[provider.key] ?? {
      loading: false,
      list: [],
      total: 0
    };
    return /* @__PURE__ */ import_react.default.createElement(
      import_SingleProviderResults.default,
      {
        provider,
        state,
        keyword,
        mode,
        onClose: close,
        navigate,
        onOpenDetail: effectiveOpenDetail,
        onRealtimePatchItems: handleRealtimePatchItems,
        detailRefreshVersions,
        onReportTotal: reportProviderTotal
      }
    );
  };
  const renderDetailContent = () => {
    if (!selectedDetail) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search-fp__detail-idle" }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.detail.idle"));
    }
    if (selectedDetail.providerKey === "order") {
      const refreshVersion = (0, import_detailRefresh.getDetailRefreshVersion)(
        detailRefreshVersions,
        "order",
        selectedDetail.id
      );
      const osKey = `global-search-order-detail-${selectedDetail.id}`;
      return /* @__PURE__ */ import_react.default.createElement(
        import_RefreshableSaleDetail.default,
        {
          key: osKey,
          refreshVersion,
          renderType: "current",
          tmpl: "B",
          variant: "tablet",
          summaryTwoColumn: true,
          osProps: {
            osKey,
            orderId: Number(selectedDetail.id),
            preloadedSalesDetail: selectedDetail.record && typeof selectedDetail.record === "object" ? selectedDetail.record : void 0,
            autoBootstrap: true,
            destroyOnUnmount: true
          }
        }
      );
    }
    return null;
  };
  const showDetailAside = !useDrawerDetail && !!keyword && mode === "admin";
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: `pisell-global-search-fp pisell-global-search-fp--${variant || "desktop"} ${className ?? ""}`.trim(),
      style
    },
    /* @__PURE__ */ import_react.default.createElement("section", { className: "pisell-global-search-fp__search-panel" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search-fp__search-row" }, /* @__PURE__ */ import_react.default.createElement(
      import_GlobalSearchFind.default,
      {
        className: "pisell-global-search-fp__find",
        displayType: "inline",
        enableScanner,
        size: variant === "phone" ? "small" : void 0,
        showHistory: true,
        historyKey,
        maxHistoryCount,
        placeholder: placeholder ?? (0, import_i18nText.getGlobalSearchText)("pisell-global-search.placeholder"),
        confirmButtonText: (0, import_i18nText.getGlobalSearchText)("pisell-global-search.search"),
        value: inputValue,
        onChange: setInputValue,
        onSearch: (v) => handleSubmit(v)
      }
    ), showModeSwitch && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search-fp__mode-switch" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Segmented,
      {
        options: modeSegmentOptions,
        value: mode,
        onChange: (v) => handleModeChange(v)
      }
    ))), /* @__PURE__ */ import_react.default.createElement(
      import_ScopeBar.default,
      {
        options: scopeOptions,
        value: activeTab,
        onChange: (v) => setInnerActiveTab(v)
      }
    )),
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: `pisell-global-search-fp__body${resizing ? " pisell-global-search-fp__body--resizing" : ""}`,
        ref: bodyRef
      },
      /* @__PURE__ */ import_react.default.createElement(
        "main",
        {
          className: `pisell-global-search-fp__main${isCustomSingleResults ? " pisell-global-search-fp__main--bare" : ""}`
        },
        renderResultsBody()
      ),
      showDetailAside && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "pisell-global-search-fp__resizer",
          onMouseDown: onResizerMouseDown,
          role: "separator",
          "aria-orientation": "vertical"
        }
      ), /* @__PURE__ */ import_react.default.createElement(
        "aside",
        {
          className: "pisell-global-search-fp__detail",
          style: { flex: `0 0 ${rightWidth}`, width: rightWidth }
        },
        renderDetailContent()
      ))
    )
  );
};
PisellGlobalSearchFullPageInner.displayName = "PisellGlobalSearchFullPage";
var PisellGlobalSearchFullPage = (0, import_responsive.withResponsive)(
  PisellGlobalSearchFullPageInner
);
var PisellGlobalSearchFullPage_default = PisellGlobalSearchFullPage;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellGlobalSearchFullPage
});
