var _excluded = ["getMergedItemWrapperStyle"];
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 _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 _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); }
/**
 * 合并 RecordBoard.floorMap 与预约默认：持久化 onSave、画布 Tab 尾区、缩放/平移等
 */
import React, { useMemo } from 'react';
import { wrapFloorMapOnSaveWithRemotePersist, getFloorMapCardPickerCategoryConfig, getFloorMapResourcePickerCardMeta, floorMapResourcePickerRecordSearchText, PisellTabbarTemplate1 } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { PisellProResourcePickerModal } from "../../pisellProResourcePickerModal";
import { PisellFloorMapPaletteViewAllModal } from "../../pisellProResourcePickerModal";
import { saveViewConfigToShopFloorPlan, toastFloorPlanSaveError } from "./floorPlanApi";
import { getReservationDataSourceFormColumns } from "./reservationMock";
import { ReservationFloorMapCanvasTabsTrailing, ReservationFloorMapDockToolButtons } from "../components/PisellReservationSubcomponents";
var I18N_FLOOR_MAP_DATA_SOURCE_LABEL = 'pisell-reservation.floor-map.data-source-label';

/**
 * 临时关闭预约 merge 后的视口 localStorage（记录/恢复拖动位置），每次进入仍走首屏全览。
 * 改回 `false` 即恢复原有行为：`viewportPersist` 尊重业务、`namespace` 使用 `reservationViewportNamespace`。
 */
var TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST = true;
export function useReservationFloorMapMerged(params) {
  var floorMapProp = params.floorMapProp,
    baseFloorConfig = params.baseFloorConfig,
    dataSources = params.dataSources,
    renderItemByKind = params.renderItemByKind,
    gridDataSourceKey = params.gridDataSourceKey,
    effectiveMapMode = params.effectiveMapMode,
    resolvedFloorPlanId = params.resolvedFloorPlanId,
    floorPlanRemoteId = params.floorPlanRemoteId,
    effectiveFloorPlanCode = params.effectiveFloorPlanCode,
    floorPlanCanvasWidth = params.floorPlanCanvasWidth,
    floorPlanCanvasHeight = params.floorPlanCanvasHeight,
    floorPlanName = params.floorPlanName,
    floorPlanSort = params.floorPlanSort,
    floorPlanStatus = params.floorPlanStatus,
    onFloorPlanPersisted = params.onFloorPlanPersisted,
    putFloorPlan = params.putFloorPlan,
    isFloorModeControlled = params.isFloorModeControlled,
    mapEditInternal = params.mapEditInternal,
    setMapEditInternal = params.setMapEditInternal,
    floorMapLayoutRef = params.floorMapLayoutRef,
    reservationFloorMapViewportOverlay = params.reservationFloorMapViewportOverlay,
    setRemoteFloorPlanView = params.setRemoteFloorPlanView,
    floorMapItemClickBefore = params.floorMapItemClickBefore,
    engineLocale = params.engineLocale,
    _params$floorMapHudTa = params.floorMapHudTableDrawer,
    floorMapHudTableDrawer = _params$floorMapHudTa === void 0 ? false : _params$floorMapHudTa,
    readModeSelectedItemIdParam = params.readModeSelectedItemId,
    editTopBarPhoneLayoutParam = params.editTopBarPhoneLayout,
    appearanceMode = params.appearanceMode,
    onToggleAppearanceMode = params.onToggleAppearanceMode;
  return useMemo(function () {
    var _floorMapProp$dataSou, _floorRest$cellSize, _floorRest$itemUnit, _floorRest$floorMapCo, _floorMapProp$renderI, _floorRest$toolbarSho, _floorRest$showDataSo, _floorRest$zoom, _floorRest$onExitEdit, _floorRest$floorMapVi, _floorRest$viewportPe, _floorRest$viewportDo, _floorRest$viewportDo2, _floorRest$editTopBar, _floorRest$renderReso, _floorRest$renderPale;
    void engineLocale;
    var labels = _defineProperty({}, gridDataSourceKey, locales.getText(I18N_FLOOR_MAP_DATA_SOURCE_LABEL));
    var forms = _defineProperty({}, gridDataSourceKey, getReservationDataSourceFormColumns());
    var _ref = floorMapProp !== null && floorMapProp !== void 0 ? floorMapProp : {},
      getMergedItemWrapperStyle = _ref.getMergedItemWrapperStyle,
      floorRest = _objectWithoutProperties(_ref, _excluded);
    var prevOnSave = floorRest.onSave;
    var persistTargetId = floorPlanRemoteId !== null && floorPlanRemoteId !== void 0 ? floorPlanRemoteId : resolvedFloorPlanId;
    var persistApi = persistTargetId != null && Number.isFinite(persistTargetId) && Math.floor(persistTargetId) === persistTargetId && persistTargetId > 0;
    var onSaveWithApi = wrapFloorMapOnSaveWithRemotePersist({
      canPersist: persistApi,
      persistTargetId: persistTargetId !== null && persistTargetId !== void 0 ? persistTargetId : 0,
      persist: function persist(id, config) {
        return saveViewConfigToShopFloorPlan(id, config, {
          canvasWidth: floorPlanCanvasWidth,
          canvasHeight: floorPlanCanvasHeight,
          code: effectiveFloorPlanCode,
          name: floorPlanName,
          sort: floorPlanSort,
          status: floorPlanStatus,
          putFloorPlan: putFloorPlan != null ? function (planId, body) {
            return putFloorPlan(planId, body);
          } : undefined
        });
      },
      setRemoteFloorPlanView: setRemoteFloorPlanView,
      onFloorPlanPersisted: onFloorPlanPersisted,
      prevOnSave: prevOnSave,
      onPersistError: toastFloorPlanSaveError
    });
    var mergedDataSources = (_floorMapProp$dataSou = floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.dataSources) !== null && _floorMapProp$dataSou !== void 0 ? _floorMapProp$dataSou : dataSources;

    /**
     * 视口持久化命名空间：同一 canvasId（`RESERVATION_MAIN_CANVAS_ID = 'main'`）在预约不同 floor plan 间共用，
     * 必须按业务维度隔离，否则换店铺 / 换 floor plan 会读到别家的缩放/位置。
     *
     * 【关键】必须使用「整生命周期稳定同步」的标识，不能用异步回填的 floorPlanRemoteId：
     * 若拖拽时 namespace 是 `reservation:${remoteId}`，下次打开首帧 remoteId 还是 null，
     * namespace 先是 `reservation:${resolvedFloorPlanId}`（可能是默认常量），读不到缓存 → autoFit 先跑。
     * 等远端返回 namespace 再切到真实 id 才能读到缓存，用户会看到「每次都先适配视口再跳回去」。
     *
     * 优先级：code（最稳定，总有兜底常量） > resolvedFloorPlanId（同步从 prop 解析） > 默认兜底。
     * 有效 code 场景下不使用 id：避免同 code 因 id 漂移造成 key 不一致。
     *
     * 当前由 `TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST` 关闭 persist 时不写入 props，保留计算供恢复开关后使用。
     */
    var reservationViewportNamespace = effectiveFloorPlanCode ? "reservation-code:".concat(effectiveFloorPlanCode) : resolvedFloorPlanId != null ? "reservation:".concat(resolvedFloorPlanId) : 'reservation:default';
    void floorPlanRemoteId;
    var reservationDefaultMapLayerBackgroundColor = appearanceMode === 'light' ? '#e8e8e8' : undefined;
    return _objectSpread(_objectSpread({
      mapLayer: _objectSpread(_objectSpread({
        showGrid: true,
        snapStep: 1
      }, reservationDefaultMapLayerBackgroundColor == null ? {} : {
        backgroundColor: reservationDefaultMapLayerBackgroundColor
      }), floorRest.mapLayer),
      cellSize: (_floorRest$cellSize = floorRest.cellSize) !== null && _floorRest$cellSize !== void 0 ? _floorRest$cellSize : 10,
      itemUnit: (_floorRest$itemUnit = floorRest.itemUnit) !== null && _floorRest$itemUnit !== void 0 ? _floorRest$itemUnit : 'pixel',
      dataSourceLabels: labels,
      dataSourceFormColumns: forms
    }, floorRest), {}, {
      floorMapConfig: (_floorRest$floorMapCo = floorRest.floorMapConfig) !== null && _floorRest$floorMapCo !== void 0 ? _floorRest$floorMapCo : baseFloorConfig,
      dataSources: mergedDataSources,
      renderItemByKind: (_floorMapProp$renderI = floorMapProp === null || floorMapProp === void 0 ? void 0 : floorMapProp.renderItemByKind) !== null && _floorMapProp$renderI !== void 0 ? _floorMapProp$renderI : renderItemByKind,
      appearanceMode: appearanceMode,
      mode: effectiveMapMode,
      toolbarShowSave: (_floorRest$toolbarSho = floorRest.toolbarShowSave) !== null && _floorRest$toolbarSho !== void 0 ? _floorRest$toolbarSho : false,
      showDataSourceRecordFormBlock: (_floorRest$showDataSo = floorRest.showDataSourceRecordFormBlock) !== null && _floorRest$showDataSo !== void 0 ? _floorRest$showDataSo : false,
      zoom: _objectSpread(_objectSpread({
        defaultScale: 1,
        min: 0.4,
        max: 2.2,
        step: 0.1
      }, floorRest.zoom), {}, {
        autoFitOnMount: TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST ? true : ((_floorRest$zoom = floorRest.zoom) === null || _floorRest$zoom === void 0 ? void 0 : _floorRest$zoom.autoFitOnMount) !== false
      }),
      controls: _objectSpread({
        showZoom: true,
        showReset: true,
        showFitBounds: true,
        showGridToggle: true
      }, floorRest.controls),
      pan: _objectSpread({
        enabled: true,
        /** 与 PisellFloorMapLayout `limitToBounds` 对齐：none 可一直拖动画布，不被内容包盒限制 */
        boundary: 'none'
      }, floorRest.pan),
      onItemClick: function onItemClick(item, index, event) {
        var _floorMapProp$onItemC;
        floorMapItemClickBefore === null || floorMapItemClickBefore === void 0 || floorMapItemClickBefore({
          item: item,
          index: index,
          event: event,
          mode: effectiveMapMode,
          dataSources: mergedDataSources
        });
        floorMapProp === null || floorMapProp === void 0 || (_floorMapProp$onItemC = floorMapProp.onItemClick) === null || _floorMapProp$onItemC === void 0 || _floorMapProp$onItemC.call(floorMapProp, item, index, event);
      },
      getMergedItemWrapperStyle: getMergedItemWrapperStyle,
      onSave: onSaveWithApi,
      /**
       * 顶栏「退出编辑 / 完成」联动：
       * - 仅在 mode 由内部受控（业务自管 mapEditInternal）时注入；mode 受控走父级 onModeChange。
       * - 「完成」= 顶栏内部先调 onSave，再调 onExitEdit；「取消编辑」= 仅调 onExitEdit。
       */
      onExitEdit: (_floorRest$onExitEdit = floorRest.onExitEdit) !== null && _floorRest$onExitEdit !== void 0 ? _floorRest$onExitEdit : isFloorModeControlled ? undefined : function () {
        setMapEditInternal(false);
      },
      floorMapViewportOverlay: (_floorRest$floorMapVi = floorRest.floorMapViewportOverlay) !== null && _floorRest$floorMapVi !== void 0 ? _floorRest$floorMapVi : reservationFloorMapViewportOverlay,
      /**
       * 场控 HUD 必须锚左下：低代码常写 `viewportOverlayPlacement: 'top-start'`，
       * 用 `??` 无法覆盖 truthy，会导致标题栏仍出现在左上。
       */
      viewportOverlayPlacement: floorMapHudTableDrawer ? 'bottom-start' : floorRest.viewportOverlayPlacement,
      viewportOverlayClassName: floorRest.viewportOverlayClassName,
      canvasTabsBarTrailing: floorRest.canvasTabsBarTrailing,
      /**
       * 视口持久化：`TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST === true` 时临时关闭读写，仅首屏全览；
       * 关闭该常量后恢复「尊重业务 persist + reservationViewportNamespace」。
       */
      viewportPersist: TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST ? false : floorRest.viewportPersist,
      viewportPersistNamespace: TEMP_DISABLE_RESERVATION_VIEWPORT_PERSIST ? undefined : (_floorRest$viewportPe = floorRest.viewportPersistNamespace) !== null && _floorRest$viewportPe !== void 0 ? _floorRest$viewportPe : reservationViewportNamespace,
      viewportDockToolButtons: (_floorRest$viewportDo = floorRest.viewportDockToolButtons) !== null && _floorRest$viewportDo !== void 0 ? _floorRest$viewportDo : /*#__PURE__*/React.createElement(ReservationFloorMapDockToolButtons, {
        appearanceMode: appearanceMode,
        onToggleAppearanceMode: onToggleAppearanceMode
      }),
      /**
       * 低代码常传 `viewportDockTrailing: false` 以隐藏 Dock 尾区（如「编辑画布」）。
       * ViewControls 用「尾槽是否存在」参与 showBar 计算：`false` 会导致无尾槽且无 zoom 时整条左下角控件消失。
       * 用空 Fragment 占位：不渲染编辑按钮，仍保留缩放/复位/fit 等 Dock 行为（与预约页默认一致）。
       */
      viewportDockTrailing: floorRest.viewportDockTrailing === false ? /*#__PURE__*/React.createElement(React.Fragment, null) : (_floorRest$viewportDo2 = floorRest.viewportDockTrailing) !== null && _floorRest$viewportDo2 !== void 0 ? _floorRest$viewportDo2 : /*#__PURE__*/React.createElement(ReservationFloorMapCanvasTabsTrailing, {
        isFloorModeControlled: isFloorModeControlled,
        mapEditInternal: mapEditInternal,
        setMapEditInternal: setMapEditInternal,
        floorMapLayoutRef: floorMapLayoutRef,
        phoneLayout: editTopBarPhoneLayoutParam
      }),
      readModeSelectedItemId: readModeSelectedItemIdParam !== null && readModeSelectedItemIdParam !== void 0 ? readModeSelectedItemIdParam : floorRest.readModeSelectedItemId,
      editTopBarPhoneLayout: (_floorRest$editTopBar = floorRest.editTopBarPhoneLayout) !== null && _floorRest$editTopBar !== void 0 ? _floorRest$editTopBar : editTopBarPhoneLayoutParam,
      /**
       * 预约平面图不做拓扑连线：禁止低代码 floorMap.enableEdges 误开四向锚点圆点。
       * 选中图元时仍可能有四角缩放手柄（布局编辑），与连线能力无关。
       */
      enableEdges: false,
      /**
       * 编辑态从画布添加资源时，使用 Pro 版资源选择 modal：顶部 PisellTabbarTemplate1，列表 Selector。
       * 通用基础 modal 已下线，由本注入承担；业务方可通过 `floorMap.renderResourcePickerModal` 显式覆盖。
       * 沿用原 floor-map 的 `area` 三级嵌套分类与卡片元信息（与下线前默认行为一致）。
       */
      renderResourcePickerModal: (_floorRest$renderReso = floorRest.renderResourcePickerModal) !== null && _floorRest$renderReso !== void 0 ? _floorRest$renderReso : function (modalProps) {
        return /*#__PURE__*/React.createElement(PisellProResourcePickerModal, _extends({}, modalProps, {
          platform: editTopBarPhoneLayoutParam ? 'h5' : 'pc',
          categoryConfig: getFloorMapCardPickerCategoryConfig(),
          getSearchText: floorMapResourcePickerRecordSearchText,
          getCardMeta: getFloorMapResourcePickerCardMeta,
          renderFilterBar: function renderFilterBar(ctx) {
            return /*#__PURE__*/React.createElement(PisellTabbarTemplate1, {
              className: "pisell-pro-resource-picker-tabbar",
              style: {
                position: 'sticky',
                top: 0,
                zIndex: 10,
                padding: 6,
                background: 'rgb(250, 250, 250)'
              },
              dataSource: ctx.tabbarDataSource,
              value: ctx.tabbarValue,
              onChange: ctx.onTabbarValueChange,
              onSearch: ctx.onKeywordChange,
              maxLevel: 3
            });
          }
        }));
      },
      renderPaletteViewAllModal: (_floorRest$renderPale = floorRest.renderPaletteViewAllModal) !== null && _floorRest$renderPale !== void 0 ? _floorRest$renderPale : function (viewAllProps) {
        return /*#__PURE__*/React.createElement(PisellFloorMapPaletteViewAllModal, _extends({}, viewAllProps, {
          platform: editTopBarPhoneLayoutParam ? 'h5' : 'pc'
        }));
      }
    });
  }, [baseFloorConfig, dataSources, floorMapProp, floorMapHudTableDrawer, reservationFloorMapViewportOverlay, renderItemByKind, gridDataSourceKey, appearanceMode, effectiveMapMode, resolvedFloorPlanId, floorPlanRemoteId, effectiveFloorPlanCode, floorPlanCanvasWidth, floorPlanCanvasHeight, floorPlanName, floorPlanSort, floorPlanStatus, onFloorPlanPersisted, putFloorPlan, isFloorModeControlled, mapEditInternal, floorMapLayoutRef, onToggleAppearanceMode, setRemoteFloorPlanView, floorMapItemClickBefore, engineLocale, readModeSelectedItemIdParam, editTopBarPhoneLayoutParam]);
}