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/PisellGlobalSearch.tsx
var PisellGlobalSearch_exports = {};
__export(PisellGlobalSearch_exports, {
  PisellGlobalSearch: () => PisellGlobalSearch,
  default: () => PisellGlobalSearch_default
});
module.exports = __toCommonJS(PisellGlobalSearch_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_saleDetail = __toESM(require("../saleDetail"));
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_PisellGlobalSearch = require("./PisellGlobalSearch.less");
var PisellGlobalSearchInner = (0, import_react.forwardRef)((props, ref) => {
  var _a, _b, _c, _d, _e, _f;
  const {
    providers,
    permissionContext,
    activeTab: activeTabProp,
    onActiveTabChange,
    allModePageSize = 5,
    singleModePageSize = 20,
    // showAllTab 已 deprecated：组件强制始终展示 All；此处不再解构
    allTabLabel,
    navigate,
    defaultMode = "business",
    mode: modeProp,
    onModeChange,
    showModeSwitch = true,
    modeOptions,
    // 默认提交式：回车 / 点搜索按钮才搜（与 FullPage 一致）；
    // 传 'instant' 可退回输入即搜。
    submitMode = "submit",
    lookupProps,
    variant,
    className,
    style
  } = props;
  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);
  }
  const enabledProviders = (0, import_react.useMemo)(() => {
    const safeProviders = Array.isArray(providers) ? providers : [];
    const list = safeProviders.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)
    );
  }, [providers, permissionContext]);
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [inputValue, setInputValue] = (0, import_react.useState)("");
  const useDrawerDetail = variant === "phone" || variant === "smallTablet" || variant === "tablet";
  const [selectedDetail, setSelectedDetail] = (0, import_react.useState)(
    null
  );
  const handleOpenDetail = (0, import_react.useCallback)(({ providerKey, id }) => {
    if (id === void 0 || id === null || id === "") return;
    setSelectedDetail({ providerKey, id });
  }, []);
  const effectiveOpenDetail = useDrawerDetail ? void 0 : handleOpenDetail;
  (0, import_react.useEffect)(() => {
    setSelectedDetail(null);
  }, [keyword]);
  const {
    rightWidth,
    containerRef: contentRef,
    onResizerMouseDown,
    resizing
  } = (0, import_hooks.useResizablePane)({ initialRatio: 0.38 });
  const effectiveShowAllTab = enabledProviders.length >= 1;
  const [innerActiveTab, setInnerActiveTab] = (0, import_react.useState)(
    // 初始 Tab 固定为 All（只要展示 All）；不再受外部 defaultActiveTab 控制，
    // 避免 lowcode schema 里固化的旧值（如 order）覆盖默认。受控 activeTab 仍优先生效。
    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 = activeTabProp ?? resolvedInnerActiveTab;
  const handleActiveTabChange = (0, import_react.useCallback)(
    (next) => {
      if (activeTabProp === void 0) setInnerActiveTab(next);
      onActiveTabChange == null ? void 0 : onActiveTabChange(next);
    },
    [activeTabProp, onActiveTabChange]
  );
  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 { stateMap, refresh } = (0, import_hooks.useProviderSearch)({
    keyword,
    activeTab,
    providers: enabledProviders,
    allModePageSize,
    singleModePageSize,
    mode
  });
  const lookupRef = (0, import_react.useRef)(null);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      open: () => {
        var _a2;
        return (_a2 = lookupRef.current) == null ? void 0 : _a2.open();
      },
      close: () => {
        var _a2;
        return (_a2 = lookupRef.current) == null ? void 0 : _a2.close();
      },
      setKeyword: (k) => {
        var _a2;
        (_a2 = lookupRef.current) == null ? void 0 : _a2.setKeyword(k);
        setInputValue(k);
        setKeyword(k);
      },
      getKeyword: () => keyword,
      setActiveTab: handleActiveTabChange,
      setMode: handleModeChange,
      getMode: () => mode,
      refresh
    }),
    [keyword, handleActiveTabChange, handleModeChange, mode, refresh]
  );
  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" }, allTabLabel ? (0, import_getLocaleLabel.getLocaleLabel)(allTabLabel, locale) : (0, import_i18nText.getGlobalSearchText)("pisell-global-search.tab.all"))
      });
    }
    return items;
  }, [enabledProviders, effectiveShowAllTab, allTabLabel, locale]);
  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 modeSwitchNode = showModeSwitch ? /* @__PURE__ */ import_react.default.createElement(
    import_antd.Segmented,
    {
      className: "pisell-global-search__mode-segmented",
      options: modeSegmentOptions,
      value: mode,
      onChange: (v) => handleModeChange(v)
    }
  ) : null;
  const renderResults = (0, import_react.useCallback)(
    (currentKeyword, onClose) => {
      const close = onClose ?? (() => {
        var _a2;
        return (_a2 = lookupRef.current) == null ? void 0 : _a2.close();
      });
      const isAll = activeTab === import_types.ALL_TAB_KEY;
      const detailContent = !selectedDetail ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search__detail-idle" }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.detail.idle")) : selectedDetail.providerKey === "order" ? /* @__PURE__ */ import_react.default.createElement(
        import_saleDetail.default,
        {
          renderType: "current",
          tmpl: "A",
          variant: "tablet",
          osProps: {
            osKey: "global-search-order-detail",
            orderId: Number(selectedDetail.id),
            autoBootstrap: true,
            destroyOnUnmount: true
          }
        }
      ) : null;
      const showDetailAside = !useDrawerDetail && !!currentKeyword && mode === "admin";
      if (enabledProviders.length === 0) {
        return /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `pisell-global-search ${className ?? ""}`.trim(),
            style
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search__empty" }, /* @__PURE__ */ import_react.default.createElement("div", { style: { marginBottom: 8, fontWeight: 600 } }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.providers-missing.title")), /* @__PURE__ */ import_react.default.createElement("div", { style: { fontSize: 12, lineHeight: 1.6 } }, (0, import_i18nText.getGlobalSearchText)("pisell-global-search.providers-missing.description"), /* @__PURE__ */ import_react.default.createElement("br", null), /* @__PURE__ */ import_react.default.createElement("code", { style: { background: "#f3f4f6", padding: "0 4px" } }, `<PisellGlobalSearch providers={allProviders} />`)))
        );
      }
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: `pisell-global-search pisell-global-search--${variant || "desktop"} ${className ?? ""}`.trim(),
          style
        },
        (scopeOptions.length >= 1 || modeSwitchNode) && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search__scope-wrap" }, /* @__PURE__ */ import_react.default.createElement(
          import_ScopeBar.default,
          {
            options: scopeOptions,
            value: activeTab,
            onChange: (v) => handleActiveTabChange(v),
            extra: modeSwitchNode
          }
        )),
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `pisell-global-search__content${resizing ? " pisell-global-search__content--resizing" : ""}`,
            ref: contentRef
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-global-search__body" }, isAll ? /* @__PURE__ */ import_react.default.createElement(
            import_GroupedResults.default,
            {
              providers: enabledProviders,
              stateMap,
              keyword: currentKeyword,
              mode,
              locale,
              onJumpTab: handleActiveTabChange,
              onClose: close,
              navigate,
              onOpenDetail: effectiveOpenDetail
            }
          ) : (() => {
            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: currentKeyword,
                mode,
                onClose: close,
                navigate,
                onOpenDetail: effectiveOpenDetail
              }
            );
          })()),
          showDetailAside && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: "pisell-global-search__resizer",
              onMouseDown: onResizerMouseDown,
              role: "separator",
              "aria-orientation": "vertical"
            }
          ), /* @__PURE__ */ import_react.default.createElement(
            "aside",
            {
              className: "pisell-global-search__detail",
              style: { flex: `0 0 ${rightWidth}`, width: rightWidth }
            },
            detailContent
          ))
        )
      );
    },
    [
      activeTab,
      className,
      style,
      scopeOptions,
      enabledProviders,
      stateMap,
      locale,
      handleActiveTabChange,
      navigate,
      modeSwitchNode,
      mode,
      variant,
      useDrawerDetail,
      selectedDetail,
      effectiveOpenDetail,
      rightWidth,
      contentRef,
      onResizerMouseDown,
      resizing
    ]
  );
  const finalLookupProps = (0, import_react.useMemo)(() => {
    return {
      triggerType: "input",
      displayType: "modal",
      placeholder: (0, import_i18nText.getGlobalSearchText)("pisell-global-search.placeholder"),
      confirmButtonText: (0, import_i18nText.getGlobalSearchText)("pisell-global-search.search"),
      modalWidth: 1080,
      showHistory: true,
      historyKey: "pisell_global_search_history",
      ...lookupProps
    };
  }, [lookupProps]);
  const searchMode = submitMode === "instant" ? "realtime" : "confirm";
  const handleLookupChange = (0, import_react.useCallback)(
    (next) => {
      setInputValue(next);
      if (submitMode === "instant") setKeyword(next);
    },
    [submitMode]
  );
  const handleLookupSearch = (0, import_react.useCallback)((next) => {
    setInputValue(next);
    setKeyword(next);
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(
    import_GlobalSearchFind.default,
    {
      ref: lookupRef,
      size: variant === "phone" ? "small" : void 0,
      ...finalLookupProps,
      searchMode,
      value: inputValue,
      onChange: handleLookupChange,
      onSearch: handleLookupSearch,
      resultRender: renderResults
    }
  );
});
PisellGlobalSearchInner.displayName = "PisellGlobalSearch";
var PisellGlobalSearch = (0, import_responsive.withResponsive)(PisellGlobalSearchInner);
var PisellGlobalSearch_default = PisellGlobalSearch;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellGlobalSearch
});
