105 lines
3.0 KiB
TypeScript
105 lines
3.0 KiB
TypeScript
import type { FieldMapping, FieldTypeConfig, ColumnConfig, DynamicDeviceData } from './types';
|
||
|
||
// 字段名映射配置
|
||
export const fieldNameMapping: FieldMapping = {
|
||
SystemName: '系统名称',
|
||
ProjectId: '项目ID',
|
||
ProjectName: '项目名称',
|
||
IoTDataType: 'IoT数据类型',
|
||
DeviceType: '设备类型',
|
||
DeviceId: '设备ID',
|
||
Timestamps: '时间戳',
|
||
// 可以根据需要添加更多映射
|
||
};
|
||
|
||
// 字段类型配置
|
||
export const fieldTypeConfig: FieldTypeConfig = {
|
||
Timestamps: {
|
||
formatter: (value: string) => {
|
||
if (!value) return '';
|
||
try {
|
||
return new Date(value).toLocaleString();
|
||
} catch {
|
||
return value;
|
||
}
|
||
},
|
||
},
|
||
// 可以根据需要添加更多类型配置
|
||
};
|
||
|
||
// 固定字段列表 - 这些字段已经在固定列中定义,不需要在动态列中重复生成
|
||
const FIXED_FIELDS = [
|
||
'SystemName',
|
||
'ProjectId',
|
||
'DeviceType',
|
||
'IoTDataType',
|
||
'DeviceId',
|
||
'Timestamps'
|
||
];
|
||
|
||
// 动态生成表格列
|
||
export const generateDynamicColumns = (data: DynamicDeviceData[]): ColumnConfig[] => {
|
||
if (!data || data.length === 0) return [];
|
||
|
||
// 获取第一条数据的所有字段
|
||
const firstRow = data[0];
|
||
if (!firstRow) return [];
|
||
const fields = Object.keys(firstRow);
|
||
|
||
// 过滤掉不需要显示的字段和固定字段
|
||
const excludeFields = ['id', 'key', '__typename', ...FIXED_FIELDS];
|
||
|
||
return fields
|
||
.filter(field => !excludeFields.includes(field))
|
||
.map(field => {
|
||
// 确保字段名是有效的字符串
|
||
const safeField = String(field || '').trim();
|
||
if (!safeField) return null;
|
||
|
||
const columnConfig: ColumnConfig = {
|
||
field: safeField,
|
||
title: fieldNameMapping[safeField] || safeField,
|
||
minWidth: 150,
|
||
showOverflow: true,
|
||
slots: {}, // 添加空的slots属性,避免VXE表格报错
|
||
};
|
||
|
||
// 应用字段类型配置,确保配置是安全的
|
||
if (fieldTypeConfig[safeField]) {
|
||
const typeConfig = fieldTypeConfig[safeField];
|
||
if (typeConfig.formatter && typeof typeConfig.formatter === 'function') {
|
||
columnConfig.formatter = typeConfig.formatter;
|
||
}
|
||
if (typeConfig.width !== undefined) {
|
||
columnConfig.width = typeConfig.width;
|
||
}
|
||
if (typeConfig.minWidth !== undefined) {
|
||
columnConfig.minWidth = typeConfig.minWidth;
|
||
}
|
||
// 确保slots属性始终存在
|
||
if (!columnConfig.slots) {
|
||
columnConfig.slots = {};
|
||
}
|
||
}
|
||
|
||
return columnConfig;
|
||
})
|
||
.filter(Boolean) as ColumnConfig[]; // 过滤掉null值
|
||
};
|
||
|
||
// 获取所有可能的字段(用于预定义列)
|
||
export const getAllPossibleFields = () => {
|
||
return Object.keys(fieldNameMapping);
|
||
};
|
||
|
||
// 预定义列配置(可选)
|
||
export const getPredefinedColumns = () => {
|
||
return getAllPossibleFields().map(field => ({
|
||
field,
|
||
title: fieldNameMapping[field] || field,
|
||
minWidth: 150,
|
||
showOverflow: true,
|
||
...fieldTypeConfig[field],
|
||
}));
|
||
};
|