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 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 = metric.key === 'voltage' || metric.key === 'current' ? row.deviceTime : row.collectorDeviceTime
    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)
}
