const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_booking = require("../../pisellSalesManagement/config/booking.js");
const require_serve = require("../../pisellSalesGrid/serve.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
let _pisell_utils = require("@pisell/utils");
let ahooks = require("ahooks");
//#region src/plus/pisellReservation/hooks/usePisellReservationBookingData.ts
/**
* 预约看板列表：与 Sales Management「预约 / monitor」一致，请求 GET /shop/schedule/booking
*/
/** 避免 `?? []` 每次 render 新数组引用，触发依赖 list 的 effect 死循环 */
const EMPTY_RESERVATION_LIST = [];
/** 营业日锚定：当日 02:00 — 次日 02:00（与时间轴默认一致） */
function bookingTimeWindowForAnchorDay(anchorDay) {
	const d0 = anchorDay.startOf("day");
	return [d0.hour(2).minute(0).second(0).millisecond(0), d0.add(1, "day").hour(2).minute(0).second(0).millisecond(0)];
}
function getDefaultMonitorSearchParams(anchorDay = (0, dayjs.default)()) {
	return { filter: { values: {
		order_payment_status: require_booking.defaultPaymentStatusKeys,
		booking_time_start_between: bookingTimeWindowForAnchorDay(anchorDay.startOf("day"))
	} } };
}
/**
* 表格视图初始筛选项：与 Sales Monitor 一致——支付态 + **今日营业日窗口**（`bookingTimeWindowForAnchorDay`）。
* 用户可在 QuickFilter 改日期；平面图仍用独立的 `floorDayBookingData` 与顶栏日程对齐。
*/
function getGridTableBookingSearchParams() {
	return { filter: { values: {
		order_payment_status: require_booking.defaultPaymentStatusKeys,
		booking_time_start_between: bookingTimeWindowForAnchorDay((0, dayjs.default)().startOf("day"))
	} } };
}
function usePisellReservationBookingData(enabled, options) {
	var _options$listPageSize, _options$getInitialSe, _options$subscribeRea, _req$data, _req$data$count, _req$data2;
	const listPageSize = (_options$listPageSize = options === null || options === void 0 ? void 0 : options.listPageSize) !== null && _options$listPageSize !== void 0 ? _options$listPageSize : 50;
	const getInitialSearchParams = (_options$getInitialSe = options === null || options === void 0 ? void 0 : options.getInitialSearchParams) !== null && _options$getInitialSe !== void 0 ? _options$getInitialSe : getDefaultMonitorSearchParams;
	const extraRequestParams = options === null || options === void 0 ? void 0 : options.extraRequestParams;
	const subscribeRealtimePush = (_options$subscribeRea = options === null || options === void 0 ? void 0 : options.subscribeRealtimePush) !== null && _options$subscribeRea !== void 0 ? _options$subscribeRea : true;
	const [pagination, setPagination] = (0, react.useState)({
		pageNumber: 1,
		pageSize: listPageSize
	});
	const [searchParams, setSearchParams] = (0, react.useState)(() => getInitialSearchParams());
	/** 列表 WebSocket 订阅 id，卸载时取消订阅（对齐 ticketBooking useProducts） */
	const subscriberIdRef = (0, react.useRef)((0, _pisell_utils.getUniqueId)());
	const bookingMutateRef = (0, react.useRef)(null);
	const requestParams = (0, react.useMemo)(() => {
		const { keyword, filter, sort } = searchParams;
		const filterVals = (filter === null || filter === void 0 ? void 0 : filter.values) || {};
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
			keyword,
			sort
		}, filterVals), extraRequestParams != null ? extraRequestParams : {}), {}, {
			skip: pagination.pageNumber,
			num: pagination.pageSize
		});
	}, [
		searchParams,
		pagination.pageNumber,
		pagination.pageSize,
		extraRequestParams
	]);
	const req = (0, ahooks.useRequest)((0, ahooks.useMemoizedFn)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (params) {
			if (!subscribeRealtimePush) return require_serve.getBookingList(params);
			return require_serve.getBookingList(params, {
				osServer: true,
				subscriberId: subscriberIdRef.current,
				callback: (res) => {
					var _res$data, _bookingMutateRef$cur;
					const payload = (_res$data = res === null || res === void 0 ? void 0 : res.data) !== null && _res$data !== void 0 ? _res$data : res;
					if (payload == null || !Array.isArray(payload.list)) return;
					/**
					* 订阅推送常在 HTTP 分页返回之后到达；若 payload 为 `list: []`（无有效行），
					* mutate 会整块覆盖 useRequest 里刚写入的当前页，表现为「每次翻页都有请求但表格不展示」。
					* 有意清空列表应依赖再次请求或明确带 count 的整包推送，此处不处理空 list 覆盖。
					*/
					if (payload.list.length === 0) return;
					(_bookingMutateRef$cur = bookingMutateRef.current) === null || _bookingMutateRef$cur === void 0 || _bookingMutateRef$cur.call(bookingMutateRef, require_serve.formatBookingResult(payload));
				}
			});
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}()), { manual: true });
	bookingMutateRef.current = req.mutate;
	(0, react.useEffect)(() => {
		if (!enabled) return;
		req.run(requestParams);
	}, [enabled, requestParams]);
	const onPageChange = (0, react.useCallback)((pageNumber, pageSize) => {
		if (pageNumber < 1 || pageSize < 1) return;
		setPagination({
			pageNumber,
			pageSize
		});
	}, []);
	const onSearch = (0, react.useCallback)((params) => {
		setSearchParams(params || {});
		setPagination((p) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, []);
	const onReset = (0, react.useCallback)(() => {
		setSearchParams(getInitialSearchParams());
		setPagination((p) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, [getInitialSearchParams]);
	const patchSearchParams = (0, react.useCallback)((updater) => {
		setSearchParams((prev) => updater(require_objectSpread2._objectSpread2({}, prev)));
		setPagination((p) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, []);
	const refresh = (0, react.useCallback)(() => {
		req.run(requestParams);
	}, [req, requestParams]);
	const refreshAsync = (0, react.useCallback)(() => {
		return req.runAsync(requestParams);
	}, [req, requestParams]);
	/** 接口常返回新的 `[]`，勿直接作依赖否则下游 effect（如 sales 合并）死循环 */
	const rawList = (_req$data = req.data) === null || _req$data === void 0 ? void 0 : _req$data.list;
	const data = (0, react.useMemo)(() => {
		if (!Array.isArray(rawList) || rawList.length === 0) return EMPTY_RESERVATION_LIST;
		return rawList;
	}, [rawList]);
	const total = (_req$data$count = (_req$data2 = req.data) === null || _req$data2 === void 0 ? void 0 : _req$data2.count) !== null && _req$data$count !== void 0 ? _req$data$count : 0;
	return {
		data,
		loading: req.loading,
		total,
		pagination,
		onPageChange,
		searchParams,
		onSearch,
		onReset,
		refresh,
		refreshAsync,
		patchSearchParams
	};
}
//#endregion
exports.EMPTY_RESERVATION_LIST = EMPTY_RESERVATION_LIST;
exports.bookingTimeWindowForAnchorDay = bookingTimeWindowForAnchorDay;
exports.getGridTableBookingSearchParams = getGridTableBookingSearchParams;
exports.usePisellReservationBookingData = usePisellReservationBookingData;
