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 useEngineContext from "../../../hooks/useEngineContext.js";
import { defaultPaymentStatusKeys } from "../config/booking.js";
import { formatBookingResult, getBookingList, getOrderList, unsubscribeBookingQuery, unsubscribeOrderQuery } 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/pisellSalesManagement/hooks/useSalesGridData.ts
function getDefaultSearchParams(perspective) {
	if (perspective === "monitor") return { filter: { values: {
		order_payment_status: defaultPaymentStatusKeys,
		booking_time_start_between: [dayjs().startOf("day"), dayjs().endOf("day")]
	} } };
	return {
		filter: { values: {
			payment_status: defaultPaymentStatusKeys,
			orderDate: [dayjs(), dayjs()]
		} },
		sort: "created_at:desc"
	};
}
/**
* 按视角解析表格行主键，保证 selectedKeys 始终为原始值而非整行对象。
* 与 formatBookingData 的 id 映射保持一致（monitor）。
*/
function resolveSalesGridRowKey(perspective, record) {
	var _record$id;
	if (perspective === "handle") return (record === null || record === void 0 ? void 0 : record.order_id) || (record === null || record === void 0 ? void 0 : record.id);
	return (_record$id = record === null || record === void 0 ? void 0 : record.id) !== null && _record$id !== void 0 ? _record$id : "";
}
/**
* Sales Management 内使用的列表数据 hook：统一发起订单/预订列表请求，
* 管理分页、筛选、多选状态，并返回传给 PisellSalesGrid 的受控 props，
* 使 Sales Grid 成为通用展示组件。
*/
function useSalesGridData(params) {
	var _engineContext$appHel, _getBookingList$data$, _getBookingList$data, _getOrderList$data$li, _getOrderList$data, _getBookingList$data$2, _getBookingList$data2, _getOrderList$data$co, _getOrderList$data2;
	const { perspective, extParams } = params;
	const engineContext = useEngineContext();
	const { action } = (engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils) || {};
	const [pagination, setPagination] = useState({
		pageNumber: 1,
		pageSize: 50
	});
	const [searchParams, setSearchParams] = useState(() => getDefaultSearchParams(perspective));
	const [selectedKeys, setSelectedKeys] = useState([]);
	const [selectedRows, setSelectedRows] = useState([]);
	const orderSubscriberIdRef = useRef(getUniqueId());
	const bookingSubscriberIdRef = useRef(getUniqueId());
	const orderMutateRef = useRef(null);
	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({
			keyword,
			sort
		}, filterVals), {}, {
			skip: pagination.pageNumber,
			num: pagination.pageSize
		});
	}, [
		searchParams,
		pagination.pageNumber,
		pagination.pageSize
	]);
	/**
	* 规范化订阅推送包结构，兼容 `res.data` / `res` 两种形态。
	*
	* @example
	* const payload = normalizeRealtimePayload({ data: { list: [] } });
	* console.log(Array.isArray(payload?.list));
	*/
	const normalizeRealtimePayload = useMemoizedFn((res) => {
		var _res$data;
		return (_res$data = res === null || res === void 0 ? void 0 : res.data) !== null && _res$data !== void 0 ? _res$data : res;
	});
	/**
	* 拉取订单列表并接入 osServer 订阅推送。
	*
	* @example
	* await fetchOrderList({ skip: 1, num: 50 });
	*/
	const fetchOrderList = useMemoizedFn(function() {
		var _ref = _asyncToGenerator(function* (query) {
			return getOrderList(query, {
				osServer: true,
				subscriberId: orderSubscriberIdRef.current,
				callback: (res) => {
					var _orderMutateRef$curre;
					const payload = normalizeRealtimePayload(res);
					if (payload == null || !Array.isArray(payload.list)) return;
					if (payload.list.length === 0) return;
					(_orderMutateRef$curre = orderMutateRef.current) === null || _orderMutateRef$curre === void 0 || _orderMutateRef$curre.call(orderMutateRef, payload);
				}
			});
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}());
	/**
	* 拉取 booking 列表并接入 osServer 订阅推送。
	* 注意：booking 数据来自本地 order 编排后的结果。
	*
	* @example
	* await fetchBookingList({ skip: 1, num: 50 });
	*/
	const fetchBookingList = useMemoizedFn(function() {
		var _ref2 = _asyncToGenerator(function* (query) {
			return getBookingList(query, {
				osServer: true,
				subscriberId: bookingSubscriberIdRef.current,
				callback: (res) => {
					var _bookingMutateRef$cur;
					const payload = normalizeRealtimePayload(res);
					if (payload == null || !Array.isArray(payload.list)) return;
					if (payload.list.length === 0) return;
					(_bookingMutateRef$cur = bookingMutateRef.current) === null || _bookingMutateRef$cur === void 0 || _bookingMutateRef$cur.call(bookingMutateRef, formatBookingResult(payload));
				}
			});
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}());
	const _getOrderList = useRequest(fetchOrderList, { manual: true });
	const _getBookingList = useRequest(fetchBookingList, { manual: true });
	orderMutateRef.current = _getOrderList.mutate;
	bookingMutateRef.current = _getBookingList.mutate;
	const runListParams = useMemo(() => _objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}), [requestParams, extParams === null || extParams === void 0 ? void 0 : extParams.list]);
	useEffect(() => {
		if (perspective === "monitor") _getBookingList.run(runListParams);
		else _getOrderList.run(runListParams);
		/**
		* 仅依赖视角与查询参数，避免 useRequest 返回对象引用变更导致 effect 循环触发请求。
		*
		* @example
		* // perspective / runListParams 不变时，此 effect 不会重复请求
		*/
	}, [perspective, runListParams]);
	useEffect(() => {
		setSearchParams(getDefaultSearchParams(perspective));
		setPagination((p) => _objectSpread2(_objectSpread2({}, p), {}, { pageNumber: 1 }));
		setSelectedKeys([]);
		setSelectedRows([]);
	}, [perspective]);
	const onPageChange = useCallback((pageNumber, pageSize) => {
		if (pageNumber < 1 || pageSize < 1) return;
		setPagination({
			pageNumber,
			pageSize
		});
	}, []);
	const onSearch = useCallback((params) => {
		setSearchParams(params || {});
		setPagination((prev) => _objectSpread2(_objectSpread2({}, prev), {}, { pageNumber: 1 }));
	}, []);
	const onReset = useCallback(() => {
		setSearchParams(getDefaultSearchParams(perspective));
		setPagination((prev) => _objectSpread2(_objectSpread2({}, prev), {}, { pageNumber: 1 }));
	}, [perspective]);
	const onSelectionChange = useCallback((keys, rows) => {
		setSelectedKeys(keys);
		setSelectedRows(rows);
	}, []);
	const onRefresh = useCallback((keys) => {
		if (perspective === "monitor") _getBookingList.run(runListParams);
		else _getOrderList.run(runListParams);
		if (keys && keys.length > 0) action({
			type: "webpos.updateLocalOrdersApi",
			data: { order_ids: keys }
		});
	}, [
		perspective,
		runListParams,
		_getBookingList,
		_getOrderList
	]);
	const refreshAsync = useCallback(() => {
		if (perspective === "monitor") return _getBookingList.runAsync(runListParams);
		return _getOrderList.runAsync(runListParams);
	}, [
		perspective,
		runListParams,
		_getBookingList,
		_getOrderList
	]);
	/**
	* 视角切换时，主动清理另一条订阅，避免离开该视角后仍接收推送。
	*
	* @example
	* // perspective = 'monitor' 时会清理 order 订阅
	* // perspective = 'handle' 时会清理 booking 订阅
	*/
	useEffect(() => {
		if (perspective === "monitor") {
			unsubscribeOrderQuery(orderSubscriberIdRef.current);
			return;
		}
		unsubscribeBookingQuery(bookingSubscriberIdRef.current);
	}, [perspective]);
	/**
	* 卸载时清理全部订阅，防止 subscriber 泄漏。
	*
	* @example
	* // 组件卸载会自动执行，无需手动调用
	*/
	useEffect(() => {
		return () => {
			unsubscribeOrderQuery(orderSubscriberIdRef.current);
			unsubscribeBookingQuery(bookingSubscriberIdRef.current);
		};
	}, []);
	return {
		data: perspective === "monitor" ? (_getBookingList$data$ = (_getBookingList$data = _getBookingList.data) === null || _getBookingList$data === void 0 ? void 0 : _getBookingList$data.list) !== null && _getBookingList$data$ !== void 0 ? _getBookingList$data$ : [] : (_getOrderList$data$li = (_getOrderList$data = _getOrderList.data) === null || _getOrderList$data === void 0 ? void 0 : _getOrderList$data.list) !== null && _getOrderList$data$li !== void 0 ? _getOrderList$data$li : [],
		loading: perspective === "monitor" ? _getBookingList.loading : _getOrderList.loading,
		total: perspective === "monitor" ? (_getBookingList$data$2 = (_getBookingList$data2 = _getBookingList.data) === null || _getBookingList$data2 === void 0 ? void 0 : _getBookingList$data2.count) !== null && _getBookingList$data$2 !== void 0 ? _getBookingList$data$2 : 0 : (_getOrderList$data$co = (_getOrderList$data2 = _getOrderList.data) === null || _getOrderList$data2 === void 0 ? void 0 : _getOrderList$data2.count) !== null && _getOrderList$data$co !== void 0 ? _getOrderList$data$co : 0,
		pagination,
		onPageChange,
		searchParams,
		onSearch,
		onReset,
		selectedKeys,
		selectedRows,
		onSelectionChange,
		rowKey: useMemo(() => (record) => resolveSalesGridRowKey(perspective, record), [perspective]),
		onRefresh,
		refreshAsync
	};
}
//#endregion
export { useSalesGridData };
