import type { FormationField, FormationItem } from '@/api/formationReports'
import { formatTestDisplayValue } from './testDataUnits'

/** 页面和打印按同一冻结工步及选择展示终止值，缺失时不借用其他工步。 */
export function formationChargeChoice(item: FormationItem, cycle: number, selections: Record<string, number>) {
  const choices = item.chargeSteps?.[String(cycle)] || []
  const reliable = choices.filter(step => ['cc', 'charge', 'charging'].includes((step.stepType || '').trim().toLowerCase()))
  return reliable.length === 1 ? reliable[0] : choices.find(step => step.stepNo === selections[`${item.source.selection.testId}|${item.source.selection.testBatteryId}|${cycle}`])
}

export const defaultFormationFields: FormationField[] = [
  ...['Z', 'H', 'F', 'A', 'B'].map(key => ({ key, scope: 'detail' as const, kind: 'battery' as const, displayName: key, unit: '' })),
  ...[['FN', 'F/N'], ['C', 'C']].map(([key, displayName]) => ({ key: key!, scope: 'detail' as const, kind: 'calculated' as const, displayName: displayName!, unit: '' })),
  ...[['method', '测试方法'], ['method2', '测试方法2'], ['manual', '数字']].map(([key, displayName]) => ({ key: key!, scope: 'cycle' as const, kind: 'manual' as const, displayName: displayName!, unit: '' })),
  ...[
    ['chargePerGram', '每克N充电量'], ['chargePerGramTotal', '每克F充电量'],
    ['capacity1v', '1.0V容量'], ['capacity1vf', '1.0VF完整容量'], ['dischargeInflection', '拐点容量'], ['dischargeInflectionTotal', '拐点完整容量'],
  ].map(([key, displayName]) => ({ key: key!, scope: 'cycle' as const, kind: 'calculated' as const, displayName: displayName!, unit: key === 'capacity1v' ? 'mAh' : '' })),
]

export function formationFieldLabel(field: FormationField) { return `${field.displayName}${field.unit ? ` (${field.unit})` : ''}` }

/** 默认值从当前预览或冻结快照读取；共享身份优先，缺失不能回退其他循环。 */
export function formationSourceValue(item: FormationItem, cycle: number, field: FormationField): string {
  if (field.kind === 'battery') return item.businessFields.find(value => field.fieldDefinitionId != null
    ? value.fieldDefinitionId === field.fieldDefinitionId : value.fieldName === field.key)?.fieldValue ?? ''
  if (field.kind === 'metric') {
    const value = item.metrics[String(cycle)]?.[field.key]
    // 快照保留 Ah/Wh；仅将来源值换算为 mAh/mWh，人工输入已经是展示值。
    return value == null ? '' : formatTestDisplayValue(field.key, value)
  }
  return ''
}
