import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { SalesSdkContext } from "./SalesSdkContext.js";
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/plus/salesSdk/context/SalesSdkSummaryContext.tsx
const SalesSdkSummaryContext = createContext(null);
SalesSdkSummaryContext.displayName = "SalesSdkSummaryContext";
/**
* 仅供 SDK 内部 Provider/action 调用，不对外暴露。
*/
const SalesSdkSummaryRefreshContext = createContext(null);
SalesSdkSummaryRefreshContext.displayName = "SalesSdkSummaryRefreshContext";
const SalesSdkSummaryProvider = ({ children }) => {
	var _sales$bookingTicket;
	const sales = useContext(SalesSdkContext);
	const bookingTicket = (_sales$bookingTicket = sales === null || sales === void 0 ? void 0 : sales.bookingTicket) !== null && _sales$bookingTicket !== void 0 ? _sales$bookingTicket : null;
	const [summary, setSummary] = useState(null);
	const requestIdRef = useRef(0);
	const refreshSummary = useMemoizedFn(_asyncToGenerator(function* () {
		const requestId = ++requestIdRef.current;
		if (!bookingTicket) {
			setSummary(null);
			return null;
		}
		const next = yield bookingTicket.getSummary();
		if (requestId === requestIdRef.current) setSummary(next !== null && next !== void 0 ? next : null);
		return next !== null && next !== void 0 ? next : null;
	}));
	useEffect(() => {
		refreshSummary().catch((e) => {
			console.warn("[SalesSdk] SummaryProvider 初始拉取 summary 失败", e);
			setSummary(null);
		});
	}, [bookingTicket, refreshSummary]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			refreshSummary().catch((e) => {
				console.warn("[SalesSdk] SummaryProvider onSalesOrderLoaded 刷新失败", e);
			});
		});
		return () => {
			try {
				off();
			} catch (_unused) {}
		};
	}, [bookingTicket, refreshSummary]);
	const value = useMemo(() => ({ summary }), [summary]);
	return /* @__PURE__ */ React.createElement(SalesSdkSummaryRefreshContext.Provider, { value: refreshSummary }, /* @__PURE__ */ React.createElement(SalesSdkSummaryContext.Provider, { value }, children));
};
//#endregion
export { SalesSdkSummaryContext, SalesSdkSummaryProvider, SalesSdkSummaryRefreshContext };
