import { RecordDetail } from '../types';

/**
 * 提取记录字段值的通用函数
 */
export const extractFieldValue = (record: RecordDetail, fieldId: string): string => {
  if (!fieldId || !record.fields[fieldId]) {
    return '';
  }
  
  const fieldValue = record.fields[fieldId];
  
  // 优先处理数组格式（公式字段）
  if (Array.isArray(fieldValue) && fieldValue.length > 0) {
    const firstItem = fieldValue[0];
    if (typeof firstItem === 'string') {
      return firstItem;
    } else if (firstItem && (firstItem.text || firstItem.name)) {
      return firstItem.text || firstItem.name;
    }
  }
  // 处理对象格式（普通字段）
  else if (typeof fieldValue === 'object' && fieldValue !== null) {
    if (fieldValue.text) {
      return fieldValue.text;
    } else if (fieldValue.name) {
      return fieldValue.name;
    }
  }
  // 处理字符串格式
  else if (typeof fieldValue === 'string') {
    return fieldValue.trim();
  }
  
  return '';
};

/**
 * 构建字段名到字段ID的映射
 */
export const buildFieldNameToIdMap = (fieldMetaList: any[]): Map<string, string> => {
  const fieldMap = new Map<string, string>();
  for (const fieldMeta of fieldMetaList) {
    fieldMap.set(fieldMeta.name, fieldMeta.id);
  }
  return fieldMap;
};

/**
 * 从记录中提取标签值
 */
export const extractLabelsFromRecord = (
  record: RecordDetail,
  fieldMap: Map<string, string>
): Record<string, string> => {
  const extractedLabels: Record<string, string> = {};
  
  const labelMappings = [
    { key: '标签2', fieldName: '品类名称' },
    { key: '标签3', fieldName: '大类名称' },
    { key: '标签4', fieldName: '中类名称' },
    { key: '标签5', fieldName: '小类名称' },
    { key: '标签6', fieldName: '工艺难易度' },
  ];
  
  for (const mapping of labelMappings) {
    const fieldId = fieldMap.get(mapping.fieldName);
    if (fieldId) {
      const value = extractFieldValue(record, fieldId);
      if (value) {
        extractedLabels[mapping.key] = value;
      }
    }
  }
  
  return extractedLabels;
};