import { filterDataSource, groupDataSource, sortDataSource, stringify } from "../Table/utils.js";
import { useMemo } from "react";
import { isArr } from "@pisell/utils";
import { Form } from "antd";
//#region src/components/table/hooks/useTransDataSource.ts
const defaultObj = {};
const useTransDataSource = (params) => {
	const { form, localPagination, dataSource: pDataSource, rowKey, filter, currentView } = params;
	const sort = Form.useWatch("order_by", {
		form,
		preserve: true
	});
	const group = Form.useWatch("group_by", {
		form,
		preserve: true
	});
	const filters = Form.useWatch("filters", {
		form,
		preserve: true
	}) || defaultObj;
	/**
	* 根据排序字符串对对象进行排序
	* @param sort 排序字符串，格式为"key:value:type"，例如"age:asc:number"
	* @returns 排序后的对象
	*/
	const sortObj = useMemo(() => {
		if (!sort) return;
		const [key, value, type] = sort.split(":");
		return {
			sortKey: key,
			sortValue: value,
			sortType: type
		};
	}, [sort]);
	const groupDetail = useMemo(() => {
		if (isArr(group) && group.length) return group;
	}, [group]);
	/**
	* 过滤本地筛选数组
	* @returns 返回过滤后的本地筛选数组
	*/
	const filterLocalArr = useMemo(() => {
		if (!(filter === null || filter === void 0 ? void 0 : filter.show) || !(filter === null || filter === void 0 ? void 0 : filter.list)) return [];
		return filter === null || filter === void 0 ? void 0 : filter.list.filter((item) => item.localFilter);
	}, [stringify(filter)]);
	return useMemo(() => {
		if (!localPagination) return pDataSource;
		let newDataSource = pDataSource;
		if (filterLocalArr.length) newDataSource = filterDataSource(newDataSource, filters, filterLocalArr);
		if (sortObj) newDataSource = sortDataSource(newDataSource, sortObj);
		if (groupDetail && currentView === "table") newDataSource = groupDataSource(newDataSource, groupDetail, rowKey);
		return newDataSource;
	}, [
		pDataSource,
		localPagination,
		sortObj,
		groupDetail,
		filterLocalArr,
		filters,
		currentView
	]);
};
//#endregion
export { useTransDataSource as default };
