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/pisellProResourcePickerModal/PisellProResourcePickerModal.tsx
var PisellProResourcePickerModal_exports = {};
__export(PisellProResourcePickerModal_exports, {
  PisellProResourcePickerModal: () => PisellProResourcePickerModal,
  default: () => PisellProResourcePickerModal_default
});
module.exports = __toCommonJS(PisellProResourcePickerModal_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_pisellFindPro = __toESM(require("../../pro/pisellFindPro"));
var import_compensatedPisellContainer = __toESM(require("../../pro/compensatedPisellContainer"));
var import_Selector = __toESM(require("../../pro/Selector"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_utils2 = require("./utils");
var import_PisellProResourcePickerModal = require("./PisellProResourcePickerModal.less");
var PREFIX = "pisell-pro-resource-picker";
var I18N_RP = "pisell-floor-map-layout.resource-picker";
function defaultGetCardMeta(record) {
  const titleRaw = record.title ?? record.name ?? record.label ?? record.id ?? "";
  const subtitleRaw = record.subtitle ?? record.desc ?? record.description;
  const subtitle = subtitleRaw == null ? "" : String(subtitleRaw).trim();
  return {
    title: String(titleRaw).trim(),
    subtitles: subtitle ? [subtitle] : []
  };
}
function formatSelectedCount(count, total) {
  return import_utils.locales.getText(`${I18N_RP}.selected-count`).replace("{count}", String(count)).replace("{total}", String(total));
}
var TABBAR_NON_CATEGORY_IDS = /* @__PURE__ */ new Set(["-1", "-2", "0"]);
function tabbarValueToSelection(value) {
  const out = [null, null, null];
  if (!value) return out;
  for (let i = 0; i < 3; i++) {
    const seg = value[i];
    if (seg == null || seg === "") continue;
    out[i] = String(seg);
  }
  return out;
}
function normalizeIds(value) {
  if (!value) return [];
  return value.map((v) => String(v ?? "").trim()).filter(Boolean);
}
function PisellProResourcePickerModal(props) {
  var _a;
  const {
    open,
    onClose,
    onConfirm,
    records,
    mode = "multiple",
    value,
    title,
    disabledIds,
    categoryConfig,
    getSearchText,
    getCardMeta,
    renderCard,
    renderFilterBar,
    selectorValueType = "primitive",
    selectorShowStepper = "auto",
    getOptionRuleConfig,
    zIndex = 1100,
    width = 880,
    className,
    platform = "pc"
  } = props;
  const isObjectMode = selectorValueType === "object";
  const resolveCardMeta = getCardMeta ?? defaultGetCardMeta;
  const resolveSearchText = getSearchText ?? import_utils2.defaultGetSearchText;
  const disabledSet = (0, import_react.useMemo)(
    () => new Set((disabledIds ?? []).map((id) => String(id))),
    [disabledIds]
  );
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [tabbarValue, setTabbarValue] = (0, import_react.useState)(["0"]);
  const [draftSelected, setDraftSelected] = (0, import_react.useState)([]);
  const [draftObjectValues, setDraftObjectValues] = (0, import_react.useState)(
    []
  );
  const prevOpenRef = (0, import_react.useRef)(false);
  const { engine } = (0, import_useEngineContext.default)();
  const engineLocale = ((_a = engine == null ? void 0 : engine.props) == null ? void 0 : _a.locale) ?? "zh-CN";
  (0, import_react.useEffect)(() => {
    if (open) {
      import_utils.locales.init(import_materials.floorMapLayoutLocales, engineLocale);
    }
  }, [open, engineLocale]);
  (0, import_react.useEffect)(() => {
    if (!open) {
      setKeyword("");
      setTabbarValue(["0"]);
      prevOpenRef.current = false;
      return;
    }
    if (!prevOpenRef.current) {
      if (isObjectMode) {
        setDraftObjectValues([]);
      } else {
        setDraftSelected(normalizeIds(value));
      }
      prevOpenRef.current = true;
    }
  }, [open, value, isObjectMode]);
  const tabbarDataSource = (0, import_react.useMemo)(
    () => (0, import_utils2.buildTabbarDataSourceFromRecords)(records, categoryConfig),
    [records, categoryConfig]
  );
  const selection = (0, import_react.useMemo)(() => {
    const sel = tabbarValueToSelection(tabbarValue);
    return sel.map(
      (s) => s != null && TABBAR_NON_CATEGORY_IDS.has(s) ? null : s
    );
  }, [tabbarValue]);
  const filterBarCtx = (0, import_react.useMemo)(
    () => ({
      keyword,
      onKeywordChange: setKeyword,
      tabbarDataSource,
      tabbarValue,
      onTabbarValueChange: setTabbarValue
    }),
    [keyword, tabbarDataSource, tabbarValue]
  );
  const filteredRecords = (0, import_react.useMemo)(() => {
    const q = keyword.trim().toLowerCase();
    return records.filter((record) => {
      if (!(0, import_utils2.matchesSelection)(record, selection, categoryConfig)) return false;
      if (!q) return true;
      return resolveSearchText(record).includes(q);
    });
  }, [records, selection, categoryConfig, keyword, resolveSearchText]);
  const selectorOptions = (0, import_react.useMemo)(() => {
    return filteredRecords.map((record) => {
      const id = String(record.id ?? "").trim();
      const meta = resolveCardMeta(record);
      return {
        id,
        title: meta.title,
        label: meta.title,
        value: id,
        disabled: disabledSet.has(id),
        ...getOptionRuleConfig ? { ruleConfig: getOptionRuleConfig(record) } : {},
        __record: record,
        __meta: meta
      };
    });
  }, [filteredRecords, disabledSet, resolveCardMeta, getOptionRuleConfig]);
  const selectableFilteredIds = (0, import_react.useMemo)(
    () => selectorOptions.map((o) => String(o.id ?? "")).filter((id) => id && !disabledSet.has(id)),
    [selectorOptions, disabledSet]
  );
  const selectedKindCount = (0, import_react.useMemo)(() => {
    if (isObjectMode) {
      return draftObjectValues.filter((item) => item.quantity > 0).length;
    }
    return draftSelected.length;
  }, [isObjectMode, draftObjectValues, draftSelected]);
  const allFilteredSelected = (0, import_react.useMemo)(() => {
    if (selectableFilteredIds.length === 0) return false;
    if (isObjectMode) {
      return selectableFilteredIds.every(
        (id) => draftObjectValues.some((x) => x.value === id && x.quantity > 0)
      );
    }
    return selectableFilteredIds.every((id) => draftSelected.includes(id));
  }, [isObjectMode, selectableFilteredIds, draftObjectValues, draftSelected]);
  const someFilteredSelected = (0, import_react.useMemo)(() => {
    if (isObjectMode) {
      return draftObjectValues.some(
        (x) => selectableFilteredIds.includes(x.value) && x.quantity > 0
      );
    }
    return draftSelected.some((id) => selectableFilteredIds.includes(id));
  }, [isObjectMode, draftObjectValues, draftSelected, selectableFilteredIds]);
  const handleSelectAllFiltered = (0, import_react.useCallback)(() => {
    if (isObjectMode) {
      setDraftObjectValues((prev) => {
        const map = new Map(prev.map((x) => [x.value, x]));
        for (const id of selectableFilteredIds) {
          const existing = map.get(id);
          map.set(id, {
            value: id,
            quantity: (existing == null ? void 0 : existing.quantity) && existing.quantity > 0 ? existing.quantity : 1
          });
        }
        return [...map.values()].filter((x) => x.quantity > 0);
      });
      return;
    }
    setDraftSelected((prev) => {
      const set = new Set(prev);
      for (const id of selectableFilteredIds) set.add(id);
      return [...set];
    });
  }, [isObjectMode, selectableFilteredIds]);
  const handleDeselectAllFiltered = (0, import_react.useCallback)(() => {
    if (mode === "single") {
      if (isObjectMode) setDraftObjectValues([]);
      else setDraftSelected([]);
      return;
    }
    if (isObjectMode) {
      setDraftObjectValues(
        (prev) => prev.filter((x) => !selectableFilteredIds.includes(x.value))
      );
      return;
    }
    setDraftSelected(
      (prev) => prev.filter((id) => !selectableFilteredIds.includes(id))
    );
  }, [mode, isObjectMode, selectableFilteredIds]);
  const parseObjectSelection = (0, import_react.useCallback)(
    (next) => {
      if (next == null || next === "") return [];
      if (!Array.isArray(next)) {
        if (typeof next === "object" && next !== null && "value" in next) {
          const valueKey = String(next.value ?? "").trim();
          if (!valueKey) return [];
          return [
            {
              value: valueKey,
              quantity: Math.max(0, Math.floor(Number(next.quantity ?? 0)))
            }
          ];
        }
        const primitive = String(next).trim();
        return primitive ? [{ value: primitive, quantity: 1 }] : [];
      }
      return next.map((v) => {
        if (typeof v === "object" && v !== null && "value" in v) {
          return {
            value: String(v.value ?? "").trim(),
            quantity: Math.max(0, Math.floor(Number(v.quantity ?? 0)))
          };
        }
        const valueKey = String(v ?? "").trim();
        return valueKey ? { value: valueKey, quantity: 1 } : null;
      }).filter((x) => Boolean(x == null ? void 0 : x.value));
    },
    []
  );
  const handleSelectorChange = (0, import_react.useCallback)(
    (next) => {
      if (isObjectMode) {
        setDraftObjectValues(
          parseObjectSelection(next).filter((x) => x.quantity > 0)
        );
        return;
      }
      if (mode === "single") {
        if (next == null || next === "") {
          setDraftSelected([]);
        } else if (typeof next === "object" && next !== null && "value" in next) {
          setDraftSelected([String(next.value)]);
        } else {
          setDraftSelected([String(next)]);
        }
        return;
      }
      if (!Array.isArray(next)) return;
      const visible = new Set(selectableFilteredIds);
      const newVisibleSelection = next.map(
        (v) => typeof v === "object" && v !== null && "value" in v ? String(v.value) : String(v)
      ).filter((id) => visible.has(id));
      setDraftSelected((prev) => {
        const keptOutsideView = prev.filter((id) => !visible.has(id));
        const merged = /* @__PURE__ */ new Set([...keptOutsideView, ...newVisibleSelection]);
        return [...merged];
      });
    },
    [isObjectMode, mode, selectableFilteredIds, parseObjectSelection]
  );
  const selectorValue = (0, import_react.useMemo)(() => {
    if (isObjectMode) {
      return draftObjectValues;
    }
    if (mode === "single") {
      return draftSelected[0] ?? "";
    }
    const visible = new Set(selectableFilteredIds);
    return draftSelected.filter((id) => visible.has(id));
  }, [isObjectMode, mode, draftObjectValues, draftSelected, selectableFilteredIds]);
  const handleConfirm = (0, import_react.useCallback)(() => {
    if (isObjectMode) {
      const confirmObject = onConfirm;
      confirmObject(draftObjectValues.filter((x) => x.quantity > 0));
    } else {
      const confirmIds = onConfirm;
      confirmIds(draftSelected.filter(Boolean));
    }
    onClose();
  }, [isObjectMode, draftObjectValues, draftSelected, onConfirm, onClose]);
  const renderSelectorItem = (0, import_react.useCallback)(
    (renderProps) => {
      var _a2;
      const { dataSource, indicator, numberSelector, actions } = renderProps;
      const option = dataSource;
      const record = option.__record;
      const meta = option.__meta;
      const id = String(option.id ?? "");
      const selected = isObjectMode ? Boolean(option.selected) : draftSelected.includes(id);
      const disabled = disabledSet.has(id);
      const customCard = record && renderCard ? renderCard(record, { selected, disabled }) : null;
      const onCardClick = () => {
        if (disabled) return;
        const key = option._key ?? id;
        actions.update(key, { quantity: selected ? 0 : 1 });
      };
      const image = meta == null ? void 0 : meta.image;
      const imageNode = image == null ? null : typeof image === "string" ? /* @__PURE__ */ import_react.default.createElement(
        "img",
        {
          className: `${PREFIX}-card-image-img`,
          src: image,
          alt: (meta == null ? void 0 : meta.title) ?? "",
          draggable: false
        }
      ) : image;
      return /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          type: "button",
          disabled,
          onClick: onCardClick,
          className: (0, import_classnames.default)(`${PREFIX}-card`, {
            [`${PREFIX}-card--selected`]: selected,
            [`${PREFIX}-card--disabled`]: disabled,
            [`${PREFIX}-card--with-stepper`]: Boolean(numberSelector)
          })
        },
        /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-body` }, customCard ? customCard : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, imageNode ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-image` }, imageNode) : null, /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-text` }, /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-title` }, (meta == null ? void 0 : meta.title) ?? option.title), (_a2 = meta == null ? void 0 : meta.subtitles) == null ? void 0 : _a2.map((sub, index) => /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            key: `${id}-sub-${index}`,
            className: `${PREFIX}-card-sub`
          },
          sub
        )), (meta == null ? void 0 : meta.badges) && meta.badges.length > 0 ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-badges` }, meta.badges.map((badge, index) => /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            key: `${id}-badge-${index}`,
            className: `${PREFIX}-card-badge`
          },
          badge.icon ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-card-badge-icon` }, badge.icon) : null,
          badge.text
        ))) : null))),
        /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            className: `${PREFIX}-card-actions`,
            onClick: (e) => e.stopPropagation()
          },
          numberSelector ?? indicator
        )
      );
    },
    [isObjectMode, draftSelected, disabledSet, renderCard]
  );
  const confirmLabel = (0, import_react.useMemo)(() => {
    const base = import_utils.locales.getText(`${I18N_RP}.confirm`);
    return selectedKindCount > 0 ? `${base} (${selectedKindCount})` : base;
  }, [selectedKindCount]);
  return /* @__PURE__ */ import_react.default.createElement(
    import_compensatedPisellContainer.default,
    {
      renderType: "modal",
      props: {
        platform,
        open,
        title,
        onCancel: onClose,
        destroyOnClose: true,
        width,
        zIndex,
        wrapClassName: (0, import_classnames.default)(`${PREFIX}-modal`, className),
        headerDivider: false,
        footerDivider: false,
        style: {
          maxHeight: "95%"
        },
        footer: /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-footer` }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: onClose }, import_utils.locales.getText(`${I18N_RP}.cancel`)), /* @__PURE__ */ import_react.default.createElement(
          import_antd.Button,
          {
            type: "primary",
            onClick: handleConfirm,
            disabled: selectedKindCount === 0
          },
          confirmLabel
        ))
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: PREFIX }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-filter-bar` }, renderFilterBar ? renderFilterBar(filterBarCtx) : /* @__PURE__ */ import_react.default.createElement(
      import_pisellFindPro.default,
      {
        triggerType: "input",
        value: keyword,
        onChange: setKeyword,
        onSearch: setKeyword,
        placeholder: import_utils.locales.getText(`${I18N_RP}.search-ph`),
        showHistory: false,
        showConfirmButton: false
      }
    )), /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar` }, mode === "multiple" ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-left` }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Checkbox,
      {
        indeterminate: someFilteredSelected && !allFilteredSelected,
        checked: allFilteredSelected,
        disabled: selectableFilteredIds.length === 0,
        onChange: (e) => {
          if (e.target.checked) handleSelectAllFiltered();
          else handleDeselectAllFiltered();
        }
      },
      import_utils.locales.getText(`${I18N_RP}.select-all`)
    ), /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: `${PREFIX}-link`,
        onClick: handleDeselectAllFiltered,
        disabled: selectedKindCount === 0
      },
      import_utils.locales.getText(`${I18N_RP}.deselect-all`)
    )) : /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-hint` }, import_utils.locales.getText(`${I18N_RP}.single-hint`)), /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-count` }, formatSelectedCount(selectedKindCount, records.length))), /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-list` }, selectorOptions.length === 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-empty` }, import_utils.locales.getText(`${I18N_RP}.empty`)) : /* @__PURE__ */ import_react.default.createElement(
      import_Selector.default,
      {
        dataSource: selectorOptions,
        mode,
        valueType: selectorValueType,
        variant: "card",
        itemLayout: "horizontal",
        showStepper: selectorShowStepper,
        value: selectorValue,
        onChange: handleSelectorChange,
        renderItem: renderSelectorItem,
        layout: {
          type: "antdGrid",
          responsive: {
            minWidth: 160,
            maxColumns: 4,
            gap: 4,
            defaultColumns: 2
          }
        },
        headerProps: { visible: false }
      }
    )))
  );
}
var PisellProResourcePickerModal_default = PisellProResourcePickerModal;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellProResourcePickerModal
});
