import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { request } from "../../utils/index.js";
import useActions from "./hooks/useActions.js";
import { defaultPaymentStatusKeys } from "../pisellSalesManagement/config/booking.js";
import { getBookingList, getOrderList } from "./serve.js";
import dayjs from "dayjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { PisellRecordBoard } from "@pisell/materials";
import { useRequest } from "ahooks";
import "./PisellSalesGrid.less";
//#region src/plus/pisellSalesGrid/PisellSalesGrid.tsx
const _excluded = ["filter"], _excluded2 = ["filter"];
/**
* 根据 currentPerspective 从 perspectives 中取当前 Perspective 配置，未找到时回退到第一项或空配置。
*/
function getCurrentPerspectiveConfig(perspectives, currentPerspective) {
	const found = perspectives.find((p) => p.key === currentPerspective);
	if (found) return found;
	if (perspectives.length > 0) return perspectives[0];
}
function getDefaultSearchParams(currentPerspective) {
	if (currentPerspective === "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"
	};
}
const SEARCH_PARAMS_STORAGE_PREFIX = "pisell_sales_grid_search_params_";
/**
* 序列化 searchParams，将 dayjs 对象转换为 ISO 字符串
*/
function serializeSearchParams(params) {
	return JSON.stringify(params, (key, value) => {
		if (dayjs.isDayjs(value)) return {
			__isDayjs: true,
			value: value.toISOString()
		};
		return value;
	});
}
/**
* 反序列化 searchParams，将 ISO 字符串还原为 dayjs 对象
*/
function deserializeSearchParams(str) {
	return JSON.parse(str, (key, value) => {
		if (value && typeof value === "object" && value.__isDayjs) return dayjs(value.value);
		return value;
	});
}
/**
* 从 sessionStorage 获取存储的 searchParams。
* 默认不还原 filter（仅还原 sort、keyword 等），调用方需与 getDefaultSearchParams 合并以得到默认筛选项。
*/
function getStoredSearchParams(id) {
	try {
		const stored = sessionStorage.getItem(`${SEARCH_PARAMS_STORAGE_PREFIX}${id}`);
		if (stored) {
			const normalized = deserializeSearchParams(stored);
			if (normalized && typeof normalized === "object") {
				const _ref = normalized, { filter: _f } = _ref;
				return _objectWithoutProperties(_ref, _excluded);
			}
			return normalized;
		}
	} catch (e) {
		console.warn("Failed to get stored search params:", e);
	}
	return null;
}
/**
* 将 searchParams 存储到 sessionStorage。
* 默认只存排序、关键词等，不存 filter；列显示隐藏由 RecordBoard 侧单独持久化。
*/
function saveSearchParams(id, params) {
	try {
		let toStore;
		{
			const { filter: _f } = params;
			toStore = _objectWithoutProperties(params, _excluded2);
		}
		sessionStorage.setItem(`${SEARCH_PARAMS_STORAGE_PREFIX}${id}`, serializeSearchParams(toStore));
	} catch (e) {
		console.warn("Failed to save search params:", e);
	}
}
/**
* 将 columnRenderers 按列 type 合并进 grid.columns（同 type 覆盖原有 render）。
*/
function mergeColumnRenderersIntoGrid(gridConfig, columnRenderers) {
	if (!(columnRenderers === null || columnRenderers === void 0 ? void 0 : columnRenderers.length) || !Array.isArray(gridConfig.columns)) return gridConfig;
	const byType = new Map(columnRenderers.map((r) => [r.type, r.render]));
	return _objectSpread2(_objectSpread2({}, gridConfig), {}, { columns: gridConfig.columns.map((col) => {
		const t = col === null || col === void 0 ? void 0 : col.type;
		if (t != null && byType.has(t)) {
			const renderCell = byType.get(t);
			return _objectSpread2(_objectSpread2({}, col), {}, { render: (value, record, index) => renderCell(value, record, index) });
		}
		return col;
	}) });
}
const PisellSalesGrid = (props) => {
	var _context$appHelper, _getBookingList$data, _getOrderList$data, _getBookingList$data2, _getOrderList$data2, _recordBoardGridProps, _recordBoardGridProps2, _currentConfig$childC3, _currentConfig$childC4, _currentConfig$childC5, _currentConfig$childC6, _currentConfig$childC7;
	const { perspectives, currentPerspective, className, style, extParams, __id, data: propsData, loading: propsLoading, total: propsTotal, pagination: propsPagination, onPageChange: propsOnPageChange, searchParams: propsSearchParams, onSearch: propsOnSearch, onReset: propsOnReset, selectedKeys: propsSelectedKeys, selectedRows: propsSelectedRows, onSelectionChange: propsOnSelectionChange, rowKey: propsRowKey, onRefresh: propsOnRefresh, refreshAsync: propsRefreshAsync, columnRenderers } = props;
	const context = useEngineContext();
	const utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	request.setRequest(utils === null || utils === void 0 ? void 0 : utils.request);
	const isControlledData = propsData !== void 0;
	const [selectedKeys, setSelectedKeys] = useState([]);
	const [selectedRows, setSelectedRows] = useState([]);
	const [pagination, setPagination] = useState({
		pageNumber: 1,
		pageSize: 50
	});
	const [searchParams, setSearchParams] = useState(() => {
		const defaultParams = getDefaultSearchParams(currentPerspective);
		if (__id) {
			const stored = getStoredSearchParams(__id);
			if (stored) return _objectSpread2(_objectSpread2({}, defaultParams), stored);
		}
		return defaultParams;
	});
	const onSelectionChange = useCallback((keys, rows) => {
		setSelectedKeys(keys);
		setSelectedRows(rows);
	}, []);
	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(currentPerspective));
		setPagination((prev) => _objectSpread2(_objectSpread2({}, prev), {}, { pageNumber: 1 }));
	}, [currentPerspective]);
	useEffect(() => {
		if (__id) saveSearchParams(__id, searchParams);
	}, [__id, searchParams]);
	useEffect(() => {
		document.body.id = "body";
	}, []);
	const _getBookingList = useRequest(getBookingList, { manual: true });
	const _getOrderList = useRequest(getOrderList, { manual: true });
	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
	]);
	const actions = useActions({
		onRefresh: useCallback(() => {
			if (currentPerspective === "monitor") {
				_getBookingList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
				return;
			}
			_getOrderList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
		}, [
			currentPerspective,
			requestParams,
			_getBookingList,
			_getOrderList
		]),
		onClearSelection: useCallback(() => {
			setSelectedKeys([]);
			setSelectedRows([]);
		}, [])
	});
	const batchActionConfig = useMemo(() => {
		return { actions };
	}, [actions]);
	useEffect(() => {
		if (isControlledData) return;
		if (currentPerspective === "monitor") _getBookingList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
		else _getOrderList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {}));
	}, [
		isControlledData,
		currentPerspective,
		requestParams,
		extParams === null || extParams === void 0 ? void 0 : extParams.list,
		_getBookingList,
		_getOrderList
	]);
	/**
	* 运行时上下文：根据当前 perspective 绑定对应的 refresh / refreshAsync，
	* 传入 perspective 的 getChildComponentProps 工厂函数。
	* 受控数据时优先使用父组件传入的 onRefresh / refreshAsync。
	*/
	const runtimeContext = useMemo(() => {
		if (isControlledData && propsOnRefresh) return {
			refresh: propsOnRefresh,
			refreshAsync: propsRefreshAsync !== null && propsRefreshAsync !== void 0 ? propsRefreshAsync : (() => Promise.resolve()),
			currentPerspective
		};
		return {
			refresh: currentPerspective === "monitor" ? () => _getBookingList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {})) : () => _getOrderList.run(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {})),
			refreshAsync: currentPerspective === "monitor" ? () => _getBookingList.runAsync(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {})) : () => _getOrderList.runAsync(_objectSpread2(_objectSpread2({}, requestParams), (extParams === null || extParams === void 0 ? void 0 : extParams.list) || {})),
			currentPerspective
		};
	}, [
		isControlledData,
		propsOnRefresh,
		propsRefreshAsync,
		currentPerspective,
		_getBookingList,
		_getOrderList,
		requestParams,
		extParams
	]);
	/**
	* 解析当前 perspective 配置：
	* - 若 perspective 提供了 getChildComponentProps 工厂，调用它并注入 runtimeContext；
	* - 否则回退到静态 childComponentProps（向后兼容）。
	*/
	const currentConfig = useMemo(() => {
		const raw = getCurrentPerspectiveConfig(perspectives, currentPerspective);
		if (!raw) return void 0;
		if (typeof raw.getChildComponentProps === "function") return _objectSpread2(_objectSpread2({}, raw), {}, { childComponentProps: raw.getChildComponentProps(runtimeContext) });
		return raw;
	}, [
		perspectives,
		currentPerspective,
		runtimeContext
	]);
	const recordBoardGridProps = useMemo(() => {
		var _currentConfig$childC, _currentConfig$childC2;
		const gridConfig = mergeColumnRenderersIntoGrid((_currentConfig$childC = currentConfig === null || currentConfig === void 0 || (_currentConfig$childC2 = currentConfig.childComponentProps) === null || _currentConfig$childC2 === void 0 ? void 0 : _currentConfig$childC2.grid) !== null && _currentConfig$childC !== void 0 ? _currentConfig$childC : {}, columnRenderers);
		const keys = isControlledData && propsSelectedKeys !== void 0 ? propsSelectedKeys : selectedKeys;
		const rows = isControlledData && propsSelectedRows !== void 0 ? propsSelectedRows : selectedRows;
		const onSel = isControlledData && propsOnSelectionChange ? propsOnSelectionChange : onSelectionChange;
		return _objectSpread2(_objectSpread2({}, gridConfig), {}, {
			selectedKeys: keys,
			selectedRows: rows,
			onSelectionChange: onSel
		});
	}, [
		currentConfig,
		isControlledData,
		propsSelectedKeys,
		propsSelectedRows,
		propsOnSelectionChange,
		selectedKeys,
		selectedRows,
		onSelectionChange,
		columnRenderers
	]);
	return /* @__PURE__ */ React.createElement("div", {
		className: `pisell-sales-grid ${className !== null && className !== void 0 ? className : ""}`.trim(),
		style: _objectSpread2({
			height: "100%",
			minHeight: 0,
			display: "flex",
			flexDirection: "column"
		}, style)
	}, /* @__PURE__ */ React.createElement(PisellRecordBoard, {
		key: currentPerspective,
		__id,
		layoutType: "grid",
		rowKey: propsRowKey !== null && propsRowKey !== void 0 ? propsRowKey : "id",
		data: isControlledData ? propsData !== null && propsData !== void 0 ? propsData : [] : currentPerspective === "monitor" ? ((_getBookingList$data = _getBookingList.data) === null || _getBookingList$data === void 0 ? void 0 : _getBookingList$data.list) || [] : ((_getOrderList$data = _getOrderList.data) === null || _getOrderList$data === void 0 ? void 0 : _getOrderList$data.list) || [],
		loading: isControlledData ? propsLoading !== null && propsLoading !== void 0 ? propsLoading : false : currentPerspective === "monitor" ? _getBookingList.loading : _getOrderList.loading,
		total: isControlledData ? propsTotal !== null && propsTotal !== void 0 ? propsTotal : 0 : currentPerspective === "monitor" ? ((_getBookingList$data2 = _getBookingList.data) === null || _getBookingList$data2 === void 0 ? void 0 : _getBookingList$data2.count) || 0 : ((_getOrderList$data2 = _getOrderList.data) === null || _getOrderList$data2 === void 0 ? void 0 : _getOrderList$data2.count) || 0,
		pagination: isControlledData && propsPagination ? propsPagination : pagination,
		onPageChange: isControlledData && propsOnPageChange ? propsOnPageChange : onPageChange,
		searchParams: isControlledData && propsSearchParams !== void 0 ? propsSearchParams : searchParams,
		onSearch: isControlledData && propsOnSearch ? propsOnSearch : onSearch,
		onReset: isControlledData && propsOnReset ? propsOnReset : onReset,
		fillHeight: (_recordBoardGridProps = (_recordBoardGridProps2 = recordBoardGridProps.scroll) === null || _recordBoardGridProps2 === void 0 ? void 0 : _recordBoardGridProps2.autoCalc) !== null && _recordBoardGridProps !== void 0 ? _recordBoardGridProps : true,
		grid: recordBoardGridProps,
		toolBar: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC3 = currentConfig.childComponentProps) === null || _currentConfig$childC3 === void 0 ? void 0 : _currentConfig$childC3.toolBar,
		search: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC4 = currentConfig.childComponentProps) === null || _currentConfig$childC4 === void 0 ? void 0 : _currentConfig$childC4.search,
		batchActionBar: _objectSpread2(_objectSpread2({}, batchActionConfig), currentConfig === null || currentConfig === void 0 || (_currentConfig$childC5 = currentConfig.childComponentProps) === null || _currentConfig$childC5 === void 0 ? void 0 : _currentConfig$childC5.batchActionBar),
		floorMap: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC6 = currentConfig.childComponentProps) === null || _currentConfig$childC6 === void 0 ? void 0 : _currentConfig$childC6.floorMap,
		defaultBodyView: currentConfig === null || currentConfig === void 0 || (_currentConfig$childC7 = currentConfig.childComponentProps) === null || _currentConfig$childC7 === void 0 ? void 0 : _currentConfig$childC7.defaultBodyView
	}, /* @__PURE__ */ React.createElement(PisellRecordBoard.ShellFrame, null, /* @__PURE__ */ React.createElement(PisellRecordBoard.GridLayout, null))));
};
PisellSalesGrid.displayName = "PisellSalesGrid";
//#endregion
export { PisellSalesGrid as default };
