/** 原始波形数据存放于 Vue 响应式体系之外，避免大数组触发深度代理与重复持有 */

interface WaveRawEntry {
    listWaveData?: unknown[][]
    listRmsData?: unknown[][]
    waveTimeRange?: { min: number; max: number }
}

const rawStore = new Map<string, WaveRawEntry>()

function calcTimeRange(data: unknown[][] | undefined): { min: number; max: number } | undefined {
    if (!data?.length) return undefined
    const first = data[0] as number[]
    const last = data[data.length - 1] as number[]
    return { min: first[0], max: last[0] + 1 }
}

export function buildWaveStoreKey(boxoList: Record<string, any>): string {
    const id = boxoList?.eventId ?? boxoList?.id ?? ''
    return `${id}|${boxoList?.startTime ?? ''}`
}

export function registerWaveRaw(storeKey: string, wp: Record<string, any>): void {
    if (!storeKey || !wp) return
    const entry: WaveRawEntry = rawStore.get(storeKey) ?? {}

    if (wp.listWaveData?.length) {
        entry.listWaveData = wp.listWaveData
        entry.waveTimeRange = calcTimeRange(wp.listWaveData) ?? entry.waveTimeRange
    }
    if (wp.listRmsData?.length) {
        entry.listRmsData = wp.listRmsData
        entry.waveTimeRange = calcTimeRange(wp.listRmsData) ?? entry.waveTimeRange
    }

    rawStore.set(storeKey, entry)
}

export function getWaveRawList(type: 'shu' | 'rms', storeKey: string | undefined): unknown[][] | undefined {
    if (!storeKey) return undefined
    const entry = rawStore.get(storeKey)
    return type === 'shu' ? entry?.listWaveData : entry?.listRmsData
}

export function getWaveTimeRange(storeKey: string | undefined): { min: number; max: number } | undefined {
    if (!storeKey) return undefined
    return rawStore.get(storeKey)?.waveTimeRange
}

export function releaseWaveRaw(storeKey: string | undefined, type: 'shu' | 'rms' | 'all' = 'all'): void {
    if (!storeKey) return
    if (type === 'all') {
        rawStore.delete(storeKey)
        return
    }
    const entry = rawStore.get(storeKey)
    if (!entry) return
    if (type === 'shu') delete entry.listWaveData
    if (type === 'rms') delete entry.listRmsData
    if (!entry.listWaveData && !entry.listRmsData) {
        rawStore.delete(storeKey)
    } else {
        rawStore.set(storeKey, entry)
    }
}

/** 构建不含大数组的 wp 对象，供子组件 props 使用 */
export function buildSlimWp(wp: Record<string, any>, storeKey: string): Record<string, any> {
    const { listWaveData: _w, listRmsData: _r, ...rest } = wp
    return {
        ...rest,
        waveStoreKey: storeKey,
        waveTimeRange: getWaveTimeRange(storeKey) ?? calcTimeRange(_w) ?? calcTimeRange(_r)
    }
}
