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 { getValueByKeys } from "./fields/utils/index.js";
import { fieldMaps } from "./fields/index.js";
import React from "react";
import { isBoolean, isFunction, isJson, isNumber, isString } from "@pisell/utils";
import dayjs from "dayjs";
import md5 from "crypto-js/md5";
import enc from "crypto-js/enc-hex";
//#region src/components/table/Table/utils.ts
const _excluded = ["view_mode"];
const tableKeyPrefix = "table-setting";
const getHash = (obj) => {
	return md5(JSON.stringify(obj)).toString(enc.Hex);
};
const transColumnsMap = (columns) => {
	return columns.reduce((p, c) => {
		return _objectSpread2(_objectSpread2({}, p), {}, { [c.dataIndex]: c });
	}, {});
};
const filterFnMap = {
	text: (value, record, dataIndex) => {
		var _record$dataIndex;
		return (_record$dataIndex = record[dataIndex]) === null || _record$dataIndex === void 0 ? void 0 : _record$dataIndex.toString().toLowerCase().includes(value.toLowerCase());
	},
	number: (value, record, dataIndex) => record[dataIndex] >= value.min && record[dataIndex] <= value.max,
	filters: (value, record, dataIndex) => {
		var _record$dataIndex2;
		return value.map((item) => item.toLowerCase()).includes((_record$dataIndex2 = record[dataIndex]) === null || _record$dataIndex2 === void 0 ? void 0 : _record$dataIndex2.toString().toLowerCase());
	}
};
const sorter = (item) => (a, b) => {
	if (item.field_type === "date") return dayjs(a[item.dataIndex]).valueOf() - dayjs(b[item.dataIndex]).valueOf();
	return a[item.dataIndex] - b[item.dataIndex];
};
const calcFilterSort = ({ dataSource, filter, sort, columns }) => {
	const columnMap = transColumnsMap(columns);
	const newDataSource = dataSource.filter((item) => {
		return Object.keys(filter || {}).every((f) => {
			var _filter$f, _columnDetail$filters;
			if (!((_filter$f = filter[f]) === null || _filter$f === void 0 ? void 0 : _filter$f.length)) return true;
			const columnDetail = columnMap[f];
			if (((_columnDetail$filters = columnDetail.filters) === null || _columnDetail$filters === void 0 ? void 0 : _columnDetail$filters.length) > 0) return filterFnMap["filters"](filter[f][0], item, columnDetail.dataIndex);
			if (columnDetail.field_type === "text") return filterFnMap[columnDetail.field_type](filter[f][0], item, columnDetail.dataIndex);
			else if (columnDetail.field_type === "number") return filterFnMap[columnDetail.field_type](filter[f][0], item, columnDetail.dataIndex);
			return true;
		});
	});
	if (sort === null || sort === void 0 ? void 0 : sort.order) newDataSource.sort((a, b) => {
		const { order } = sort;
		if (order === "descend") return sorter(sort.column)(b, a);
		if (order === "ascend") return sorter(sort.column)(a, b);
	});
	return newDataSource;
};
/**
* 从本地存储获取指定表的列信息
* @param tableId 表的标识符
* @returns 返回包含列信息的对象，若未找到则返回空对象
*/
const getColumnsFromLocalStorage = (tableId, currentViewMode) => {
	if (!tableId) return {};
	const { column_setting } = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
	const col = column_setting;
	if (col) return col.reduce((p, c) => {
		p[c.key] = c;
		return p;
	}, {});
	return {};
};
/**
* 合并列设置
* @param defaultColumns 默认列设置
* @param tableId 表ID
* @returns 合并后的列设置
*/
const mergeColumnSetting = ({ columns, tableId, currentViewMode }) => {
	if (!tableId) return columns.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { isShow: true }));
	const colKeyMap = getColumnsFromLocalStorage(tableId, currentViewMode);
	const newColumns = columns.map((item, index) => {
		const col = colKeyMap[item.key];
		let sortIndex = index;
		if (isBoolean(item.fixed) && item.fixed || item.fixed === "left") sortIndex = -99;
		else if (item.fixed === "right") sortIndex = 9999;
		if (col) {
			var _col$width, _col$isShow;
			sortIndex = [
				true,
				false,
				"left",
				"right"
			].includes(item.fixed) ? sortIndex : col.sortIndex;
			return _objectSpread2(_objectSpread2({}, item), {}, {
				width: (_col$width = col.width) !== null && _col$width !== void 0 ? _col$width : item.width,
				isShow: (_col$isShow = col.isShow) !== null && _col$isShow !== void 0 ? _col$isShow : true,
				sortIndex
			});
		}
		return _objectSpread2(_objectSpread2({}, item), {}, {
			isShow: true,
			sortIndex
		});
	});
	newColumns.sort((a, b) => a.sortIndex - b.sortIndex);
	return newColumns;
};
/**
* 对数据源进行排序
* @param dataSource 数据源数组
* @param sortObj 排序对象，包含排序的键、值和类型
* @returns 排序后的数据源数组
*/
const sortDataSource = (dataSource, sortObj) => {
	const { sortKey, sortValue, sortType } = sortObj;
	const newDataSource = [...dataSource];
	const sorter = (sortKey, sortType) => {
		return (a, b) => {
			const aValue = getValueByKeys(a, sortKey.split(","));
			const bValue = getValueByKeys(b, sortKey.split(","));
			if (sortType === "string") {
				if (sortValue === "asc") return aValue === null || aValue === void 0 ? void 0 : aValue.localeCompare(bValue);
				return bValue === null || bValue === void 0 ? void 0 : bValue.localeCompare(aValue);
			}
			if (sortType === "date") {
				if (sortValue !== "asc") return new Date(bValue).getTime() - new Date(aValue).getTime();
				return new Date(aValue).getTime() - new Date(bValue).getTime();
			}
			if (sortType === "number") {
				if (sortValue === "asc") return (Number(aValue) || 0) - (Number(bValue) || 0);
				return (Number(bValue) || 0) - (Number(aValue) || 0);
			}
		};
	};
	newDataSource.sort(sorter(sortKey, sortType));
	return newDataSource;
};
/**
* 根据行键获取 ID
* @param item 记录对象
* @param rowKey 行键，可以是字符串或函数
* @returns 返回 ID
*/
const getIdByRowKey = (item, rowKey) => {
	if (isString(rowKey)) return item[rowKey];
	else if (isFunction(rowKey)) return item[rowKey(item)];
	return item[rowKey || "id"];
};
/**
* 根据分组条件对数据源进行分组
* @param dataSource 数据源
* @param group 分组条件
* @param rowKey 行键生成函数或字符串
* @returns 返回分组后的数据源
*/
const groupDataSource = (dataSource, group, rowKey) => {
	const groupField = group[0].field;
	if (!groupField) return dataSource;
	const dataIndex = groupField.split(",");
	let newDataSource = [...dataSource];
	newDataSource = Object.values(newDataSource.reduce((pre, cur, index) => {
		const groupValue = getValueByKeys(cur, dataIndex);
		if (!pre[groupValue]) pre[groupValue] = {
			__table_group_field: groupField,
			__is_group: true,
			children: [cur]
		};
		else pre[groupValue].children.push(cur);
		pre[groupValue].__rowKey = `group-${pre[groupValue].children.map((item) => getIdByRowKey(item, rowKey)).join("-")}`;
		pre[groupValue].id = pre[groupValue].__rowKey;
		return _objectSpread2({}, pre);
	}, {}));
	return newDataSource;
};
/**
* 将表格设置保存到本地存储
* @param tableId 表格id
* @param tableSettingObj 表格设置对象
*/
const setTableSettingToLocalStorage = ({ tableId, tableSettingObj, currentViewMode, currentSettingHash }) => {
	if (!tableId) return;
	const originData = localStorage.getItem(getTableKey(tableId));
	let newData = {};
	if (originData && isJson(originData)) newData = _objectSpread2({}, JSON.parse(originData) || {});
	const { view_mode } = tableSettingObj, itemSetting = _objectWithoutProperties(tableSettingObj, _excluded);
	newData = _objectSpread2(_objectSpread2({}, newData), {}, {
		view_mode: view_mode || newData.view_mode,
		currentSettingHash,
		[currentViewMode]: _objectSpread2(_objectSpread2({}, newData[currentViewMode] || {}), itemSetting)
	});
	localStorage.setItem(getTableKey(tableId), JSON.stringify(newData));
	return {
		key: getTableKey(tableId),
		value: newData
	};
};
const clearTableSettingToLocalStorage = (tableId) => {
	if (!tableId) return;
	localStorage.removeItem(getTableKey(tableId));
};
/**
* 从本地存储中获取表格设置, 全部配置
* @param tableId 表格ID
* @returns 表格设置对象
*/
const getTableSettingFromLocalStorage = (tableId) => {
	if (!tableId) return {};
	const originData = localStorage.getItem(getTableKey(tableId));
	if (originData && isJson(originData)) return JSON.parse(originData);
	return {};
};
/**
* 从LocalStorage读取表当前视图模式
* @param tableId
*/
const getCurrentViewModeFromLocalStorage = (tableId) => {
	return getTableSettingFromLocalStorage(tableId)["view_mode"];
};
/**
* 根据视图模式获取配置
* @param tableId
* @param currentViewMode
*/
const getTableSettingByCurrentViewMode = (tableId, currentViewMode) => {
	return getTableSettingFromLocalStorage(tableId)[currentViewMode];
};
/**
* 将表单值保存到本地存储中
* @param tableId 表单ID
* @param allValues 表单所有值
* @param keys 存储的键名
*/
const setFormValuesToLocalStorage = ({ tableId, allValues, keys, currentViewMode, currentSettingHash }) => {
	if (!tableId) return;
	let obj = {};
	keys === null || keys === void 0 || keys.forEach((key) => {
		obj[key] = allValues === null || allValues === void 0 ? void 0 : allValues[key];
	});
	return setTableSettingToLocalStorage({
		tableId,
		tableSettingObj: obj,
		currentViewMode,
		currentSettingHash
	});
};
/**
* 获取表格键值
* @param tableId 表格ID
* @returns 返回格式化后的表格键值
*/
const getTableKey = (tableId) => {
	if (typeof window === "undefined" || typeof window.location === "undefined") return `${tableKeyPrefix}-${tableId}`;
	const { pathname, search } = window.location;
	let appendPath = pathname || "/";
	let memoryKey = "";
	try {
		const mk = new URLSearchParams(search || "").get("memory_key");
		if (mk && mk.trim() !== "") memoryKey = mk.trim();
	} catch (e) {}
	return `${tableKeyPrefix}-${tableId}-${memoryKey ? `${appendPath}#${memoryKey}` : appendPath}`;
};
/**
* 合并筛选设置
* @param list 列表数据
* @param quickFilterMaxLength 快速筛选最大长度
* @param tableId 表ID
* @returns 返回合并后的筛选设置
*/
const mergeFilterSetting = ({ list, quickFilterMaxLength, tableId, sortButtonShow, currentViewMode }) => {
	if (!sortButtonShow) return {
		quickFilter: [],
		otherFilter: [],
		notSortFilter: list
	};
	const { filter_setting } = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
	const { quickFilter, otherFilter } = filter_setting || {};
	const notSortList = [];
	const sortList = [];
	list.forEach((item) => {
		if (item.sort) sortList.push(item);
		else notSortList.push(item);
	});
	if (!tableId || !quickFilter || !otherFilter) {
		var _sortList$slice, _sortList$slice2;
		return {
			quickFilter: (sortList === null || sortList === void 0 || (_sortList$slice = sortList.slice) === null || _sortList$slice === void 0 ? void 0 : _sortList$slice.call(sortList, 0, quickFilterMaxLength)) || [],
			otherFilter: (sortList === null || sortList === void 0 || (_sortList$slice2 = sortList.slice) === null || _sortList$slice2 === void 0 ? void 0 : _sortList$slice2.call(sortList, quickFilterMaxLength)) || [],
			notSortFilter: notSortList
		};
	}
	const quickFilterMap = new Map(quickFilter.map((item, index) => [item.key, _objectSpread2(_objectSpread2({}, item), {}, { sortIndex: index })]));
	const otherFilterMap = new Map(otherFilter.map((item, index) => [item.key, _objectSpread2(_objectSpread2({}, item), {}, { sortIndex: index })]));
	let newQuickFilter = Array.from({ length: 200 });
	let newOtherFilter = Array.from({ length: 200 });
	let notSortFilter = [];
	list.forEach((item) => {
		if (!item.sort) notSortFilter.push(item);
		else if (quickFilterMap.has(item.key)) if (isNumber(quickFilterMap.get(item.key).sortIndex)) newQuickFilter[quickFilterMap.get(item.key).sortIndex] = item;
		else newQuickFilter.push(item);
		else if (otherFilterMap.has(item.key)) if (isNumber(otherFilterMap.get(item.key).sortIndex)) newOtherFilter[otherFilterMap.get(item.key).sortIndex] = item;
		else newOtherFilter.push(item);
		else newOtherFilter.push(item);
	});
	return {
		quickFilter: newQuickFilter.filter(Boolean),
		otherFilter: newOtherFilter.filter(Boolean),
		notSortFilter
	};
};
/**
* 过滤数据源
* @param dataSource 数据源
* @param filters 过滤条件
* @param filterLocalArr 本地过滤项
* @returns 过滤后的数据源
*/
const filterDataSource = (dataSource, filters, filterLocalArr) => {
	const fnArr = filterLocalArr.map((filterItem) => {
		if (!filters[filterItem.name]) return null;
		const { filterFn } = fieldMaps[filterItem.type];
		if (!isFunction(filterFn)) return null;
		return (item) => {
			try {
				return filterFn({
					value: filters[filterItem.name],
					item,
					key: filterItem.name
				});
			} catch (error) {
				return false;
			}
		};
	}).filter(Boolean);
	return dataSource.filter((item) => {
		return !fnArr.some((fn) => {
			return !(fn === null || fn === void 0 ? void 0 : fn(item));
		});
	});
};
/**
* 根据模式获取设置键数组
* @param filter 筛选器
* @param columnSetting 列设置
* @param dataSourceGroup 数据源分组
* @param sort 排序
* @param mode 模式，可选值为 "localStorage" 或 "remote"
* @returns 返回设置键数组
*/
const getSettingKeyArrByMode = ({ filter, columnSetting, dataSourceGroup, sort, mode, currentViewMode }) => {
	const keyArr = [];
	if ((filter === null || filter === void 0 ? void 0 : filter.show) && ((filter === null || filter === void 0 ? void 0 : filter.storageMode) || "") == mode) keyArr.push("filter_setting");
	if (((columnSetting === null || columnSetting === void 0 ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "gallery") keyArr.push("gallery_setting", "column_setting");
	if (((columnSetting === null || columnSetting === void 0 ? void 0 : columnSetting.storageMode) || "") == mode && currentViewMode === "grid") keyArr.push("column_setting");
	if ((dataSourceGroup === null || dataSourceGroup === void 0 ? void 0 : dataSourceGroup.show) && ((dataSourceGroup === null || dataSourceGroup === void 0 ? void 0 : dataSourceGroup.storageMode) || "") == mode) keyArr.push("group_by");
	if ((sort === null || sort === void 0 ? void 0 : sort.show) && sort.storageMode == mode) keyArr.push("order_by");
	keyArr.push("view_mode");
	return keyArr;
};
const omit = (obj, keys) => {
	const shallowCopy = Object.assign({}, obj);
	for (let i = 0; i < keys.length; i += 1) {
		const key = keys[i];
		delete shallowCopy[key];
	}
	return shallowCopy;
};
const stringify = (obj) => {
	return JSON.stringify(obj, (key, value) => {
		if (isFunction(value)) return value.toString();
		if (React.isValidElement(value)) return value.toString();
		return value;
	});
};
//#endregion
export { calcFilterSort, clearTableSettingToLocalStorage, filterDataSource, getCurrentViewModeFromLocalStorage, getHash, getIdByRowKey, getSettingKeyArrByMode, getTableSettingByCurrentViewMode, getTableSettingFromLocalStorage, groupDataSource, mergeColumnSetting, mergeFilterSetting, omit, setFormValuesToLocalStorage, setTableSettingToLocalStorage, sortDataSource, stringify };
