import { stepCurveChartOption } from './stepCurveChart'
import type { PersistedTestRecord } from '@/api/tests'
import { toTestDisplayValue } from './testDataUnits'

export type ReportMetricKey = 'voltage' | 'current' | 'positiveVoltage' | 'negativeVoltage' | 'temperature'
export interface MeasurementSeries { name: string; zeroTime: number | null; records: PersistedTestRecord[]; hidden?: boolean }

/** 曲线与空状态使用同一时间口径；导入快照的已有辅助测量可沿用记录绝对时间。 */
export function measurementRecordTime(metric: ReportMetricKey, row: PersistedTestRecord) {
  if (metric === 'voltage' || metric === 'current') return row.deviceTime
  return row.collectorDeviceTime ?? (row.sourceType === 'SNAPSHOT' ? row.deviceTime : null)
}

/** 页面和打印共用测量、时间及单位口径；不连接缺失值，也不限制曲线条数。 */
export function measurementChartOption(metric: { key: ReportMetricKey; unit: string }, items: MeasurementSeries[], colors: string[]) {
  const field: Record<ReportMetricKey, keyof PersistedTestRecord> = { voltage: 'voltage', current: 'current', positiveVoltage: 'positivePotential', negativeVoltage: 'negativePotential', temperature: 'temperature' }
  const series = items.map(item => item.records.flatMap(row => {
    const time = measurementRecordTime(metric.key, row)
    if (time == null || item.zeroTime == null) return []
    const value = row[field[metric.key]]
    return [[(Number(time) - item.zeroTime) / 1000, value == null ? null : toTestDisplayValue(metric.key, Number(value))] as [number, number | null]]
  }).sort((left, right) => left[0] - right[0]))
  return stepCurveChartOption(metric, items.map((item, index) => ({ name: item.name, hidden: item.hidden, points: series[index] || [] })), colors)
}
