import { getText } from "../../../locales/index.js";
import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import PisellSingleLineText_default from "../../pisellSingleLineText/PisellSingleLineText.js";
import "../../pisellSingleLineText/index.js";
import PisellLongText_default from "../../pisellLongText/PisellLongText.js";
import "../../pisellLongText/index.js";
import MemoizedPisellNumber from "../../pisellNumber/PisellNumber.js";
import "../../pisellNumber/index.js";
import MemoizedPisellCurrency from "../../pisellCurrency/PisellCurrency.js";
import "../../pisellCurrency/index.js";
import MemoizedPisellPercent from "../../pisellPercent/PisellPercent.js";
import "../../pisellPercent/index.js";
import PisellPhone_default from "../../pisellPhone/PisellPhone.js";
import "../../pisellPhone/index.js";
import PisellEmail_default from "../../pisellEmail/PisellEmail.js";
import "../../pisellEmail/index.js";
import PisellUrl_default from "../../pisellUrl/PisellUrl.js";
import "../../pisellUrl/index.js";
import PisellRating_default from "../../pisellRating/PisellRating.js";
import "../../pisellRating/index.js";
import PisellSingleSelect from "../../pisellSingleSelect/PisellSingleSelect.js";
import "../../pisellSingleSelect/index.js";
import PisellMultipleSelect from "../../pisellMultipleSelect/PisellMultipleSelect.js";
import "../../pisellMultipleSelect/index.js";
import PisellDateTimeDisplay_default from "../../pisellDateTimeDisplay/PisellDateTimeDisplay.js";
import React, { useEffect, useState } from "react";
//#region src/components/pisellRecordBoard/utils/recordBoardColumns.tsx
const FIELD_TYPE_TO_READ_COMPONENT = {
	singleLineText: PisellSingleLineText_default,
	longText: PisellLongText_default,
	email: PisellEmail_default,
	phone: PisellPhone_default,
	url: PisellUrl_default,
	number: MemoizedPisellNumber,
	currency: MemoizedPisellCurrency,
	percent: MemoizedPisellPercent,
	rating: PisellRating_default,
	singleSelect: PisellSingleSelect,
	multipleSelect: PisellMultipleSelect,
	dateTime: PisellDateTimeDisplay_default
};
/** 列 type 对应排序类型默认值（组件未导出 SortOptions 时使用） */
const FIELD_TYPE_TO_SORT_OPTIONS_DEFAULT = {
	singleLineText: { type: "string" },
	longText: { type: "string" },
	email: { type: "string" },
	phone: { type: "string" },
	url: { type: "string" },
	number: { type: "number" },
	currency: { type: "number" },
	percent: { type: "number" },
	rating: { type: "number" },
	singleSelect: { type: "option" },
	multipleSelect: { type: "option" },
	dateTime: { type: "date" }
};
/** 从组件或默认值取排序配置；组件可挂载 SortOptions.getSortItems（内置完整排序项）或 SortOptions.type */
function getSortOptionForFieldType(fieldType) {
	const Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
	const fromComponent = Com && Com.SortOptions;
	const fallback = FIELD_TYPE_TO_SORT_OPTIONS_DEFAULT[fieldType];
	const opts = fromComponent !== null && fromComponent !== void 0 ? fromComponent : fallback;
	return opts ? _objectSpread2(_objectSpread2({}, fallback), opts) : null;
}
/** 列 type 对应到 FilterItem 的 type（用于不传 type 时的手动 filter 或派生筛选项的兼容形态）。dateTime 默认用 rangePickerNew（antd）避免使用自研/MUI 的 rangePicker。 */
const FIELD_TYPE_TO_FILTER_TYPE = {
	singleLineText: "input",
	longText: "input",
	email: "input",
	phone: "input",
	url: "input",
	number: "input",
	currency: "input",
	percent: "input",
	rating: "single",
	singleSelect: "single",
	multipleSelect: "single",
	dateTime: "rangePickerNew"
};
function getColumnKey(column) {
	var _column$key;
	const key = (_column$key = column.key) !== null && _column$key !== void 0 ? _column$key : Array.isArray(column.dataIndex) ? column.dataIndex.join(".") : column.dataIndex;
	return typeof key === "string" ? key : "";
}
/** 获取列唯一 key，供列显示隐藏等使用 */
function getRecordBoardColumnKey(column) {
	return getColumnKey(column);
}
function getColumnLabel(column) {
	const title = column.title;
	if (typeof title === "string") return title;
	return getColumnKey(column) || "";
}
/** 从 record 按 dataIndex（支持 string | string[]）取值 */
function getRecordValue(record, dataIndex) {
	if (record == null || dataIndex == null) return void 0;
	return (Array.isArray(dataIndex) ? dataIndex : [dataIndex]).reduce((r, k) => r != null && typeof r === "object" ? r[k] : void 0, record);
}
/** 是否视为空值（用于「全空」判断） */
function isEmptyValue(v) {
	return v == null || v === "";
}
/**
* 同值列总结栏不展示的内容：null/undefined、空串、纯空白、占位「-」。
* 列仍可折叠；仅用于不生成总结栏条目（避免「-」、空白等占位）。
*/
function isTrivialUniformSummaryDisplayValue(v) {
	if (v == null) return true;
	if (typeof v === "string") {
		const t = v.trim();
		return t === "" || t === "-";
	}
	if (typeof v === "number" && Number.isNaN(v)) return true;
	return false;
}
/**
* 总结区实际渲染的 React 节点是否视为无展示价值（与 {@link isTrivialUniformSummaryDisplayValue} 对齐，含一层子节点）。
*/
function isTrivialUniformSummaryReactContent(node) {
	if (node == null || node === false) return true;
	if (typeof node === "string") {
		const t = node.trim();
		return t === "" || t === "-";
	}
	if (typeof node === "number") return Number.isNaN(node);
	if (Array.isArray(node)) return node.length === 0 || node.every((n) => isTrivialUniformSummaryReactContent(n));
	if (React.isValidElement(node)) {
		const ch = node.props.children;
		if (ch == null || ch === false) return true;
		if (typeof ch === "string") {
			const t = ch.trim();
			return t === "" || t === "-";
		}
		if (typeof ch === "number") return Number.isNaN(ch);
		if (Array.isArray(ch)) return ch.length === 0 || ch.every((c) => isTrivialUniformSummaryReactContent(c));
		if (React.isValidElement(ch)) return isTrivialUniformSummaryReactContent(ch);
	}
	return false;
}
/** 是否可直接用 === 比较（string / number） */
function isComparablePrimitive(v) {
	return typeof v === "string" || typeof v === "number";
}
/**
* 根据当前页 data 计算：哪些列「全列同值」或「全空」应隐藏，以及总结区展示项。
* 折叠列与总结项可不一一对应：全空、整列「-」/空白等同值仍折叠，但不生成无信息总结项。
* 仅当 grid.collapseUniformColumns 为 true 时使用。
*/
function computeUniformColumnSummary(data, columns) {
	const uniformHiddenColumnKeys = [];
	const summaryItems = [];
	if (!Array.isArray(data) || data.length === 0) return {
		uniformHiddenColumnKeys,
		summaryItems
	};
	for (const column of columns) {
		if (!(column.collapseWhenUniform !== false)) continue;
		const columnKey = getColumnKey(column);
		if (!columnKey) continue;
		const dataIndex = column.dataIndex;
		const getVal = typeof column.uniformCompare === "function" ? (record) => column.uniformCompare(getRecordValue(record, Array.isArray(dataIndex) ? dataIndex : dataIndex), record) : (record) => getRecordValue(record, Array.isArray(dataIndex) ? dataIndex : dataIndex);
		const values = data.map(getVal);
		const first = values[0];
		if (first === void 0 || first === null) continue;
		const cellValue = getRecordValue(data[0], Array.isArray(dataIndex) ? dataIndex : dataIndex);
		if (values.every((v) => isEmptyValue(v))) {
			uniformHiddenColumnKeys.push(columnKey);
			continue;
		}
		if (!isComparablePrimitive(first)) continue;
		if (!values.every((v) => isEmptyValue(v) && isEmptyValue(first) || v === first)) continue;
		uniformHiddenColumnKeys.push(columnKey);
		if (isTrivialUniformSummaryDisplayValue(first)) continue;
		summaryItems.push({
			columnKey,
			title: getColumnLabel(column),
			type: "uniform",
			displayValue: first != null && first !== "" ? String(first) : void 0,
			value: first,
			cellValue,
			record: data[0]
		});
	}
	return {
		uniformHiddenColumnKeys,
		summaryItems
	};
}
function normalizeOptions(list) {
	if (!Array.isArray(list)) return [];
	return list.map((item) => item && typeof item === "object" && "label" in item && "value" in item ? {
		label: String(item.label),
		value: item.value
	} : {
		label: String(item),
		value: item
	});
}
/**
* 只读单元格：当列使用 getOptions（异步）时，先解析选项再渲染 Pisell 只读组件。
*/
function AsyncOptionsReadCell({ getOptions, value, fieldType, fieldProps }) {
	const [options, setOptions] = useState([]);
	const Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
	useEffect(() => {
		const result = getOptions();
		Promise.resolve(result).then((list) => setOptions(normalizeOptions(list)));
	}, [getOptions]);
	if (Com == null) return value;
	const common = _objectSpread2(_objectSpread2({ value }, fieldProps), {}, { options });
	if (fieldType === "singleSelect" || fieldType === "multipleSelect") return /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({}, common), {}, { readOnly: true }));
	return /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({}, common), {}, { mode: "read" }));
}
/** 为带 type 的列生成只读态渲染函数（Pisell 组件） */
function createReadRender(column, fieldType) {
	var _column$fieldProps;
	const Com = FIELD_TYPE_TO_READ_COMPONENT[fieldType];
	const fieldProps = (_column$fieldProps = column.fieldProps) !== null && _column$fieldProps !== void 0 ? _column$fieldProps : {};
	const getOptions = fieldProps.getOptions;
	const useAsyncOptions = (fieldType === "singleSelect" || fieldType === "multipleSelect") && typeof getOptions === "function";
	return (value) => {
		if (Com == null) return value;
		if (useAsyncOptions) return /* @__PURE__ */ React.createElement(AsyncOptionsReadCell, {
			getOptions,
			value,
			fieldType,
			fieldProps
		});
		const common = _objectSpread2({ value }, fieldProps);
		if (fieldType === "singleSelect" || fieldType === "multipleSelect") return /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({}, common), {}, { readOnly: true }));
		if (fieldType === "dateTime") return /* @__PURE__ */ React.createElement(Com, common);
		return /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({}, common), {}, { mode: "read" }));
	};
}
/**
* 处理列配置：对带 type 的列注入基于 Pisell 组件的 render，其余列保持不变。
* 有 type 时若列上传入了 render 则优先使用（覆盖自动派生）。
*/
function processColumnsForGrid(columns) {
	if (!Array.isArray(columns) || columns.length === 0) return columns !== null && columns !== void 0 ? columns : [];
	return columns.map((col) => {
		const fieldType = col.type;
		if (!fieldType || !FIELD_TYPE_TO_READ_COMPONENT[fieldType]) return col;
		const existingRender = col.render;
		const readRender = createReadRender(col, fieldType);
		return _objectSpread2(_objectSpread2({}, col), {}, { render: existingRender !== null && existingRender !== void 0 ? existingRender : ((value, record, index) => readRender(value, record, index)) });
	});
}
/** 从列配置生成筛选项（FilterItemProps）；有 type 时可由 filter 覆盖，无 type 时需传 filter */
function columnToFilterItem(column) {
	var _f$label2, _f$props2, _f$options;
	const key = getColumnKey(column);
	const label = getColumnLabel(column);
	if (!key) return null;
	if (column.filterable === false) return null;
	const hasExplicitFilter = column.filter && (column.filter.type != null || column.filter.component);
	if (column.type && !hasExplicitFilter) {
		var _column$fieldProps2, _fieldProps$options, _fieldProps$placehold, _getText;
		const fieldType = column.type;
		const filterType = FIELD_TYPE_TO_FILTER_TYPE[fieldType];
		const fieldProps = (_column$fieldProps2 = column.fieldProps) !== null && _column$fieldProps2 !== void 0 ? _column$fieldProps2 : {};
		const hasGetOptions = typeof fieldProps.getOptions === "function";
		const options = fieldType === "singleSelect" || fieldType === "multipleSelect" || fieldType === "rating" ? (_fieldProps$options = fieldProps.options) !== null && _fieldProps$options !== void 0 ? _fieldProps$options : fieldType === "rating" ? [
			1,
			2,
			3,
			4,
			5
		].map((v) => ({
			label: String(v),
			value: v
		})) : hasGetOptions ? void 0 : [] : void 0;
		return {
			type: filterType,
			key,
			name: key,
			label,
			props: filterType === "single" ? _objectSpread2({
				options: options !== null && options !== void 0 ? options : [],
				getOptions: fieldProps.getOptions
			}, fieldProps) : _objectSpread2({ placeholder: (_fieldProps$placehold = fieldProps.placeholder) !== null && _fieldProps$placehold !== void 0 ? _fieldProps$placehold : String((_getText = getText("pisell2.recordBoard.filter.placeholderEnter")) !== null && _getText !== void 0 ? _getText : "").replace(/\{label\}/g, label) }, fieldProps),
			other: _objectSpread2({
				fieldType,
				getOptions: fieldProps.getOptions
			}, fieldProps)
		};
	}
	if (!column.filter) return null;
	const f = column.filter;
	if (f.component) {
		var _f$label, _f$props;
		return {
			type: "custom",
			key,
			name: key,
			label: (_f$label = f.label) !== null && _f$label !== void 0 ? _f$label : label,
			props: (_f$props = f.props) !== null && _f$props !== void 0 ? _f$props : {},
			other: _objectSpread2({ component: f.component }, f.props || {})
		};
	}
	const filterType = f.type;
	if (!filterType) return null;
	const hasGetOptions = typeof f.getOptions === "function";
	return {
		type: filterType,
		key,
		name: key,
		label: (_f$label2 = f.label) !== null && _f$label2 !== void 0 ? _f$label2 : label,
		props: (_f$props2 = f.props) !== null && _f$props2 !== void 0 ? _f$props2 : filterType === "single" ? {
			options: (_f$options = f.options) !== null && _f$options !== void 0 ? _f$options : [],
			getOptions: f.getOptions
		} : {},
		other: filterType === "single" && hasGetOptions ? { getOptions: f.getOptions } : {}
	};
}
/** 从列配置生成排序项（SortItemProps）；有 type 时可由 sort 覆盖，无 type 时需传 sortable + sort */
function columnToSortItem(column) {
	var _s$label;
	const key = getColumnKey(column);
	const label = getColumnLabel(column);
	if (!key) return null;
	if (column.sortable === false) return null;
	const hasExplicitSort = column.sort && (column.sort.type != null || typeof column.sort.getSortItems === "function");
	if (column.type && !hasExplicitSort) {
		var _opts$label;
		const fieldType = column.type;
		if (!FIELD_TYPE_TO_READ_COMPONENT[fieldType]) return null;
		const opts = getSortOptionForFieldType(fieldType);
		if (!opts) return null;
		const hasGetSortItems = "getSortItems" in opts && typeof opts.getSortItems === "function";
		return _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, hasGetSortItems ? {} : { type: "type" in opts ? opts.type : void 0 }), hasGetSortItems && "getSortItems" in opts ? { getSortItems: opts.getSortItems } : {}), {}, {
			name: key,
			label: "label" in opts ? (_opts$label = opts.label) !== null && _opts$label !== void 0 ? _opts$label : label : label,
			isCustom: false
		}, "localFilter" in opts && opts.localFilter !== void 0 && { localFilter: opts.localFilter }), "isHidden" in opts && opts.isHidden !== void 0 && { isHidden: opts.isHidden });
	}
	if (!column.type && column.sortable !== true) return null;
	if (!column.sort) return null;
	const s = column.sort;
	const hasGetSortItems = typeof s.getSortItems === "function";
	const sortItem = _objectSpread2({
		name: key,
		label: (_s$label = s.label) !== null && _s$label !== void 0 ? _s$label : label,
		isCustom: false
	}, s.isHidden !== void 0 && { isHidden: s.isHidden });
	if (hasGetSortItems && s.getSortItems) sortItem.getSortItems = s.getSortItems;
	else if (s.type != null) sortItem.type = s.type;
	return sortItem;
}
/**
* 从 columns 派生排序列表（SortItemProps[]）。
* 有 type 的列：根据组件 SortOptions（或默认）生成；无 type 的列：根据 sortable + sort 生成。
*/
function deriveSortFromColumns(columns) {
	if (!Array.isArray(columns) || columns.length === 0) return [];
	const list = [];
	for (const col of columns) {
		if (Boolean(col.type && FIELD_TYPE_TO_READ_COMPONENT[col.type]) && col.sortable === false) continue;
		const item = columnToSortItem(col);
		if (item) list.push(item);
	}
	return list;
}
/**
* 从 columns 派生 filter 列表（quickFilter + otherFilter）。
* 有 type 的列：根据 type + fieldProps 生成筛选项；无 type 的列：根据 filterable + filter 生成。
*/
function deriveFilterFromColumns(columns) {
	const quickFilter = [];
	const otherFilter = [];
	if (!Array.isArray(columns) || columns.length === 0) return {
		quickFilter,
		otherFilter
	};
	for (const col of columns) {
		var _col$filter, _col$filter2;
		if (!getColumnKey(col)) continue;
		const hasType = Boolean(col.type && FIELD_TYPE_TO_READ_COMPONENT[col.type]);
		if (hasType && col.filterable === false) continue;
		const useQuick = hasType ? ((_col$filter = col.filter) === null || _col$filter === void 0 ? void 0 : _col$filter.quickFilter) === true : Boolean(col.filterable && ((_col$filter2 = col.filter) === null || _col$filter2 === void 0 ? void 0 : _col$filter2.quickFilter));
		const item = columnToFilterItem(col);
		if (!item) continue;
		if (useQuick) quickFilter.push(item);
		else otherFilter.push(item);
	}
	return {
		quickFilter,
		otherFilter
	};
}
//#endregion
export { computeUniformColumnSummary, deriveFilterFromColumns, deriveSortFromColumns, getRecordBoardColumnKey, isTrivialUniformSummaryReactContent, processColumnsForGrid };
