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/components/pisellFloorMapLayout/components/FloorMapToolbar.tsx
var FloorMapToolbar_exports = {};
__export(FloorMapToolbar_exports, {
  FloorMapToolbar: () => FloorMapToolbar,
  default: () => FloorMapToolbar_default
});
module.exports = __toCommonJS(FloorMapToolbar_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_types = require("../types");
var import_floorMapElementKindUtils = require("../utils/floorMapElementKindUtils");
var import_floorMapDropUtils = require("../utils/floorMapDropUtils");
var import_floorMapDataRecordLabel = require("../utils/floorMapDataRecordLabel");
var import_utils = require("@pisell/utils");
var import_FloorMapToolbar = require("./FloorMapToolbar.less");
var PREFIX = "pisell-floor-map-layout";
var I18N_TB = "pisell-floor-map-layout.toolbar";
var I18N_EP_DS = "pisell-floor-map-layout.edit-panel.ph-data-source";
var DEFAULT_PLACEMENT_SIZE = { width: 180, height: 120 };
var DEFAULT_DECORATION_SIZE = 48;
function getUnplacedRecordsForKey(dataSourceKey, dataSources, elements) {
  const used = new Set(
    elements.filter((e) => {
      var _a;
      return ((_a = e.dataBinding) == null ? void 0 : _a.dataSourceKey) === dataSourceKey;
    }).map((e) => e.dataBinding.recordId)
  );
  const list = dataSources[dataSourceKey] ?? [];
  return list.filter(
    (r) => r && typeof r.id === "string" && !used.has(r.id)
  );
}
function buildScenePreviewMergedItem(kind, dataSourceKey, size) {
  const el = {
    instanceId: `preview_${kind.value}`,
    canvasId: "",
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    elementKind: kind.value,
    shape: kind.defaultShape,
    dataBinding: dataSourceKey && (0, import_floorMapElementKindUtils.resolveDataBindingPolicy)(kind) !== "none" ? { dataSourceKey, recordId: "" } : void 0,
    ...kind.value === import_types.FLOOR_MAP_IMAGE_ELEMENT_KIND ? { imageUrl: "" } : {}
  };
  return {
    id: el.instanceId,
    instanceId: el.instanceId,
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    shape: kind.defaultShape,
    elementKind: kind.value,
    _sceneElement: el
  };
}
var STAGE_PREVIEW_SIZE = { width: 160, height: 64 };
var IMAGE_PREVIEW_SIZE = { width: 140, height: 80 };
function FloorMapToolbar(props) {
  const {
    config,
    dataSources,
    dataSourceLabels = {},
    canCreate,
    placeMode,
    onPlaceModeChange,
    renderPreviewItem,
    placementPreviewSize = DEFAULT_PLACEMENT_SIZE,
    decorationPreviewSize = DEFAULT_DECORATION_SIZE,
    sceneElements = [],
    onSave,
    saving,
    saveError,
    layoutDirty,
    className,
    onPaletteCardPointerDown,
    consumeToolbarClickIfTouchDrag
  } = props;
  const paletteKinds = (0, import_react.useMemo)(
    () => (config.elementKinds ?? []).filter((k) => k.showInPalette !== false),
    [config.elementKinds]
  );
  const categories = (0, import_react.useMemo)(() => {
    const raw = config.elementKindCategories ?? [];
    const sorted = [...raw].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
    return sorted.length ? sorted : [
      {
        id: "_uncat",
        label: import_utils.locales.getText(`${I18N_TB}.category-fallback`),
        order: 0
      }
    ];
  }, [config.elementKindCategories]);
  const kindsByCategory = (0, import_react.useMemo)(() => {
    var _a;
    const map = /* @__PURE__ */ new Map();
    for (const c of categories) {
      map.set(c.id, []);
    }
    const fallbackId = ((_a = categories[0]) == null ? void 0 : _a.id) ?? "_uncat";
    for (const k of paletteKinds) {
      const cid = k.categoryId ?? fallbackId;
      if (!map.has(cid)) map.set(cid, []);
      map.get(cid).push(k);
    }
    return map;
  }, [categories, paletteKinds]);
  const handleSelectKind = (kind) => {
    const policy = (0, import_floorMapElementKindUtils.resolveDataBindingPolicy)(kind);
    const next = {
      type: "scene",
      elementKind: kind.value,
      /** 不预锁单一数据源，由用户在工具栏「数据源」中选择；落点时用 allowedKeys[0] 作兜底 */
      dataSourceKey: void 0,
      recordId: void 0
    };
    const isSame = (placeMode == null ? void 0 : placeMode.type) === "scene" && placeMode.elementKind === kind.value;
    onPlaceModeChange(isSame ? null : next);
  };
  const handleDsChange = (mode, key) => {
    onPlaceModeChange({
      ...mode,
      dataSourceKey: key,
      recordId: void 0,
      recordIds: void 0
    });
  };
  const handleRecordsChange = (mode, ids) => {
    const list = (ids == null ? void 0 : ids.filter(Boolean)) ?? [];
    onPlaceModeChange({
      ...mode,
      recordIds: list.length > 0 ? list : void 0,
      recordId: void 0
    });
  };
  const cancelPlaceMode = () => onPlaceModeChange(null);
  const renderKindCard = (k) => {
    var _a;
    const policy = (0, import_floorMapElementKindUtils.resolveDataBindingPolicy)(k);
    const isStage = k.value === import_types.FLOOR_MAP_STAGE_ELEMENT_KIND;
    const isImageKind = k.value === import_types.FLOOR_MAP_IMAGE_ELEMENT_KIND;
    const placementLike = policy !== "none" && !isStage || isImageKind;
    const size = isStage ? STAGE_PREVIEW_SIZE : placementLike ? isImageKind ? IMAGE_PREVIEW_SIZE : placementPreviewSize : {
      width: decorationPreviewSize,
      height: decorationPreviewSize
    };
    const activeDs = (placeMode == null ? void 0 : placeMode.type) === "scene" && placeMode.elementKind === k.value ? placeMode.dataSourceKey : void 0;
    const item = buildScenePreviewMergedItem(k, activeDs, size);
    const isActive = (placeMode == null ? void 0 : placeMode.type) === "scene" && placeMode.elementKind === k.value;
    const cellW = isStage ? 92 : placementLike ? 80 : decorationPreviewSize;
    const cellH = isStage ? 40 : placementLike ? 54 : decorationPreviewSize;
    const previewW = isImageKind ? IMAGE_PREVIEW_SIZE.width : placementPreviewSize.width;
    const previewH = isImageKind ? IMAGE_PREVIEW_SIZE.height : placementPreviewSize.height;
    const placeScale = placementLike ? Math.min(cellW / previewW, cellH / previewH) : 1;
    const stageScale = isStage ? Math.min(cellW / item.width, cellH / item.height, 1) : 1;
    const allKeys = Object.keys(dataSources);
    const allowedKeys = ((_a = k.allowedDataSourceKeys) == null ? void 0 : _a.length) ? k.allowedDataSourceKeys.filter((x) => allKeys.includes(x)) : allKeys;
    const paletteDragPayload = {
      elementKind: k.value,
      ...(placeMode == null ? void 0 : placeMode.type) === "scene" && placeMode.elementKind === k.value ? {
        dataSourceKey: placeMode.dataSourceKey,
        ...placeMode.recordIds && placeMode.recordIds.length > 0 ? { recordIds: placeMode.recordIds } : placeMode.recordId ? { recordId: placeMode.recordId } : {}
      } : {}
    };
    return /* @__PURE__ */ import_react.default.createElement("div", { key: k.value, className: `${PREFIX}-toolbar-preview-card-wrap` }, /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        draggable: true,
        className: (0, import_classnames.default)(
          `${PREFIX}-toolbar-preview-card`,
          !placementLike ? `${PREFIX}-toolbar-preview-card-deco` : void 0,
          { [`${PREFIX}-toolbar-preview-card-active`]: isActive }
        ),
        onClick: () => {
          if (consumeToolbarClickIfTouchDrag == null ? void 0 : consumeToolbarClickIfTouchDrag()) return;
          handleSelectKind(k);
        },
        onPointerDown: (e) => onPaletteCardPointerDown == null ? void 0 : onPaletteCardPointerDown(paletteDragPayload, e),
        onDragStart: (e) => {
          e.dataTransfer.setData(
            import_floorMapDropUtils.FLOOR_MAP_PALETTE_DRAG_MIME,
            JSON.stringify(paletteDragPayload)
          );
          e.dataTransfer.effectAllowed = "copy";
        },
        title: import_utils.locales.getText(`${I18N_TB}.palette-card-title`).replace(/\{name\}/g, k.label)
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: `${PREFIX}-toolbar-preview-cell`,
          style: { width: cellW, height: cellH }
        },
        renderPreviewItem ? /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `${PREFIX}-toolbar-preview-content`,
            style: placementLike ? {
              width: previewW,
              height: previewH,
              transform: `scale(${placeScale})`,
              transformOrigin: "top left"
            } : isStage ? {
              width: item.width,
              height: item.height,
              transform: `scale(${stageScale})`,
              transformOrigin: "top left"
            } : void 0
          },
          renderPreviewItem(item)
        ) : /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-toolbar-preview-fallback` }, k.label)
      ),
      /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-toolbar-preview-card-label` }, k.label)
    ), isActive && policy !== "none" && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, allowedKeys.length >= 1 && /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-pick` }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-pick-label` }, import_utils.locales.getText(`${I18N_TB}.data-binding-optional`)), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Select,
      {
        placeholder: import_utils.locales.getText(I18N_EP_DS),
        allowClear: true,
        value: placeMode.type === "scene" ? placeMode.dataSourceKey : void 0,
        options: allowedKeys.map((key) => ({
          value: key,
          label: dataSourceLabels[key] ?? key
        })),
        onChange: (v) => {
          if ((placeMode == null ? void 0 : placeMode.type) === "scene")
            handleDsChange(placeMode, v);
        },
        size: "large",
        style: { width: "100%" }
      }
    ), (() => {
      const mode = (placeMode == null ? void 0 : placeMode.type) === "scene" ? placeMode : null;
      const key = mode == null ? void 0 : mode.dataSourceKey;
      if (!key) {
        return /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-pick-hint` }, import_utils.locales.getText(`${I18N_TB}.hint-after-select-ds`));
      }
      const unplaced = getUnplacedRecordsForKey(
        key,
        dataSources,
        sceneElements
      );
      if (unplaced.length === 0) {
        return /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-pick-hint` }, import_utils.locales.getText(`${I18N_TB}.hint-no-unplaced-rows`));
      }
      const recordValue = (mode == null ? void 0 : mode.recordIds) && mode.recordIds.length > 0 ? mode.recordIds : (mode == null ? void 0 : mode.recordId) ? [mode.recordId] : void 0;
      return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Select,
        {
          mode: "multiple",
          placeholder: import_utils.locales.getText(
            `${I18N_TB}.ph-select-records`
          ),
          allowClear: true,
          maxTagCount: "responsive",
          value: recordValue,
          options: unplaced.map((r) => ({
            value: r.id,
            label: (0, import_floorMapDataRecordLabel.formatDataRecordOptionLabel)(r)
          })),
          onChange: (v) => {
            if (mode) handleRecordsChange(mode, v);
          },
          size: "large",
          style: { width: "100%", marginTop: 4 }
        }
      ), /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-pick-hint` }, import_utils.locales.getText(`${I18N_TB}.hint-multi-drop`)));
    })()), allowedKeys.length === 0 && /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-record-hint` }, import_utils.locales.getText(`${I18N_TB}.no-data-sources`)), /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: `${PREFIX}-toolbar-btn cancel-inline`,
        onClick: cancelPlaceMode
      },
      import_utils.locales.getText(`${I18N_TB}.cancel-place`)
    )), isActive && policy === "none" && /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: `${PREFIX}-toolbar-btn cancel-inline`,
        onClick: cancelPlaceMode
      },
      import_utils.locales.getText(`${I18N_TB}.cancel-place`)
    ));
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)(
        `${PREFIX}-toolbar`,
        `${PREFIX}-toolbar-sidebar`,
        className
      )
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-body` }, canCreate && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, categories.map((cat) => {
      const kinds = kindsByCategory.get(cat.id) ?? [];
      if (!kinds.length) return null;
      return /* @__PURE__ */ import_react.default.createElement("section", { key: cat.id, className: `${PREFIX}-toolbar-section` }, /* @__PURE__ */ import_react.default.createElement("h3", { className: `${PREFIX}-toolbar-section-title` }, cat.label), /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-preview-list` }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-preview-group` }, kinds.map((k) => renderKindCard(k)))));
    }))),
    onSave && config.canvasUi.canEdit && /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}-toolbar-footer` }, layoutDirty ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-toolbar-dirty-hint`, role: "status" }, import_utils.locales.getText(`${I18N_TB}.layout-dirty-hint`)) : null, saveError && /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}-toolbar-error` }, typeof saveError === "string" ? saveError : saveError == null ? void 0 : saveError.message), /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        type: "button",
        className: (0, import_classnames.default)(`${PREFIX}-toolbar-btn`, "primary", {
          [`${PREFIX}-toolbar-save-dirty`]: layoutDirty
        }),
        disabled: saving,
        onClick: onSave
      },
      saving ? import_utils.locales.getText(`${I18N_TB}.saving`) : import_utils.locales.getText(`${I18N_TB}.save`)
    ))
  );
}
var FloorMapToolbar_default = FloorMapToolbar;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FloorMapToolbar
});
