import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { defaultPaymentStatusKeys } from "../../pisellSalesManagement/config/booking.js";
import { formatBookingResult, getBookingList } from "../../pisellSalesGrid/serve.js";
import dayjs from "dayjs";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { getUniqueId } from "@pisell/utils";
import { useMemoizedFn, useRequest } from "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 = dayjs()) {
	return { filter: { values: {
		order_payment_status: defaultPaymentStatusKeys,
		booking_time_start_between: bookingTimeWindowForAnchorDay(anchorDay.startOf("day"))
	} } };
}
/**
* 表格视图初始筛选项：与 Sales Monitor 一致——支付态 + **今日营业日窗口**（`bookingTimeWindowForAnchorDay`）。
* 用户可在 QuickFilter 改日期；平面图仍用独立的 `floorDayBookingData` 与顶栏日程对齐。
*/
function getGridTableBookingSearchParams() {
	return { filter: { values: {
		order_payment_status: defaultPaymentStatusKeys,
		booking_time_start_between: bookingTimeWindowForAnchorDay(dayjs().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] = useState({
		pageNumber: 1,
		pageSize: listPageSize
	});
	const [searchParams, setSearchParams] = useState(() => getInitialSearchParams());
	/** 列表 WebSocket 订阅 id，卸载时取消订阅（对齐 ticketBooking useProducts） */
	const subscriberIdRef = useRef(getUniqueId());
	const bookingMutateRef = useRef(null);
	const requestParams = useMemo(() => {
		const { keyword, filter, sort } = searchParams;
		const filterVals = (filter === null || filter === void 0 ? void 0 : filter.values) || {};
		return _objectSpread2(_objectSpread2(_objectSpread2({
			keyword,
			sort
		}, filterVals), extraRequestParams != null ? extraRequestParams : {}), {}, {
			skip: pagination.pageNumber,
			num: pagination.pageSize
		});
	}, [
		searchParams,
		pagination.pageNumber,
		pagination.pageSize,
		extraRequestParams
	]);
	const req = useRequest(useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (params) {
			if (!subscribeRealtimePush) return getBookingList(params);
			return 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, formatBookingResult(payload));
				}
			});
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}()), { manual: true });
	bookingMutateRef.current = req.mutate;
	useEffect(() => {
		if (!enabled) return;
		req.run(requestParams);
	}, [enabled, requestParams]);
	const onPageChange = useCallback((pageNumber, pageSize) => {
		if (pageNumber < 1 || pageSize < 1) return;
		setPagination({
			pageNumber,
			pageSize
		});
	}, []);
	const onSearch = useCallback((params) => {
		setSearchParams(params || {});
		setPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, []);
	const onReset = useCallback(() => {
		setSearchParams(getInitialSearchParams());
		setPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, [getInitialSearchParams]);
	const patchSearchParams = useCallback((updater) => {
		setSearchParams((prev) => updater(_objectSpread2({}, prev)));
		setPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
	}, []);
	const refresh = useCallback(() => {
		req.run(requestParams);
	}, [req, requestParams]);
	const refreshAsync = 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 = 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
export { EMPTY_RESERVATION_LIST, bookingTimeWindowForAnchorDay, getGridTableBookingSearchParams, usePisellReservationBookingData };
