const AXIS_DECIMALS = 2
/** 与 formatAxisLabel 小数位一致，刻度步长不得小于此值，避免标签重复 */
const MIN_TICK_STEP = 10 ** -AXIS_DECIMALS

export interface YAxisRange {
    min: number
    max: number
    interval: number
}

export function roundAxisValue(val: number, decimals = AXIS_DECIMALS): number {
    if (!Number.isFinite(val)) return 0
    const factor = 10 ** decimals
    return Math.round(val * factor) / factor
}

/** Y 轴刻度：最多 2 位小数，末尾 0 去掉（如 1.00 → 1，0.10 → 0.1） */
export function formatAxisLabel(value: number): string {
    if (!Number.isFinite(value)) return '0'
    return String(Number(roundAxisValue(value).toFixed(AXIS_DECIMALS)))
}

/** 根据数据范围计算与显示精度对齐的刻度步长 */
function calcNiceTickInterval(range: number, maxTicks = 6): number {
    if (!Number.isFinite(range) || range <= 0) return MIN_TICK_STEP

    const raw = range / maxTicks
    const magnitude = 10 ** Math.floor(Math.log10(raw))
    const normalized = raw / magnitude

    let niceFactor: number
    if (normalized <= 1) niceFactor = 1
    else if (normalized <= 2) niceFactor = 2
    else if (normalized <= 5) niceFactor = 5
    else niceFactor = 10

    let interval = niceFactor * magnitude

    if (interval < MIN_TICK_STEP) {
        interval = MIN_TICK_STEP
    } else {
        interval = Math.ceil(interval / MIN_TICK_STEP) * MIN_TICK_STEP
    }

    return roundAxisValue(interval)
}

/** 将 min/max 对齐到刻度步长边界 */
function alignAxisToInterval(min: number, max: number, interval: number): { min: number; max: number } {
    const alignedMin = Math.floor(min / interval) * interval
    let alignedMax = Math.ceil(max / interval) * interval

    if (alignedMax <= alignedMin) {
        alignedMax = alignedMin + interval
    }

    return {
        min: roundAxisValue(alignedMin),
        max: roundAxisValue(alignedMax)
    }
}

function buildYAxisRange(axisMin: number, axisMax: number): YAxisRange {
    const interval = calcNiceTickInterval(axisMax - axisMin)
    const aligned = alignAxisToInterval(axisMin, axisMax, interval)
    return {
        ...aligned,
        interval
    }
}

/** 瞬间波形 Y 轴范围 */
export function calcShuYAxisRange(dataMin: number, dataMax: number): YAxisRange {
    const min = Number(dataMin)
    const max = Number(dataMax)
    if (!Number.isFinite(min) || !Number.isFinite(max)) {
        return buildYAxisRange(0, 1)
    }

    let axisMax = max * 1.1
    let axisMin = min > 0 ? min - min * 0.1 : min * 1.1

    if (axisMax <= axisMin) {
        const pad = Math.abs(max) * 0.1 || 0.01
        axisMax = max + pad
        axisMin = min - pad
    }

    return buildYAxisRange(axisMin, axisMax)
}

/** 波形图 dataZoom（默认 filterMode，仅缩放 X 轴） */
export const WAVE_DATA_ZOOM = [
    {
        type: 'inside' as const,
        xAxisIndex: 0,
        start: 0,
        end: 100,
        

    },
    {
        type: 'slider' as const,
        xAxisIndex: 0,
        height: 13,
        bottom: '10px',
        start: 0,
        end: 100
    }
]

export const WAVE_AXIS_POINTER = {
    type: 'line' as const,
    snap: true
}

/** 波形折线 series：不做 sampling/smooth，保证 tooltip 与折线位置一致 */
export function createWaveLineSeries(name: string | null, data: number[][], color: string) {
    return {
        name,
        type: 'line' as const,
        large: data.length > 2000,
        largeThreshold: 2000,
        smooth: false,
        symbol: 'none' as const,
        itemStyle: { color },
        data
    }
}

const WAVE_TOOLTIP_SKIP_SERIES = new Set(['暂降触发点', '最小暂降幅值'])

/** 波形图 axis tooltip：从 data/value 中安全取 [x, y] */
export function formatWaveAxisTooltip(
    params: any[],
    options?: { showMarker?: boolean }
): string {
    if (!params?.length) return ''

    const showMarker = options?.showMarker !== false
    let time = ''

    const axisValue = params[0]?.axisValue
    if (axisValue != null && Number.isFinite(Number(axisValue))) {
        time = String(Number(Number(axisValue).toFixed(2)))
    } else {
        for (const param of params) {
            if (!param || WAVE_TOOLTIP_SKIP_SERIES.has(param.seriesName)) continue
            const point = param.data ?? param.value
            if (Array.isArray(point) && point.length >= 2) {
                time = String(point[0])
                break
            }
        }
    }

    let tips = `时刻:${time}<br/>`
    for (const param of params) {
        if (!param?.seriesName || WAVE_TOOLTIP_SKIP_SERIES.has(param.seriesName)) continue
        const point = param.data ?? param.value
        const y = Array.isArray(point) ? Number(point[1]) : Number(point)
        if (!Number.isFinite(y)) continue
        const prefix = showMarker ? param.marker || '' : ''
        tips += `${prefix}${param.seriesName}:${y.toFixed(2)}<br/>`
    }
    return tips
}

/** RMS 波形 Y 轴范围 */
export function calcRmsYAxisRange(dataMin: number, dataMax: number): YAxisRange {
    const min = Number(dataMin)
    const max = Number(dataMax)
    if (!Number.isFinite(min) || !Number.isFinite(max)) {
        return buildYAxisRange(0, 1)
    }

    let axisMax = max * 1.06 * 1.1
    let axisMin = min - min * 0.2

    if (axisMax <= axisMin) {
        const pad = Math.abs(max - min) * 0.1 || Math.abs(max) * 0.1 || 0.01
        axisMax = max + pad
        axisMin = min - pad
    }

    return buildYAxisRange(axisMin, axisMax)
}
