import { toRaw } from 'vue'
import { getWaveRawList } from './waveRawStore'

type WorkerMessageHandler = (data: any) => void

let shuWorker: Worker | null = null
let rmsWorker: Worker | null = null

/** 递归剥离 Vue 响应式代理，得到可 structuredClone 的纯对象 */
export function toPlainDeep<T>(value: T): T {
    const raw = toRaw(value as object) as T
    if (Array.isArray(raw)) {
        return raw.map(item => toPlainDeep(item)) as T
    }
    if (raw !== null && typeof raw === 'object') {
        const out: Record<string, unknown> = {}
        for (const [key, val] of Object.entries(raw)) {
            out[key] = toPlainDeep(val)
        }
        return out as T
    }
    return raw
}

const BOXO_LIST_KEYS = [
    'systemType',
    'powerStationName',
    'measurementPointName',
    'startTime',
    'featureAmplitude',
    'duration',
    'engineeringName',
    'equipmentName',
    'evtParamVVaDepth',
    'evtParamTm',
    'lineName',
    'persistTime',
    'subName'
] as const

export function buildWorkerPayload(
    type: 'shu' | 'rms',
    wp: Record<string, any>,
    boxoList: Record<string, any>,
    extras: { requestId: number; value: number; isOpen: boolean; iphasic?: number }
) {
    const plainWp = toPlainDeep(wp)
    const wpPayload: Record<string, unknown> = {
        pt: plainWp.pt,
        ct: plainWp.ct,
        waveTitle: plainWp.waveTitle,
        iphasic: plainWp.iphasic,
        time: plainWp.time,
        waveType: plainWp.waveType,
        yzd: plainWp.yzd
    }
    const storeKey = plainWp.waveStoreKey as string | undefined
    if (type === 'shu') {
        wpPayload.listWaveData = getWaveRawList('shu', storeKey) ?? plainWp.listWaveData
    } else {
        wpPayload.listRmsData = getWaveRawList('rms', storeKey) ?? plainWp.listRmsData
    }

    const plainBoxo: Record<string, unknown> = {}
    const rawBoxo = toPlainDeep(boxoList)
    for (const key of BOXO_LIST_KEYS) {
        if (rawBoxo[key] !== undefined) {
            plainBoxo[key] = rawBoxo[key]
        }
    }

    return {
        requestId: extras.requestId,
        value: extras.value,
        isOpen: extras.isOpen,
        iphasic: extras.iphasic,
        wp: wpPayload,
        boxoList: plainBoxo
    }
}

export function getShuWorker(onMessage: WorkerMessageHandler): Worker {
    if (!shuWorker) {
        shuWorker = new Worker(new URL('../components/echarts/shuWorker.js', import.meta.url))
    }
    shuWorker.onmessage = e => onMessage(e.data)
    shuWorker.onerror = error => console.error('Shu worker error:', error)
    return shuWorker
}

export function getRmsWorker(onMessage: WorkerMessageHandler): Worker {
    if (!rmsWorker) {
        rmsWorker = new Worker(new URL('../components/echarts/rmsWorker.js', import.meta.url))
    }
    rmsWorker.onmessage = e => onMessage(e.data)
    rmsWorker.onerror = error => console.error('Rms worker error:', error)
    return rmsWorker
}
