import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { getSettingKeyArrByMode, getTableSettingByCurrentViewMode, getTableSettingFromLocalStorage, mergeColumnSetting, mergeFilterSetting, setFormValuesToLocalStorage, setTableSettingToLocalStorage } from "../Table/utils.js";
import React, { useMemo } from "react";
import { useMemoizedFn } from "ahooks";
//#region src/components/table/hooks/useTableSetting.ts
const useTableSetting = (params) => {
	var _context$appHelper;
	const { tableId, filter, columnSetting, dataSourceGroup, sort, view, currentViewMode, columns: propsColumns, gallery, currentSettingHash, exportImport, localSettings } = params;
	const { isTerminal, interaction } = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const columnsMap = useMemo(() => {
		return new Map(propsColumns.map((item) => [item.key, item]));
	}, [propsColumns]);
	const columns = useMemo(() => {
		if (currentViewMode === "grid") return propsColumns;
		else if (currentViewMode === "gallery") {
			var _gallery$content;
			return ((gallery === null || gallery === void 0 || (_gallery$content = gallery.content) === null || _gallery$content === void 0 ? void 0 : _gallery$content.fields) || []).filter((item) => item.show).map((item) => columnsMap.get(item.columnKey)).filter(Boolean);
		}
		return propsColumns;
	}, [
		propsColumns,
		currentViewMode,
		gallery,
		columnsMap
	]);
	const { list, quickFilterMaxLength, sortButtonShow } = filter || {};
	const defaultGalleryCoverSetting = useMemo(() => {
		var _gallery$cover, _columns$find;
		return {
			coverObjectFit: gallery === null || gallery === void 0 || (_gallery$cover = gallery.cover) === null || _gallery$cover === void 0 ? void 0 : _gallery$cover.objectFit,
			coverField: (_columns$find = columns.find((column) => {
				var _gallery$cover2;
				return column.key === (gallery === null || gallery === void 0 || (_gallery$cover2 = gallery.cover) === null || _gallery$cover2 === void 0 || (_gallery$cover2 = _gallery$cover2.fields) === null || _gallery$cover2 === void 0 ? void 0 : _gallery$cover2[0]);
			})) === null || _columns$find === void 0 ? void 0 : _columns$find.dataIndex,
			compactMode: "default",
			isShowLabel: true
		};
	}, [gallery, columns]);
	/**
	* 获取需要本地存储的 keyArr
	*/
	const localStorageSettingKeyArr = useMemo(() => {
		var _localSettings$scope;
		const keys = getSettingKeyArrByMode({
			filter,
			columnSetting,
			dataSourceGroup,
			sort,
			mode: "localStorage",
			currentViewMode
		});
		if ((localSettings === null || localSettings === void 0 ? void 0 : localSettings.enable) && ((_localSettings$scope = localSettings.scope) === null || _localSettings$scope === void 0 ? void 0 : _localSettings$scope.includes("filters"))) {
			if (!keys.includes("filters")) keys.push("filters");
		}
		return keys;
	}, [
		tableId,
		filter,
		columnSetting,
		dataSourceGroup,
		sort,
		currentViewMode
	]);
	const defaultKeyArr = useMemo(() => {
		return getSettingKeyArrByMode({
			filter,
			columnSetting,
			dataSourceGroup,
			sort,
			mode: "",
			currentViewMode
		});
	}, [
		tableId,
		filter,
		columnSetting,
		dataSourceGroup,
		sort,
		view,
		currentViewMode
	]);
	/**
	* 获取本地存储的 tableSetting 用于刷新后回显
	*/
	const tableLocalSetting = useMemo(() => {
		const setting = {};
		/** 当前组件下的所有配置 */
		const allSetting = getTableSettingFromLocalStorage(tableId);
		/** 当前视图下的配置 */
		const currentViewModeSetting = getTableSettingByCurrentViewMode(tableId, currentViewMode);
		const mergedSetting = _objectSpread2(_objectSpread2({}, allSetting), currentViewModeSetting);
		localStorageSettingKeyArr.forEach((item) => {
			if (item === "view_mode")
 /** 多视图模式当前视图从本地存储取， 单视图模式直接取默认视图 */
			setting[item] = view.multiple ? (mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]) || view.defaultViewMode : view.defaultViewMode;
			else if (item === "filter_setting") setting[item] = mergeFilterSetting({
				list,
				quickFilterMaxLength,
				tableId,
				sortButtonShow,
				currentViewMode
			});
			else if (item === "column_setting") setting[item] = mergeColumnSetting({
				columns,
				tableId,
				currentViewMode
			});
			else if (item === "gallery_setting") {
				var _mergedSetting$item, _mergedSetting$item2, _mergedSetting$item3, _mergedSetting$item$i, _mergedSetting$item4;
				setting[item] = _objectSpread2(_objectSpread2({}, mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]), {}, {
					coverObjectFit: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item = mergedSetting[item]) === null || _mergedSetting$item === void 0 ? void 0 : _mergedSetting$item.coverObjectFit) || defaultGalleryCoverSetting.coverObjectFit,
					coverField: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item2 = mergedSetting[item]) === null || _mergedSetting$item2 === void 0 ? void 0 : _mergedSetting$item2.coverField) || defaultGalleryCoverSetting.coverField,
					compactMode: (mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item3 = mergedSetting[item]) === null || _mergedSetting$item3 === void 0 ? void 0 : _mergedSetting$item3.compactMode) || defaultGalleryCoverSetting.compactMode,
					isShowLabel: (_mergedSetting$item$i = mergedSetting === null || mergedSetting === void 0 || (_mergedSetting$item4 = mergedSetting[item]) === null || _mergedSetting$item4 === void 0 ? void 0 : _mergedSetting$item4.isShowLabel) !== null && _mergedSetting$item$i !== void 0 ? _mergedSetting$item$i : defaultGalleryCoverSetting.isShowLabel
				});
			} else if (item === "filters") setting[item] = (mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item]) || {};
			else setting[item] = mergedSetting === null || mergedSetting === void 0 ? void 0 : mergedSetting[item];
		});
		return setting;
	}, [
		localStorageSettingKeyArr,
		tableId,
		view,
		list,
		quickFilterMaxLength,
		tableId,
		sortButtonShow,
		columns,
		currentViewMode,
		gallery,
		defaultGalleryCoverSetting
	]);
	const defaultTableSetting = useMemo(() => {
		const setting = {};
		defaultKeyArr.forEach((item) => {
			if (item === "column_setting") setting[item] = mergeColumnSetting({
				columns,
				tableId,
				currentViewMode
			});
			else if (item === "filter_setting") setting[item] = mergeFilterSetting({
				list,
				quickFilterMaxLength,
				tableId: "",
				sortButtonShow,
				currentViewMode
			});
			else if (item === "gallery_setting") setting[item] = {
				coverObjectFit: defaultGalleryCoverSetting.coverObjectFit,
				coverField: defaultGalleryCoverSetting.coverField,
				compactMode: defaultGalleryCoverSetting.compactMode,
				isShowLabel: defaultGalleryCoverSetting.isShowLabel
			};
		});
		return setting;
	}, [
		defaultKeyArr,
		columns,
		defaultGalleryCoverSetting,
		columns,
		tableId,
		currentViewMode,
		list,
		quickFilterMaxLength,
		sortButtonShow
	]);
	/**
	* 更新 tableSetting
	* @param values
	*/
	const setTableSetting = useMemoizedFn((values) => {
		var _localSettings$scope2;
		let valuesForSave = values;
		if ((localSettings === null || localSettings === void 0 ? void 0 : localSettings.enable) && ((_localSettings$scope2 = localSettings.scope) === null || _localSettings$scope2 === void 0 ? void 0 : _localSettings$scope2.includes("filters"))) {
			const excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
			const filterValue = {};
			((filter === null || filter === void 0 ? void 0 : filter.list) || []).forEach((item) => {
				const rawName = item === null || item === void 0 ? void 0 : item.name;
				if (!rawName) return;
				const key = Array.isArray(rawName) ? rawName.join(",") : String(rawName);
				if (excluded.has(key)) return;
				if (values.hasOwnProperty(key)) filterValue[key] = values[key];
			});
			valuesForSave = _objectSpread2(_objectSpread2({}, values), {}, { filters: filterValue });
		}
		setFormValuesToLocalStorage({
			tableId,
			allValues: valuesForSave,
			keys: localStorageSettingKeyArr,
			currentViewMode,
			currentSettingHash
		});
	});
	const tableSetting = useMemo(() => {
		var _localSettings$scope3;
		const merged = _objectSpread2(_objectSpread2({}, tableLocalSetting), defaultTableSetting);
		if ((localSettings === null || localSettings === void 0 ? void 0 : localSettings.enable) && ((_localSettings$scope3 = localSettings.scope) === null || _localSettings$scope3 === void 0 ? void 0 : _localSettings$scope3.includes("filters"))) {
			const persistedFilter = tableLocalSetting === null || tableLocalSetting === void 0 ? void 0 : tableLocalSetting.filters;
			if (persistedFilter && typeof persistedFilter === "object") return _objectSpread2(_objectSpread2({}, merged), persistedFilter);
		}
		return merged;
	}, [tableLocalSetting, defaultTableSetting]);
	/**
	* 当刷新后获得新的 localSettings（scope 或 excludedFilterFields 变化）时，
	* 根据最新规则调整已存储的 filters
	*/
	useMemo(() => {
		try {
			var _localSettings$scope4;
			if (!tableId) return;
			const current = getTableSettingByCurrentViewMode(tableId, currentViewMode) || {};
			const persistedFilters = (current === null || current === void 0 ? void 0 : current.filters) || {};
			let nextFilters = _objectSpread2({}, persistedFilters);
			let shouldUpdate = false;
			if (!!!((localSettings === null || localSettings === void 0 ? void 0 : localSettings.enable) && ((_localSettings$scope4 = localSettings.scope) === null || _localSettings$scope4 === void 0 ? void 0 : _localSettings$scope4.includes("filters")))) {
				if (Object.keys(persistedFilters || {}).length > 0) {
					nextFilters = {};
					shouldUpdate = true;
				}
			} else {
				let names = /* @__PURE__ */ new Set();
				if (React.isValidElement(filter) || React.isValidElement(filter === null || filter === void 0 ? void 0 : filter.dom)) names = new Set(((filter === null || filter === void 0 ? void 0 : filter.items) || []).filter((item) => !item.isHidden).map((item) => {
					const rawName = item === null || item === void 0 ? void 0 : item.value;
					if (!rawName) return void 0;
					return Array.isArray(rawName) ? rawName.join(",") : String(rawName);
				}));
				else names = new Set(((filter === null || filter === void 0 ? void 0 : filter.list) || []).map((item) => {
					const rawName = item === null || item === void 0 ? void 0 : item.name;
					if (!rawName) return void 0;
					return Array.isArray(rawName) ? rawName.join(",") : String(rawName);
				}).filter(Boolean));
				const flatPersistedFilters = {};
				Object.entries(persistedFilters || {}).forEach(([key, value]) => {
					if (typeof value === "object" && value !== null && !Array.isArray(value)) Object.entries(value).forEach(([subKey, subValue]) => {
						flatPersistedFilters[`${key},${subKey}`] = subValue;
					});
					else flatPersistedFilters[key] = value;
				});
				const excluded = new Set((localSettings === null || localSettings === void 0 ? void 0 : localSettings.excludedFilterFields) || []);
				const allowed = new Set(Array.from(names).filter((k) => !excluded.has(k)));
				const filtered = {};
				Object.keys(flatPersistedFilters || {}).forEach((k) => {
					if (allowed.has(k)) {
						var _k$split, _k$split2;
						const parts = (_k$split = k === null || k === void 0 || (_k$split2 = k.split) === null || _k$split2 === void 0 ? void 0 : _k$split2.call(k, ",")) !== null && _k$split !== void 0 ? _k$split : [];
						const topKey = parts[0];
						const subKey = parts[1];
						if (subKey) {
							if (!filtered[topKey]) filtered[topKey] = {};
							filtered[topKey][subKey] = flatPersistedFilters[k];
						} else filtered[topKey] = flatPersistedFilters[k];
					} else shouldUpdate = true;
				});
				if (Object.keys(filtered).length !== Object.keys(persistedFilters || {}).length) shouldUpdate = true;
				nextFilters = filtered;
			}
			if (shouldUpdate) setTableSettingToLocalStorage({
				tableId,
				tableSettingObj: { filters: nextFilters },
				currentViewMode,
				currentSettingHash
			});
		} catch (e) {}
	}, []);
	return {
		setTableSetting,
		tableSetting
	};
};
//#endregion
export { useTableSetting as default };
