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/pisellReservation/hooks/useReservationCalendarSlot.tsx
var useReservationCalendarSlot_exports = {};
__export(useReservationCalendarSlot_exports, {
  useReservationCalendarSlot: () => useReservationCalendarSlot
});
module.exports = __toCommonJS(useReservationCalendarSlot_exports);
var import_react = __toESM(require("react"));
var import_dayjs = __toESM(require("dayjs"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_utils = require("@pisell/utils");
var import_utils2 = require("../../../utils");
var import_reservationDataUtils = require("../data/reservationDataUtils");
var import_calendarAdapter = require("../data/calendarAdapter");
var import_bookingCalendarMoveIntegration = require("../data/bookingCalendarMoveIntegration");
var import_blockTimeModal = __toESM(require("../components/blockTimeModal"));
var import_reservationConstants = require("../reservationConstants");
var import_ReservationCalendarBookingNode = require("../components/ReservationCalendarBookingNode");
function useCalendarDragSuppressRef() {
  return (0, import_react.useRef)({ bookingId: null, timer: null });
}
function useReservationCalendarSlot(p) {
  const {
    isInternalListData,
    floorDayBookingData,
    operatingDayBoundary,
    tables,
    openBookingDetailFromRaw,
    schedule,
    handleScheduleChange,
    calendarResources,
    calendarBookings,
    effectiveTimelineRange,
    runtimeContext
  } = p;
  const calendarDragSuppressDetailRef = useCalendarDragSuppressRef();
  const [calendarGranularity, setCalendarGranularity] = (0, import_react.useState)("week");
  const calendarLoadedKeySetRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const calendarInflightKeyRef = (0, import_react.useRef)(null);
  const prevFloorDayLoadingRef = (0, import_react.useRef)(false);
  const handleCalendarAnchorChange = (0, import_react.useCallback)(
    (d) => {
      const dj = (0, import_dayjs.default)(d).startOf("day");
      const atSrc = (0, import_dayjs.default)(schedule.at);
      handleScheduleChange({
        date: dj,
        at: dj.hour(atSrc.hour()).minute(atSrc.minute()).second(0).millisecond(0)
      });
    },
    [handleScheduleChange, schedule.at]
  );
  const handleCalendarViewportChange = (0, import_react.useCallback)(
    (payload) => {
      if (!isInternalListData) return;
      floorDayBookingData.patchSearchParams((prev) => {
        const merged = (0, import_reservationDataUtils.mergeSearchParamsBookingRange)(
          prev,
          payload.rangeStart,
          payload.rangeEnd,
          operatingDayBoundary
        );
        const filterObj = merged.filter && typeof merged.filter === "object" ? merged.filter : {};
        const valuesObj = filterObj.values && typeof filterObj.values === "object" ? { ...filterObj.values } : {};
        if (payload.view === "week" || payload.view === "month" || payload.view === "resource") {
          valuesObj.enable_remote_memory_cache = true;
          valuesObj.compact_fields = true;
        } else {
          delete valuesObj.enable_remote_memory_cache;
          delete valuesObj.compact_fields;
        }
        return {
          ...merged,
          filter: {
            ...filterObj,
            values: valuesObj
          }
        };
      });
    },
    [
      isInternalListData,
      floorDayBookingData.patchSearchParams,
      operatingDayBoundary
    ]
  );
  const handleCalendarBookingClick = (0, import_react.useCallback)(
    (item) => {
      const raw = item.raw;
      if (!raw || typeof raw !== "object") return false;
      openBookingDetailFromRaw({
        raw,
        row: (0, import_calendarAdapter.findMergedTableRowForBookingRaw)(
          raw,
          tables
        )
      });
      return true;
    },
    [openBookingDetailFromRaw, tables]
  );
  const reservationCalendarPersist = (0, import_react.useMemo)(() => {
    return {
      beforePersist: () => {
        import_antd.message.warning(import_utils.locales.getText(import_reservationConstants.I18N_CALENDAR_WRITE_NOT_AVAILABLE));
        return false;
      }
    };
  }, []);
  const renderReservationCalendarBooking = (0, import_react.useCallback)(
    (args) => /* @__PURE__ */ import_react.default.createElement(
      import_ReservationCalendarBookingNode.ReservationCalendarBookingNode,
      {
        args,
        tables,
        calendarDragSuppressDetailRef
      }
    ),
    [tables]
  );
  const handleBlockedTimePanelRequest = (0, import_ahooks.useMemoizedFn)(
    async (payload) => {
      const { mergedRange, slotStepMinutes } = payload;
      try {
        await import_blockTimeModal.default.open({
          resources: calendarResources,
          initialResourceId: mergedRange.courtId,
          initialTimeRange: [
            (0, import_calendarAdapter.dayjsFromCalendarHour)(mergedRange.date, mergedRange.startHour),
            (0, import_calendarAdapter.dayjsFromCalendarHour)(mergedRange.date, mergedRange.endHour)
          ],
          minuteStep: slotStepMinutes,
          blockedSalesChannels: ["online_store"],
          onSubmit: async ({ submitPayload }) => {
            await import_utils2.request.getRequest().post("/shop/schedule/blocked-time", submitPayload);
            import_antd.message.success("保存成功");
            await runtimeContext.refreshAsync();
          }
        });
        return true;
      } catch {
        return false;
      }
    }
  );
  const handleCalendarBookingMoveRequest = (0, import_ahooks.useMemoizedFn)(
    async (payload) => (0, import_bookingCalendarMoveIntegration.openBookingChangeModalAfterCalendarDrag)({
      calendarItem: payload.item,
      draft: payload.draft,
      calendarResources,
      calendarBookings,
      effectiveTimelineRange,
      anchorDate: schedule.date.toDate(),
      slotStepMinutes: 30,
      onSuccessRefresh: async () => {
        await runtimeContext.refreshAsync();
      }
    })
  );
  const calendarLoadKey = (0, import_react.useMemo)(
    () => `${calendarGranularity}_${(0, import_dayjs.default)(schedule.date).startOf("day").valueOf()}_${(0, import_dayjs.default)(
      schedule.at
    ).valueOf()}`,
    [calendarGranularity, schedule.date, schedule.at]
  );
  (0, import_react.useEffect)(() => {
    const prev = prevFloorDayLoadingRef.current;
    const now = floorDayBookingData.loading;
    if (!prev && now) {
      calendarInflightKeyRef.current = calendarLoadKey;
    } else if (prev && now && calendarInflightKeyRef.current !== calendarLoadKey) {
      calendarInflightKeyRef.current = calendarLoadKey;
    } else if (prev && !now) {
      const doneKey = calendarInflightKeyRef.current ?? calendarLoadKey;
      calendarLoadedKeySetRef.current.add(doneKey);
      calendarInflightKeyRef.current = null;
    }
    prevFloorDayLoadingRef.current = now;
  }, [floorDayBookingData.loading, calendarLoadKey]);
  const calendarLoading = (0, import_react.useMemo)(() => {
    if (calendarGranularity === "week" || calendarGranularity === "month" || calendarGranularity === "resource") {
      return false;
    }
    if (!floorDayBookingData.loading) return false;
    return !calendarLoadedKeySetRef.current.has(calendarLoadKey);
  }, [floorDayBookingData.loading, calendarLoadKey, calendarGranularity]);
  const onCreateBookingFromSelection = (0, import_ahooks.useMemoizedFn)(
    (payload) => {
      const resourceName = (id) => {
        var _a;
        return ((_a = calendarResources.find((r) => String(r.id) === String(id))) == null ? void 0 : _a.name) ?? id;
      };
      if (payload.mode === "day") {
        console.log("[Create booking] 日视图", {
          groups: payload.groups.map((g) => ({
            resourceId: g.courtId,
            resourceName: resourceName(g.courtId),
            date: g.date,
            startHour: g.startHour,
            endHour: g.endHour
          }))
        });
        return;
      }
      const { courtId, dates, startHour, endHour } = payload;
      console.log("[Create booking] 资源视图", {
        resourceId: courtId,
        resourceName: resourceName(courtId),
        dates,
        dateRange: dates.length > 1 ? `${dates[0]} ~ ${dates[dates.length - 1]}` : dates[0],
        startHour,
        endHour
      });
    }
  );
  const reservationCalendarSlotProps = (0, import_react.useMemo)(() => {
    return {
      persistGuard: reservationCalendarPersist,
      resources: calendarResources,
      bookings: calendarBookings,
      loading: false,
      onViewportChange: handleCalendarViewportChange,
      onBookingClick: handleCalendarBookingClick,
      timelineRange: effectiveTimelineRange,
      calendarView: calendarGranularity,
      onCalendarViewChange: setCalendarGranularity,
      anchorDate: schedule.date.toDate(),
      onAnchorDateChange: handleCalendarAnchorChange,
      slotStepMinutes: 30,
      renderBooking: renderReservationCalendarBooking,
      blockedTimeSalesChannels: ["online_store"],
      onBlockedTimePanelRequest: handleBlockedTimePanelRequest,
      onBookingMoveRequest: handleCalendarBookingMoveRequest,
      onCreateBookingFromSelection
    };
  }, [
    reservationCalendarPersist,
    calendarResources,
    calendarBookings,
    handleCalendarViewportChange,
    handleCalendarBookingClick,
    calendarGranularity,
    schedule.date,
    handleCalendarAnchorChange,
    effectiveTimelineRange,
    renderReservationCalendarBooking,
    handleBlockedTimePanelRequest,
    handleCalendarBookingMoveRequest,
    onCreateBookingFromSelection
  ]);
  return {
    reservationCalendarSlotProps,
    calendarGranularity,
    setCalendarGranularity
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useReservationCalendarSlot
});
