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/usePisellReservationBookingData.ts
var usePisellReservationBookingData_exports = {};
__export(usePisellReservationBookingData_exports, {
  EMPTY_RESERVATION_LIST: () => EMPTY_RESERVATION_LIST,
  bookingTimeWindowForAnchorDay: () => bookingTimeWindowForAnchorDay,
  bookingTimeWindowForCalendarRange: () => bookingTimeWindowForCalendarRange,
  bookingTimeWindowForCalendarRequest: () => bookingTimeWindowForCalendarRequest,
  bookingTimeWindowForReservationRequest: () => bookingTimeWindowForReservationRequest,
  bookingTimeWindowForReservationView: () => bookingTimeWindowForReservationView,
  bookingWindowClockOrDefault: () => bookingWindowClockOrDefault,
  getDefaultMonitorSearchParams: () => getDefaultMonitorSearchParams,
  getGridTableBookingSearchParams: () => getGridTableBookingSearchParams,
  usePisellReservationBookingData: () => usePisellReservationBookingData
});
module.exports = __toCommonJS(usePisellReservationBookingData_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_reservationOperatingDayRange = require("../data/reservationOperatingDayRange");
var import_reservationConstants = require("../reservationConstants");
var import_booking = require("../../pisellSalesManagement/config/booking");
var import_serve = require("../../pisellSalesGrid/serve");
var EMPTY_RESERVATION_LIST = [];
function bookingWindowClockOrDefault(operatingDayBoundary) {
  return (0, import_reservationOperatingDayRange.boundaryClockFromOperatingDayBoundary)(operatingDayBoundary) ?? import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE.start;
}
function anchorAtBoundaryClock(d0, clock) {
  const [hs, ms] = clock.split(":");
  const h = Number(hs);
  const m = Number(ms ?? "0");
  return d0.hour(h).minute(m).second(0).millisecond(0);
}
function isEndTimeOperatingBoundary(operatingDayBoundary) {
  const b = operatingDayBoundary;
  return String((b == null ? void 0 : b.type) ?? "") === "end_time";
}
function bookingTimeWindowForAnchorDay(anchorDay, operatingDayBoundary) {
  const clock = bookingWindowClockOrDefault(operatingDayBoundary);
  const d0 = anchorDay.startOf("day");
  const refDay = isEndTimeOperatingBoundary(operatingDayBoundary) ? d0.subtract(1, "day") : d0;
  const start = anchorAtBoundaryClock(refDay, clock);
  const end = start.add(1, "day");
  return [start, end];
}
function bookingTimeWindowForReservationView(scheduleDate, operatingDayBoundary, timelineRange = import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE, wallClock = (0, import_dayjs.default)()) {
  const anchorDay = (0, import_dayjs.default)(scheduleDate).startOf("day");
  const isViewingToday = anchorDay.isSame(wallClock.startOf("day"), "day");
  if (isViewingToday) {
    const ref = (0, import_materials.pickReferenceDateContainingNow)(timelineRange, wallClock);
    return (0, import_materials.getRangeBounds)(timelineRange, ref);
  }
  return bookingTimeWindowForAnchorDay(anchorDay, operatingDayBoundary);
}
function bookingTimeWindowRequestStrings(range) {
  return [
    (0, import_dayjs.default)(range[0]).format("YYYY-MM-DD HH:mm:ss"),
    (0, import_dayjs.default)(range[1]).subtract(1, "second").format("YYYY-MM-DD HH:mm:ss")
  ];
}
function bookingTimeWindowForReservationRequest(scheduleDate, operatingDayBoundary, timelineRange = import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE, wallClock = (0, import_dayjs.default)()) {
  return bookingTimeWindowRequestStrings(
    bookingTimeWindowForReservationView(
      scheduleDate,
      operatingDayBoundary,
      timelineRange,
      wallClock
    )
  );
}
function bookingTimeWindowForCalendarRange(rangeStart, rangeEnd, operatingDayBoundary) {
  const clock = bookingWindowClockOrDefault(operatingDayBoundary);
  let rs = (0, import_dayjs.default)(rangeStart).startOf("day");
  let re = (0, import_dayjs.default)(rangeEnd).startOf("day");
  if (re.isBefore(rs)) {
    const t = rs;
    rs = re;
    re = t;
  }
  if (isEndTimeOperatingBoundary(operatingDayBoundary)) {
    const start2 = anchorAtBoundaryClock(rs.subtract(1, "day"), clock);
    const end2 = anchorAtBoundaryClock(re, clock);
    return [start2, end2];
  }
  const start = anchorAtBoundaryClock(rs, clock);
  const end = anchorAtBoundaryClock(re.add(1, "day"), clock);
  return [start, end];
}
function bookingTimeWindowForCalendarRequest(rangeStart, rangeEnd, operatingDayBoundary) {
  return bookingTimeWindowRequestStrings(
    bookingTimeWindowForCalendarRange(rangeStart, rangeEnd, operatingDayBoundary)
  );
}
function getDefaultMonitorSearchParams(anchorDay = (0, import_dayjs.default)(), operatingDayBoundary, timelineRange = import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE, now = (0, import_dayjs.default)()) {
  return {
    filter: {
      values: {
        order_payment_status: import_booking.defaultPaymentStatusKeys,
        booking_time_start_between: bookingTimeWindowForReservationRequest(
          anchorDay.startOf("day"),
          operatingDayBoundary,
          timelineRange,
          now
        )
      }
    }
  };
}
function getGridTableBookingSearchParams(operatingDayBoundary, timelineRange = import_reservationConstants.RESERVATION_TIMELINE_BUSINESS_RANGE) {
  return getDefaultMonitorSearchParams(
    (0, import_dayjs.default)().startOf("day"),
    operatingDayBoundary,
    timelineRange
  );
}
function usePisellReservationBookingData(enabled, options) {
  var _a, _b;
  const listPageSize = (options == null ? void 0 : options.listPageSize) ?? 50;
  const getInitialSearchParams = (options == null ? void 0 : options.getInitialSearchParams) ?? (() => getDefaultMonitorSearchParams((0, import_dayjs.default)()));
  const extraRequestParams = options == null ? void 0 : options.extraRequestParams;
  const subscribeRealtimePush = (options == null ? void 0 : options.subscribeRealtimePush) ?? true;
  const [pagination, setPagination] = (0, import_react.useState)({
    pageNumber: 1,
    pageSize: listPageSize
  });
  const [searchParams, setSearchParams] = (0, import_react.useState)(
    () => getInitialSearchParams()
  );
  const subscriberIdRef = (0, import_react.useRef)((0, import_utils.getUniqueId)());
  const bookingMutateRef = (0, import_react.useRef)(null);
  const pendingPayloadRef = (0, import_react.useRef)(null);
  const flushScheduledRef = (0, import_react.useRef)(null);
  const isMountedRef = (0, import_react.useRef)(true);
  const [pushDataVersion, setPushDataVersion] = (0, import_react.useState)(0);
  (0, import_react.useEffect)(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
      if (flushScheduledRef.current != null) {
        cancelAnimationFrame(flushScheduledRef.current);
        flushScheduledRef.current = null;
      }
      pendingPayloadRef.current = null;
    };
  }, []);
  const requestParams = (0, import_react.useMemo)(() => {
    const { keyword, filter, sort } = searchParams;
    const filterVals = (filter == null ? void 0 : filter.values) || {};
    return {
      keyword,
      sort,
      ...filterVals,
      ...extraRequestParams != null ? extraRequestParams : {},
      skip: pagination.pageNumber,
      num: pagination.pageSize
    };
  }, [
    searchParams,
    pagination.pageNumber,
    pagination.pageSize,
    extraRequestParams
  ]);
  const fetchBookingList = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (!subscribeRealtimePush) {
        return (0, import_serve.getBookingList)(params, {
          osServer: true
        });
      }
      return (0, import_serve.getBookingList)(params, {
        osServer: true,
        subscriberId: subscriberIdRef.current,
        /**
         * 订阅推送会多次进 callback；若 payload 没有与列表接口一致的 `list` 数组，
         * 不能 mutate 整块覆盖，否则会抹掉 HTTP 刚写入的 `list`，表格一直为空。
         *
         * 性能优化：同一渲染帧内可能收到多条推送（后端常按 booking 逐条推），
         * 这里把每一条 payload 暂存到 ref，只在 rAF 里跑一次 `formatBookingResult + mutate`，
         * 把 N 次「mutate → setSalesResourceBookings → tables 全量 re-merge → canvas 重渲染」
         * 合并成 1 次，显著降低推送密集时的卡顿与画布闪烁。
         */
        callback: (res) => {
          const payload = (res == null ? void 0 : res.data) ?? res;
          if (payload == null || !Array.isArray(payload.list)) return;
          pendingPayloadRef.current = payload;
          if (flushScheduledRef.current != null) return;
          flushScheduledRef.current = requestAnimationFrame(() => {
            var _a2;
            flushScheduledRef.current = null;
            const next = pendingPayloadRef.current;
            pendingPayloadRef.current = null;
            if (next == null || !isMountedRef.current) return;
            (_a2 = bookingMutateRef.current) == null ? void 0 : _a2.call(bookingMutateRef, (0, import_serve.formatBookingResult)(next));
            setPushDataVersion((v) => v + 1);
          });
        }
      });
    }
  );
  const req = (0, import_ahooks.useRequest)(fetchBookingList, { manual: true });
  bookingMutateRef.current = req.mutate;
  (0, import_react.useEffect)(() => {
    if (!enabled) return;
    void req.run(requestParams);
  }, [enabled, requestParams]);
  const onPageChange = (0, import_react.useCallback)((pageNumber, pageSize) => {
    if (pageNumber < 1 || pageSize < 1) return;
    setPagination({ pageNumber, pageSize });
  }, []);
  const onSearch = (0, import_react.useCallback)((params) => {
    setSearchParams(params || {});
    setPagination((p) => ({ ...p, pageNumber: 1 }));
  }, []);
  const onReset = (0, import_react.useCallback)(() => {
    setSearchParams(getInitialSearchParams());
    setPagination((p) => ({ ...p, pageNumber: 1 }));
  }, [getInitialSearchParams]);
  const patchSearchParams = (0, import_react.useCallback)(
    (updater) => {
      setSearchParams((prev) => updater({ ...prev }));
      setPagination((p) => ({ ...p, pageNumber: 1 }));
    },
    []
  );
  const refresh = (0, import_react.useCallback)(() => {
    void req.run(requestParams);
  }, [req, requestParams]);
  const refreshAsync = (0, import_react.useCallback)(() => {
    return req.runAsync(requestParams);
  }, [req, requestParams]);
  const rawList = (_a = req.data) == null ? void 0 : _a.list;
  const data = (0, import_react.useMemo)(() => {
    if (!Array.isArray(rawList) || rawList.length === 0) {
      return EMPTY_RESERVATION_LIST;
    }
    return rawList;
  }, [rawList]);
  const total = ((_b = req.data) == null ? void 0 : _b.count) ?? 0;
  const loading = req.loading;
  return {
    data,
    loading,
    total,
    pagination,
    onPageChange,
    searchParams,
    onSearch,
    onReset,
    refresh,
    refreshAsync,
    patchSearchParams,
    pushDataVersion
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  EMPTY_RESERVATION_LIST,
  bookingTimeWindowForAnchorDay,
  bookingTimeWindowForCalendarRange,
  bookingTimeWindowForCalendarRequest,
  bookingTimeWindowForReservationRequest,
  bookingTimeWindowForReservationView,
  bookingWindowClockOrDefault,
  getDefaultMonitorSearchParams,
  getGridTableBookingSearchParams,
  usePisellReservationBookingData
});
