import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { SalesSdkContext } from "./SalesSdkContext.js";
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/plus/salesSdk/context/SalesSdkCustomerContext.tsx
const SalesSdkCustomerContext = createContext(null);
SalesSdkCustomerContext.displayName = "SalesSdkCustomerContext";
const DEFAULT_PAGINATION = {
	page: 1,
	pageSize: 20,
	total: 0,
	totalPages: 0
};
const EMPTY_CUSTOMER_LIST = [];
const EMPTY_SEARCH_PARAMS = {};
/**
* 客户 Provider。
*
* 数据源拆分为两条互不相同的链路：
*  1. 客户列表（搜索/分页/置顶）→ 直接消费 OS CustomerModule
*     - `${customer.name}:onCustomerListUpdate`：getCustomerList / loadMore / addToFirst 后触发
*     - `${customer.name}:onPaginationChange`：分页变化触发
*  2. 当前下单客户（selected）→ 单一真源是 OrderModule.tempOrder snapshot
*     - 订阅 `${bookingTicket.name}:onOrderCustomerChange`：包含
*       { patch: OrderCustomerView, snapshot: ICustomer | null } 或 null（清空）
*     - 初始同步通过 bookingTicket.getOrderCustomerSnapshot() 读取
*     - 编辑态进入时 OS BaseSales 已经把 customer 协议字段写入 tempOrder，
*       这里继续监听 onSalesOrderLoaded 兜底刷新一次。
*
* Action 引用纪律：每个 action 用 `useMemoizedFn` 单独包装；详见 docs.md。
*/
const SalesSdkCustomerProvider = ({ children }) => {
	var _sales$bookingTicket, _bookingTicket$store$, _bookingTicket$store;
	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 customerModule = (_bookingTicket$store$ = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$store = bookingTicket.store) === null || _bookingTicket$store === void 0 ? void 0 : _bookingTicket$store.customer) !== null && _bookingTicket$store$ !== void 0 ? _bookingTicket$store$ : null;
	const [selected, setSelected] = useState(null);
	const [list, setList] = useState(EMPTY_CUSTOMER_LIST);
	const [pagination, setPagination] = useState(DEFAULT_PAGINATION);
	const [hasMore, setHasMore] = useState(false);
	const [loading, setLoading] = useState(false);
	const [loadingMore, setLoadingMore] = useState(false);
	const [searchParams, setSearchParams] = useState(EMPTY_SEARCH_PARAMS);
	useEffect(() => {
		if (!bookingTicket) {
			setSelected(null);
			setList(EMPTY_CUSTOMER_LIST);
			setPagination(DEFAULT_PAGINATION);
			setHasMore(false);
			setLoading(false);
			setLoadingMore(false);
			setSearchParams(EMPTY_SEARCH_PARAMS);
			return;
		}
		try {
			var _bookingTicket$getOrd, _bookingTicket$getOrd2, _bookingTicket$getCus, _bookingTicket$getCus2, _bookingTicket$getCus3, _bookingTicket$getCus4;
			setSelected((_bookingTicket$getOrd = (_bookingTicket$getOrd2 = bookingTicket.getOrderCustomerSnapshot) === null || _bookingTicket$getOrd2 === void 0 ? void 0 : _bookingTicket$getOrd2.call(bookingTicket)) !== null && _bookingTicket$getOrd !== void 0 ? _bookingTicket$getOrd : null);
			setList((_bookingTicket$getCus = (_bookingTicket$getCus2 = bookingTicket.getCustomers) === null || _bookingTicket$getCus2 === void 0 ? void 0 : _bookingTicket$getCus2.call(bookingTicket)) !== null && _bookingTicket$getCus !== void 0 ? _bookingTicket$getCus : EMPTY_CUSTOMER_LIST);
			setPagination((_bookingTicket$getCus3 = (_bookingTicket$getCus4 = bookingTicket.getCustomerPaginationInfo) === null || _bookingTicket$getCus4 === void 0 ? void 0 : _bookingTicket$getCus4.call(bookingTicket)) !== null && _bookingTicket$getCus3 !== void 0 ? _bookingTicket$getCus3 : DEFAULT_PAGINATION);
		} catch (e) {
			console.warn("[SalesSdk] CustomerProvider 初始同步失败", e);
		}
	}, [bookingTicket]);
	useEffect(() => {
		if (!customerModule || typeof customerModule.effectsOn !== "function") return;
		const offs = [];
		offs.push(customerModule.effectsOn("onCustomerListUpdate", (state) => {
			if (Array.isArray(state === null || state === void 0 ? void 0 : state.customerList)) setList(state.customerList);
			if (typeof (state === null || state === void 0 ? void 0 : state.hasMore) === "boolean") setHasMore(state.hasMore);
			if (typeof (state === null || state === void 0 ? void 0 : state.loading) === "boolean") setLoading(state.loading);
			if (typeof (state === null || state === void 0 ? void 0 : state.loadingMore) === "boolean") setLoadingMore(state.loadingMore);
			if ((state === null || state === void 0 ? void 0 : state.searchParams) && typeof state.searchParams === "object") setSearchParams(state.searchParams);
			if (typeof (state === null || state === void 0 ? void 0 : state.total) === "number" && typeof (state === null || state === void 0 ? void 0 : state.currentPage) === "number" && typeof (state === null || state === void 0 ? void 0 : state.pageSize) === "number") setPagination({
				page: state.currentPage,
				pageSize: state.pageSize,
				total: state.total,
				totalPages: Math.ceil(state.total / Math.max(state.pageSize, 1)) || 0
			});
		}));
		offs.push(customerModule.effectsOn("onPaginationChange", (info) => {
			if (info && typeof info === "object") setPagination(info);
		}));
		return () => {
			for (const off of offs) try {
				off();
			} catch (_unused) {}
		};
	}, [customerModule]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onOrderCustomerChange", (payload) => {
			var _payload$snapshot;
			setSelected((_payload$snapshot = payload === null || payload === void 0 ? void 0 : payload.snapshot) !== null && _payload$snapshot !== void 0 ? _payload$snapshot : null);
		});
		return () => {
			try {
				off();
			} catch (_unused2) {}
		};
	}, [bookingTicket]);
	useEffect(() => {
		if (!bookingTicket) return;
		const off = bookingTicket.effectsOn("onSalesOrderLoaded", () => {
			try {
				var _bookingTicket$getOrd3, _bookingTicket$getOrd4;
				setSelected((_bookingTicket$getOrd3 = (_bookingTicket$getOrd4 = bookingTicket.getOrderCustomerSnapshot) === null || _bookingTicket$getOrd4 === void 0 ? void 0 : _bookingTicket$getOrd4.call(bookingTicket)) !== null && _bookingTicket$getOrd3 !== void 0 ? _bookingTicket$getOrd3 : null);
			} catch (_unused3) {}
		});
		return () => {
			try {
				off();
			} catch (_unused4) {}
		};
	}, [bookingTicket]);
	const select = useMemoizedFn((customer) => {
		var _bookingTicket$setOrd;
		if (!bookingTicket) {
			console.warn("[SalesSdk] Customer.select: bookingTicket 未就绪");
			return;
		}
		(_bookingTicket$setOrd = bookingTicket.setOrderCustomer) === null || _bookingTicket$setOrd === void 0 || _bookingTicket$setOrd.call(bookingTicket, customer);
	});
	const loadList = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (params) {
			if (!bookingTicket) throw new Error("[SalesSdk] Customer: bookingTicket 未初始化");
			return bookingTicket.getCustomerList(params);
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	const search = useMemoizedFn(function() {
		var _ref2 = _asyncToGenerator(function* (keyword) {
			if (!bookingTicket) throw new Error("[SalesSdk] Customer: bookingTicket 未初始化");
			return bookingTicket.resetAndLoadCustomers({ search: keyword });
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const loadMore = useMemoizedFn(_asyncToGenerator(function* () {
		if (!bookingTicket) throw new Error("[SalesSdk] Customer: bookingTicket 未初始化");
		return bookingTicket.loadMoreCustomers();
	}));
	const changePage = useMemoizedFn(function() {
		var _ref3 = _asyncToGenerator(function* (page, pageSize) {
			if (!bookingTicket) throw new Error("[SalesSdk] Customer: bookingTicket 未初始化");
			return bookingTicket.changeCustomerPage(page, pageSize);
		});
		return function(_x3, _x4) {
			return _ref3.apply(this, arguments);
		};
	}());
	const addToFirst = useMemoizedFn((customer) => {
		bookingTicket === null || bookingTicket === void 0 || bookingTicket.addCustomerToFirst(customer);
	});
	const clear = useMemoizedFn(() => {
		bookingTicket === null || bookingTicket === void 0 || bookingTicket.clearCustomers();
	});
	const loadById = useMemoizedFn((id) => {
		if (!bookingTicket) return null;
		return bookingTicket.getCustomerById(id);
	});
	const value = useMemo(() => ({
		selected,
		list,
		pagination,
		hasMore,
		loading,
		loadingMore,
		searchParams,
		select,
		loadList,
		search,
		loadMore,
		changePage,
		addToFirst,
		clear,
		loadById
	}), [
		selected,
		list,
		pagination,
		hasMore,
		loading,
		loadingMore,
		searchParams,
		select,
		loadList,
		search,
		loadMore,
		changePage,
		addToFirst,
		clear,
		loadById
	]);
	return /* @__PURE__ */ React.createElement(SalesSdkCustomerContext.Provider, { value }, children);
};
//#endregion
export { SalesSdkCustomerContext, SalesSdkCustomerProvider };
