<template>
    <div v-loading="loading" style="position: relative; height: 100%">
        <div id="boxr">
            <div id="rmsp" :style="`height:${vh};overflow: hidden;min-height: 200px;`">
                <div class="bx" id="rms" style="min-height: 200px"></div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import html2canvas from 'html2canvas'
import $ from 'jquery'
import * as echarts from 'echarts'
import { mainHeight } from '@/utils/layout'
import { calcRmsYAxisRange, formatAxisLabel } from '@/utils/chartAxisHelper'
import url from '@/assets/img/point.png'
import url2 from '@/assets/img/dw.png'
import { buildWaveCacheKey, getWaveCache, setWaveCache } from '@/utils/waveCache'
import { getRmsWorker, buildWorkerPayload } from '@/utils/waveWorkerPool'

let waveRequestId = 0
const pendingCacheKeys = new Map<number, string>()
let rmsWorker: Worker | null = null
interface WaveData {
    instantF: { max: number; min: number }
    instantS: { max: number; min: number }
    RMSF: { max: number; min: number }
    RMSS: { max: number; min: number }
    RMSFMinDetail: {
        rmsvFirstX: number
        rmsvFirstY: number
        firstZhou: string
    }
    RMSSMinDetail: {
        rmsvSecondX: number
        rmsvSecondY: number
        secondeZhou: string
    }
    shunshiF: {
        shunshiFA: number[][]
        shunshiFB: number[][]
        shunshiFC: number[][]
    }
    shunshiS: {
        shunshiSA: number[][]
        shunshiSB: number[][]
        shunshiSC: number[][]
    }
    RMSFWave: {
        rmsFA: number[][]
        rmsFB: number[][]
        rmsFC: number[][]
    }
    RMSSWave: {
        rmsSA: number[][]
        rmsSB: number[][]
        rmsSC: number[][]
    }
    title: {
        aTitle: string
        bTitle: string
        cTitle: string
        unit: string
    }
    unit: string
}

interface Props {
    value?: number
    flag?: string | number | boolean
    parentHeight?: any
    DColor?: boolean
    boxoList?: any
    wp?: any
}

const props = withDefaults(defineProps<Props>(), {
    value: 2,
    flag: 3,
    parentHeight: 0,
    DColor: false,
    boxoList: () => ({}),
    wp: () => ({})
})

const loading = ref(true)
const tabvalue = ref(props.value)
const valA: any = ref(0)
const valB: any = ref(0)
const isOpen = ref(false)
const time = ref('')
const type = ref('')
const severity = ref('')
const iphasic: any = ref(0)
const eventValue = ref('')
const persistTime = ref('')
const lineName = ref('')
const subName = ref('')
const waveDatas = ref<WaveData[]>([])
const ptpass = ref('')
const color = ref('#006565')
const charts = ref({})
const arrpoints = ref([])
const fz = ref<number[]>([])
const titles = ref('')
const zoom = ref(1)
const myChartess = ref<echarts.ECharts | null>(null)
const myChartess1 = ref<echarts.ECharts | null>(null)
const myChartess2 = ref<echarts.ECharts | null>(null)
const myChartess3 = ref<echarts.ECharts | null>(null)
const myChartess4 = ref<echarts.ECharts | null>(null)
const myChartess5 = ref<echarts.ECharts | null>(null)

const vh = computed(() => {
    if (props.parentHeight == 999) {
        return `calc((60vh - 150px) / 2 )`
    } else if (props.parentHeight != 0) {
        return mainHeight(props.parentHeight, 2).height
    }

    if (props.flag == 1) {
        return mainHeight(200).height
    } else {
        return mainHeight(200, 2).height
    }
})

const vw = computed(() => '100%')

watch(
    () => props.value,
    () => {
        query()
    }
)

watch(
    () => props.wp,
    () => {
        query()
    }
)

const applyWorkerResult = (data: any) => {
    titles.value = data.titles
    waveDatas.value = data.waveDatas
    time.value = data.time
    type.value = data.type
    severity.value = data.severity
    iphasic.value = data.iphasic

    if (Number(severity.value) < 0) {
        severity.value = '/'
        type.value = '/'
    }

    initWave(waveDatas.value, time.value, type.value, severity.value, isOpen.value)
    loading.value = false
}

onMounted(() => {
    const zoomValue = document.body.style.getPropertyValue('zoom')
    zoom.value = 1 / (zoomValue ? parseFloat(zoomValue) : 1)
    window.addEventListener('resize', handleResize)

    rmsWorker = getRmsWorker(data => {
        if (data.requestId !== waveRequestId) return
        if (!data.success) {
            console.error('Worker error:', data.error)
            loading.value = false
            return
        }
        const cacheKey = pendingCacheKeys.get(data.requestId)
        if (cacheKey) {
            setWaveCache(cacheKey, data)
            pendingCacheKeys.delete(data.requestId)
        }
        applyWorkerResult(data)
    })

    nextTick(() => {
        query()
    })
})

onBeforeUnmount(() => {
    backbxlb()
    window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
    const zoomValue = document.body.style.getPropertyValue('zoom')
    zoom.value = 1 / (zoomValue ? parseFloat(zoomValue) : 1)
}

const download = () => {
    const boxr = document.getElementById('boxr')
    if (boxr) {
        html2canvas(boxr, {
            scale: 2
        }).then(function (canvas) {
            const creatIMg = document.createElement('a')
            creatIMg.download = 'rms波形.png'
            creatIMg.href = canvas.toDataURL()
            creatIMg.click()
            creatIMg.remove()
        })
    }
}

const EXTRA_PANEL_CLASS = 'wave-extra-panel'

const resetWaveDom = () => {
    backbxlb()
    $('#rmsp').nextAll(`.${EXTRA_PANEL_CLASS}`).remove()
}

const query = () => {
    initWaves()
}

const waveData = (
    instantF: any,
    instantS: any,
    RMSF: any,
    RMSS: any,
    RMSFMinDetail: any,
    RMSSMinDetail: any,
    shunshiF: any,
    shunshiS: any,
    RMSFWave: any,
    RMSSWave: any,
    title: any,
    unit: any
): WaveData => {
    return {
        instantF,
        instantS,
        RMSF,
        RMSS,
        RMSFMinDetail,
        RMSSMinDetail,
        shunshiF,
        shunshiS,
        RMSFWave,
        RMSSWave,
        title,
        unit
    }
}

const initWaves = () => {
    if (!props.wp?.listRmsData?.length) {
        initWave(null, null, null, null, null)
        loading.value = false
        return
    }

    const cacheKey = buildWaveCacheKey('rms', props.wp, props.value, isOpen.value, props.boxoList)
    const cached = getWaveCache<any>(cacheKey)
    if (cached) {
        applyWorkerResult(cached)
        return
    }

    loading.value = true
    iphasic.value = props.wp.iphasic || 1
    const currentRequestId = ++waveRequestId
    pendingCacheKeys.set(currentRequestId, cacheKey)

    rmsWorker?.postMessage(
        buildWorkerPayload('rms', props.wp, props.boxoList, {
            requestId: currentRequestId,
            value: props.value,
            isOpen: isOpen.value
        })
    )
}

const fliteWaveData = (wp: any, step: number): WaveData => {
    const rmsData = wp.listRmsData
    const pt = Number(wp.pt) / 1000
    const ct = Number(wp.ct)
    const titleList = wp.waveTitle
    let xishu = pt
    let aTitle = '',
        bTitle = '',
        cTitle = '',
        unit = '电压'
    let rmsvFirstX = 0,
        rmsvFirstY = 0,
        rmsvSecondX = 0,
        rmsvSecondY = 0,
        firstZhou = 'a',
        secondeZhou = 'a'
    let ifmax = 0,
        ifmin = 0,
        ismax = 0,
        ismin = 0,
        rfmax = 0,
        rfmin = 0,
        rsmax = 0,
        rsmin = 0

    const shunshiFA: number[][] = []
    const shunshiFB: number[][] = []
    const shunshiFC: number[][] = []
    const shunshiSA: number[][] = []
    const shunshiSB: number[][] = []
    const shunshiSC: number[][] = []
    const rmsFA: number[][] = []
    const rmsFB: number[][] = []
    const rmsFC: number[][] = []
    const rmsSA: number[][] = []
    const rmsSB: number[][] = []
    const rmsSC: number[][] = []

    if (titleList[iphasic.value * step + 1]?.substring(0, 1) !== 'U') {
        xishu = ct
        unit = '电流'
    }

    for (let i = 1; i <= iphasic.value; i++) {
        switch (i) {
            case 1:
                aTitle = titleList[iphasic.value * step + i]?.substring(1) || ''
                break
            case 2:
                bTitle = titleList[iphasic.value * step + i]?.substring(1) || ''
                break
            case 3:
                cTitle = titleList[iphasic.value * step + i]?.substring(1) || ''
                break
        }
    }

    if (rmsData[0][iphasic.value * step + 1] !== undefined) {
        rfmax = rmsData[0][iphasic.value * step + 1] * xishu
        rfmin = rmsData[0][iphasic.value * step + 1] * xishu
        rmsvFirstY = rmsData[0][iphasic.value * step + 1] * xishu
        rmsvFirstX = rmsData[0][0]
        rsmax = rmsData[0][iphasic.value * step + 1]
        rsmin = rmsData[0][iphasic.value * step + 1]
        rmsvSecondY = rmsData[0][iphasic.value * step + 1]
        rmsvSecondX = rmsData[0][0]
    }

    for (let rms = 0; rms < rmsData.length; rms++) {
        if (rmsData[rms][iphasic.value * step + 1] === undefined) {
            break
        }

        switch (iphasic.value) {
            case 1:
                const rmsFirstA = rmsData[rms][iphasic.value * step + 1] * xishu
                rmsFA.push([rmsData[rms][0], rmsFirstA])
                rfmax = rfmax > rmsFirstA ? rfmax : rmsFirstA
                rfmin = rfmin < rmsFirstA ? rfmin : rmsFirstA
                if (rfmin < rmsvFirstY) {
                    rmsvFirstY = rfmin
                    firstZhou = 'a'
                    rmsvFirstX = rmsData[rms][0]
                }

                const rmsSecondA = rmsData[rms][iphasic.value * step + 1]
                rmsSA.push([rmsData[rms][0], rmsSecondA])
                rsmax = rsmax > rmsSecondA ? rsmax : rmsSecondA
                rsmin = rsmin < rmsSecondA ? rsmin : rmsSecondA
                if (rsmin < rmsvSecondY) {
                    rmsvSecondY = rsmin
                    secondeZhou = 'a'
                    rmsvSecondX = rmsData[rms][0]
                }
                break
            case 2:
                const rmsFirstA2 = rmsData[rms][iphasic.value * step + 1] * xishu
                const rmsFirstB2 = rmsData[rms][iphasic.value * step + 2] * xishu
                rmsFA.push([rmsData[rms][0], rmsFirstA2])
                rmsFB.push([rmsData[rms][0], rmsFirstB2])
                rfmax = getMaxTwo(rfmax, rmsFirstA2, rmsFirstB2)
                rfmin = getMinOpen(rfmin, rmsFirstA2, rmsFirstB2)
                if (rfmin < rmsvFirstY) {
                    rmsvFirstY = rfmin
                    if (rfmin === rmsFirstA2) {
                        firstZhou = 'a'
                    } else if (rfmin === rmsFirstB2) {
                        firstZhou = 'b'
                    }
                    rmsvFirstX = rmsData[rms][0]
                }

                const rmsSecondA2 = rmsData[rms][iphasic.value * step + 1]
                const rmsSecondB2 = rmsData[rms][iphasic.value * step + 2]
                rmsSA.push([rmsData[rms][0], rmsSecondA2])
                rmsSB.push([rmsData[rms][0], rmsSecondB2])
                rsmax = getMaxTwo(rsmax, rmsSecondA2, rmsSecondB2)
                rsmin = getMinOpen(rsmin, rmsSecondA2, rmsSecondB2)
                if (rsmin < rmsvSecondY) {
                    rmsvSecondY = rsmin
                    if (rsmin === rmsSecondA2) {
                        secondeZhou = 'a'
                    } else if (rsmin === rmsSecondB2) {
                        secondeZhou = 'b'
                    }
                    rmsvSecondX = rmsData[rms][0]
                }
                break
            case 3:
                const rmsFirstA3 = rmsData[rms][iphasic.value * step + 1] * xishu
                const rmsFirstB3 = rmsData[rms][iphasic.value * step + 2] * xishu
                const rmsFirstC3 = rmsData[rms][iphasic.value * step + 3] * xishu
                rmsFA.push([rmsData[rms][0], rmsFirstA3])

                rmsFB.push([rmsData[rms][0], rmsFirstB3])
                rmsFC.push([rmsData[rms][0], rmsFirstC3])
                rfmax = getMax(rfmax, rmsFirstA3, rmsFirstB3, rmsFirstC3)
                rfmin = isOpen.value
                    ? getMinOpen(rfmin, rmsFirstA3, rmsFirstC3)
                    : getMin(rfmin, rmsFirstA3, rmsFirstB3, rmsFirstC3)
                if (rfmin < rmsvFirstY) {
                    rmsvFirstY = rfmin
                    if (rfmin === rmsFirstA3) {
                        firstZhou = 'a'
                    } else if (rfmin === rmsFirstB3) {
                        firstZhou = 'b'
                    } else {
                        firstZhou = 'c'
                    }
                    rmsvFirstX = rmsData[rms][0]
                }

                const rmsSecondA3 = rmsData[rms][iphasic.value * step + 1]
                const rmsSecondB3 = rmsData[rms][iphasic.value * step + 2]
                const rmsSecondC3 = rmsData[rms][iphasic.value * step + 3]
                rmsSA.push([rmsData[rms][0], rmsSecondA3])
                rmsSB.push([rmsData[rms][0], rmsSecondB3])
                rmsSC.push([rmsData[rms][0], rmsSecondC3])
                rsmax = getMax(rsmax, rmsSecondA3, rmsSecondB3, rmsSecondC3)
                rsmin = isOpen.value
                    ? getMinOpen(rsmin, rmsSecondA3, rmsSecondC3)
                    : getMin(rsmin, rmsSecondA3, rmsSecondB3, rmsSecondC3)
                if (rsmin < rmsvSecondY) {
                    rmsvSecondY = rsmin
                    if (rsmin === rmsSecondA3) {
                        secondeZhou = 'a'
                    } else if (rsmin === rmsSecondB3) {
                        secondeZhou = 'b'
                    } else {
                        secondeZhou = 'c'
                    }
                    rmsvSecondX = rmsData[rms][0]
                }
                break
        }
    }

    const instantF = { max: ifmax, min: ifmin }
    const instantS = { max: ismax, min: ismin }
    const RMSF = { max: rfmax, min: rfmin }
    const RMSS = { max: rsmax, min: rsmin }
    const RMSFMinDetail = { rmsvFirstX, rmsvFirstY, firstZhou }
    const RMSSMinDetail = { rmsvSecondX, rmsvSecondY, secondeZhou }
    const shunshiF = { shunshiFA, shunshiFB, shunshiFC }
    const shunshiS = { shunshiSA, shunshiSB, shunshiSC }
    const RMSFWave = { rmsFA, rmsFB, rmsFC }
    const RMSSWave = { rmsSA, rmsSB, rmsSC }
    const title = { aTitle, bTitle, cTitle, unit }

    return waveData(
        instantF,
        instantS,
        RMSF,
        RMSS,
        RMSFMinDetail,
        RMSSMinDetail,
        shunshiF,
        shunshiS,
        RMSFWave,
        RMSSWave,
        title,
        unit
    )
}

const initWave = (
    waveDatas: WaveData[] | null,
    time: string | null,
    type: string | null,
    severity: string | null,
    isOpen: boolean | null
) => {
    resetWaveDom()

    let picHeight = vh.value
    const show = !isOpen
    let isvisible = false
    let rmscu: number[][] = []
    let rmscm: number[][] = []
    let titleText = ''
    let unit = ''
    let a: string | null = null,
        b: string | null = null,
        c: string | null = null
    let radata: number[][] = [],
        rbdata: number[][] = [],
        rcdata: number[][] = []
    let rmsvX: any = 0,
        rmsvY: any = 0,
        zhou = ''

    if (!waveDatas) {
        titleText = '该事件暂无波形图'
    } else if (waveDatas.length > 0) {
        titleText = titles.value

        if (Number(eventValue.value) <= 90) {
            isvisible = true
        }

        switch (iphasic.value) {
            case 1:
                a = waveDatas[0].title.aTitle
                if (props.value === 1) {
                    rmscu = [[0, waveDatas[0].RMSF.min]]
                    rmscm = [[0, waveDatas[0].RMSF.max]]
                    radata = waveDatas[0].RMSFWave.rmsFA
                    rmsvX = waveDatas[0].RMSFMinDetail.rmsvFirstX
                    rmsvY = waveDatas[0].RMSFMinDetail.rmsvFirstY
                    zhou = waveDatas[0].RMSFMinDetail.firstZhou
                } else {
                    rmscu = [[0, waveDatas[0].RMSS.min]]
                    rmscm = [[0, waveDatas[0].RMSS.max]]
                    radata = waveDatas[0].RMSSWave.rmsSA
                    rmsvX = waveDatas[0].RMSSMinDetail.rmsvSecondX
                    rmsvY = waveDatas[0].RMSSMinDetail.rmsvSecondY
                    zhou = waveDatas[0].RMSSMinDetail.secondeZhou
                }
                break
            case 2:
                a = waveDatas[0].title.aTitle
                b = waveDatas[0].title.bTitle
                if (props.value === 1) {
                    rmscu = [[0, waveDatas[0].RMSF.min]]
                    rmscm = [[0, waveDatas[0].RMSF.max]]
                    radata = waveDatas[0].RMSFWave.rmsFA
                    rbdata = waveDatas[0].RMSFWave.rmsFB
                    rmsvX = waveDatas[0].RMSFMinDetail.rmsvFirstX
                    rmsvY = waveDatas[0].RMSFMinDetail.rmsvFirstY
                    zhou = waveDatas[0].RMSFMinDetail.firstZhou
                } else {
                    rmscu = [[0, waveDatas[0].RMSS.min]]
                    rmscm = [[0, waveDatas[0].RMSS.max]]
                    radata = waveDatas[0].RMSSWave.rmsSA
                    rbdata = waveDatas[0].RMSSWave.rmsSB
                    rmsvX = waveDatas[0].RMSSMinDetail.rmsvSecondX
                    rmsvY = waveDatas[0].RMSSMinDetail.rmsvSecondY
                    zhou = waveDatas[0].RMSSMinDetail.secondeZhou
                }
                break
            case 3:
                a = waveDatas[0].title.aTitle
                b = waveDatas[0].title.bTitle
                c = waveDatas[0].title.cTitle
                if (props.value === 1) {
                    rmscu = [[0, waveDatas[0].RMSF.min]]
                    rmscm = [[0, waveDatas[0].RMSF.max]]
                    radata = waveDatas[0].RMSFWave.rmsFA
                    rbdata = waveDatas[0].RMSFWave.rmsFB
                    rcdata = waveDatas[0].RMSFWave.rmsFC
                    rmsvX = waveDatas[0].RMSFMinDetail.rmsvFirstX
                    rmsvY = waveDatas[0].RMSFMinDetail.rmsvFirstY
                    zhou = waveDatas[0].RMSFMinDetail.firstZhou
                } else {
                    rmscu = [[0, waveDatas[0].RMSS.min]]
                    rmscm = [[0, waveDatas[0].RMSS.max]]
                    radata = waveDatas[0].RMSSWave.rmsSA
                    rbdata = waveDatas[0].RMSSWave.rmsSB
                    rcdata = waveDatas[0].RMSSWave.rmsSC
                    rmsvX = waveDatas[0].RMSSMinDetail.rmsvSecondX
                    rmsvY = waveDatas[0].RMSSMinDetail.rmsvSecondY
                    zhou = waveDatas[0].RMSSMinDetail.secondeZhou
                }
                break
        }

        if (waveDatas[0].title.unit === '电压') {
            if (props.value === 1) {
                fz.value = [
                    props.wp.listRmsMinData[0][0],
                    Number(((props.wp.listRmsMinData[0][1] * Number(props.wp.pt)) / 1000).toFixed(2))
                ]
                unit = 'kV'
            } else {
                fz.value = [props.wp.listRmsMinData[0][0], props.wp.listRmsMinData[0][1]]
                unit = 'V'
            }
        } else {
            unit = 'A'
        }

        for (let step = waveDatas.length - 1; step > 0 && step < waveDatas.length; step--) {
            const rmsId = 'rms' + step
            const newDivRms = $(
                `<div class="${EXTRA_PANEL_CLASS}" style="height:${vh.value};overflow: hidden;min-height: 200px;"><div class='bx' id='${rmsId}'></div></div>`
            )
            newDivRms.insertAfter($('#rmsp'))
            $(`#${rmsId}`).css('height', picHeight).css('width', vw.value).css('min-height', '200px')
        }
    } else {
        titleText = `变电站名称：${subName.value} 监测点名称：${lineName.value} 发生时刻：${time} 暂降(骤升)幅值：${(
            Number(eventValue.value) * 1
        ).toFixed(0)}% 持续时间：${persistTime.value}s`
    }
    const rms = document.getElementById('rmsp')

    if (!rms) return

    const yRange = calcRmsYAxisRange(rmscu[0]?.[1] ?? 0, rmscm[0]?.[1] ?? 0)

    const existingChart = echarts.getInstanceByDom(rms)
    if (existingChart) existingChart.dispose()

    const myChartes = echarts.init(rms)
    const echartsColor = {
        WordColor: '#000',
        thread: '#000',
        FigureColor: [
            '#07CCCA ',
            '#00BFF5',
            '#FFBF00',
            '#77DA63',
            '#D5FF6B',
            '#Ff6600',
            '#FF9100',
            '#5B6E96',
            '#66FFCC',
            '#B3B3B3',
            '#FF00FF',
            '#CC00FF',
            '#FF9999'
        ]
    }

    setTimeout(() => {
        rms.style.width = '100%'
        rms.style.height = vh.value
    }, 0)

    const option = {
        tooltip: {
            top: '10px',
            trigger: 'axis',
            borderColor: 'grey',
            formatter: function (params: any) {
                let tips = '时刻:' + params[0].data[0] + '</br/>'
                for (let i = 0; i < params.length; i++) {
                    if (params[i].seriesName != '暂降触发点') {
                        tips +=
                            params[i].marker +
                            params[i].seriesName +
                            ':' +
                            (params[i].value[1] - 0).toFixed(2) +
                            '<br/>'
                    }
                }
                return tips
            },
            textStyle: {
                color: '#fff',
                fontStyle: 'normal',
                opacity: 0.35,
                fontSize: 14
            },
            backgroundColor: 'rgba(0,0,0,0.55)',
            borderWidth: 0
        },
        title: {
            left: 'center',
            text: titleText,
            subtitle: {
                text: '电压',
                align: 'left'
            },
            textStyle: {
                fontSize: '16px',
                color: props.DColor ? '#000' : echartsColor.WordColor
            }
        },
        legend: {
            right: 50,
            top: 25,
            verticalAlign: 'top',
            enabled: true,
            itemDistance: 5,
            textStyle: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                rich: { a: { verticalAlign: 'middle' } },
                padding: [0, 0, 0, 0]
            }
        },
        toolbox: {
            right: 20,
            top: 15,
            feature: {
                myCustomDownload: {
                    title: '',
                    icon: 'path://M892.342857 463.238095l-73.142857-68.266666-258.438095 258.438095V29.257143h-97.52381v624.152381L204.8 394.971429 131.657143 463.238095l380.342857 380.342857zM107.27619 897.219048h804.571429v97.523809H107.27619z',
                    onclick: () => download()
                }
            }
        },
        xAxis: {
            type: 'value',
            name: '时间\n(ms)',
            min: props.wp?.listRmsData[0][0] || 0,
            max: props.wp?.listRmsData[props.wp?.listRmsData.length - 1][0] + 1 || 1,
            boundaryGap: false,
            title: {
                text: 'ms',
                textStyle: {
                    fontSize: '12px',
                    color: props.DColor ? '#000' : echartsColor.WordColor
                },
                enabled: true,
                align: 'high'
            },
            nameTextStyle: { fontSize: '12px' },
            labels: {
                formatter: function () {
                    return this.value
                }
            },
            splitLine: { show: false },
            axisTick: { alignWithLabel: true },
            axisLine: {
                lineStyle: {
                    color: props.DColor ? '#000' : echartsColor.thread
                },
                onZero: false
            },
            axisLabel: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                formatter: function (value: number) {
                    if (valA.value != (value - 0).toFixed(0)) {
                        valA.value = Number((value - 0).toFixed(0))
                        return (value - 0).toFixed(0)
                    }
                    return ''
                }
            }
        },
        yAxis: {
            type: 'value',
            name: unit,
            title: {
                align: 'high',
                offset: 0,
                text: unit,
                rotation: 0,
                y: -10
            },
            // max: rmscm[0]?.[1] * 1.06 || 0,
            // min: rmscu[0]?.[1] - rmscu[0]?.[1] * 0.2 || 0,
            max: yRange.max,
            min: yRange.min,
            boundaryGap: [0, '100%'],
            showLastLabel: true,
            opposite: false,
            nameTextStyle: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: props.DColor ? '#000' : echartsColor.thread
                },
                onZero: false
            },
            axisLabel: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                formatter: function (value: number) {
                    return formatAxisLabel(value)
                }
            },
            splitLine: {
                lineStyle: {
                    color: [props.DColor ? '#000' : echartsColor.thread],
                    type: 'dashed',
                    opacity: 0.5
                }
            }
        },
        grid: {
            left: '60px',
            right: '45px',
            bottom: '40px',
            top: '60px'
            // containLabel: true
        },
        dataZoom: [
            {
                type: 'inside',
                height: 13,
                start: 0,
                bottom: '20px',
                end: 100
            },
            {
                start: 0,
                height: 13,
                bottom: '20px',
                end: 100
            }
        ],
        series: [
            {
                name: a,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#DAA520' },
                data: radata
            },
            {
                name: b,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#2E8B57' },
                data: rbdata
            },
            {
                name: c,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#A52a2a' },
                data: rcdata
            },
            {
                name: '暂降触发点',
                type: 'scatter',
                symbol: 'image://' + url,
                itemStyle: { width: 18, height: 18 },
                data: rmscu
            },
            {
                name: '最小暂降(骤升)幅值',
                type: 'scatter',
                symbol: 'image://' + url2,
                itemStyle: { width: 45, height: 45 },
                label: {
                    show: true,
                    position: [5, -20],
                    color: '#000',
                    fontSize: '12px',
                    fontWeight: 'bold',
                    borderType: 'solid',
                    borderWidth: 0.5,
                    backgroundColor: '#ffff',
                    borderColor: '#0099FF'
                },
                data: [fz.value]
            }
        ]
    }

    myChartes.setOption(option)
    myChartess.value = myChartes

    setTimeout(() => {
        myChartes.resize()
        loading.value = false
    }, 500)

    if (waveDatas && waveDatas.length > 1) {
        const waveDatasTemp = waveDatas.slice(1)
        for (let step = 0; step < waveDatasTemp.length; step++) {
            drawPics(waveDatasTemp[step], picHeight, step, show, myChartes, rmscm, rmscu, titleText)
        }
    }
}

const drawPics = (
    waveDataTemp: WaveData,
    picHeight: string,
    step: number,
    show: boolean,
    myChartes1: echarts.ECharts,
    rmscm: number[][],
    rmscu: number[][],
    title: string
) => {
    step = step + 1
    const rmsId = 'rms' + step
    let a = '',
        b = '',
        c = ''
    let unit = ''
    let radata: number[][] = [],
        rbdata: number[][] = [],
        rcdata: number[][] = []

    switch (iphasic.value) {
        case 1:
            a = waveDataTemp.title.aTitle
            break
        case 2:
            a = waveDataTemp.title.aTitle
            b = waveDataTemp.title.bTitle
            break
        case 3:
            a = waveDataTemp.title.aTitle
            b = waveDataTemp.title.bTitle
            c = waveDataTemp.title.cTitle
            break
    }

    if (props.value === 1) {
        radata = waveDataTemp.RMSFWave.rmsFA
        rbdata = waveDataTemp.RMSFWave.rmsFB
        rcdata = waveDataTemp.RMSFWave.rmsFC
    } else {
        radata = waveDataTemp.RMSSWave.rmsSA
        rbdata = waveDataTemp.RMSSWave.rmsSB
        rcdata = waveDataTemp.RMSSWave.rmsSC
    }

    if (waveDataTemp.title.unit === '电压') {
        unit = props.value === 1 ? 'kV' : 'V'
    } else {
        unit = 'A'
    }

    let titlename = ''
    if (props.boxoList.systemType == 'ZL') {
        const str = rmsId.split('s')
        const str1 = Number(str[1])

        props.wp.channelNames.forEach((element: string, i: number) => {
            if (i == 4 || i == 7 || i == 10) {
                if (str1 == 1 && i == 4) {
                    const s = element.split('A')
                    const s1 = s[0] == 'LI' ? '电网侧-电流' : s[0] + '侧' + s[1]
                    titlename = s1 + '    ' + title
                }
                if (str1 == 2 && i == 7) {
                    const s = element.split('A')
                    const s1 = s[0] == 'SU' ? '负载侧-电压' : s[0] + '侧' + s[1]
                    titlename = s1 + '    ' + title
                }
                if (str1 == 3 && i == 10) {
                    const s = element.split('A')
                    const s1 = s[0] == 'SI' ? '负载侧-电流' : s[0] + '侧' + s[1]
                    titlename = s1 + '    ' + title
                }
            }
        })
    }

    const rmsIds = document.getElementById(rmsId)
    if (!rmsIds) return

    const subMin = props.value === 1 ? waveDataTemp.RMSF.min : waveDataTemp.RMSS.min
    const subMax = props.value === 1 ? waveDataTemp.RMSF.max : waveDataTemp.RMSS.max
    const yRange = calcRmsYAxisRange(subMin, subMax)

    const myChartes = echarts.init(rmsIds)
    const echartsColor = {
        WordColor: '#000',
        thread: '#000',
        FigureColor: [
            '#07CCCA ',
            '#00BFF5',
            '#FFBF00',
            '#77DA63',
            '#D5FF6B',
            '#Ff6600',
            '#FF9100',
            '#5B6E96',
            '#66FFCC',
            '#B3B3B3',
            '#FF00FF',
            '#CC00FF',
            '#FF9999'
        ]
    }

    const option = {
        tooltip: {
            top: '10px',
            trigger: 'axis',
            borderColor: 'grey',
            formatter: function (params: any) {
                let tips = '时刻:' + params[0].data[0] + '</br/>'
                for (let i = 0; i < params.length; i++) {
                    if (params[i].seriesName != '暂降触发点') {
                        tips +=
                            params[i].marker +
                            params[i].seriesName +
                            ':' +
                            (params[i].value[1] - 0).toFixed(2) +
                            '<br/>'
                    }
                }
                return tips
            },
            textStyle: {
                color: '#fff',
                fontStyle: 'normal',
                opacity: 0.35,
                fontSize: 14
            },
            backgroundColor: 'rgba(0,0,0,0.55)',
            borderWidth: 0
        },
        title: {
            left: 'center',
            text: '', //titlename || title,
            textStyle: {
                fontSize: '16px',
                color: props.DColor ? '#000' : echartsColor.WordColor
            }
        },
        legend: {
            right: 50,
            top: 25,
            verticalAlign: 'top',
            enabled: true,
            itemDistance: 5,
            textStyle: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                rich: { a: { verticalAlign: 'middle' } },
                padding: [0, 0, 0, 0]
            }
        },
        xAxis: {
            type: 'value',
            name: '时间\n(ms)',
            min: props.wp.listRmsData[0][0],
            max: props.wp.listRmsData[props.wp.listRmsData.length - 1][0] + 1,
            boundaryGap: false,
            title: {
                text: 'ms',
                textStyle: {
                    fontSize: '12px',
                    color: props.DColor ? '#000' : echartsColor.WordColor
                },
                enabled: true,
                align: 'high'
            },
            labels: {
                formatter: function () {
                    return this.value
                }
            },
            nameTextStyle: { fontSize: '12px' },
            splitLine: { show: false },
            axisTick: { alignWithLabel: true },
            axisLine: {
                lineStyle: {
                    color: props.DColor ? '#000' : echartsColor.thread
                },
                onZero: false
            },
            axisLabel: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                formatter: function (value: number) {
                    if (valB.value != (value - 0).toFixed(0)) {
                        valB.value = Number((value - 0).toFixed(0))
                        return (value - 0).toFixed(0)
                    }
                    return ''
                }
            }
        },
        yAxis: {
            type: 'value',
            name: unit,
            title: {
                align: 'high',
                offset: 0,
                text: unit,
                rotation: 0,
                y: -10
            },
            boundaryGap: [0, '100%'],
            showLastLabel: true,
            max: yRange.max,
            min: yRange.min,
            opposite: false,
            // max: Math.floor((rmscm[0]?.[1] * 1.06 || 0) * 1.1 * 10) / 10,
            // min: Math.floor((rmscu[0]?.[1] - rmscu[0]?.[1] * 0.2 || 0) * 10) / 10,
            nameTextStyle: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: props.DColor ? '#000' : echartsColor.thread
                },
                onZero: false
            },
            axisLabel: {
                fontSize: '12px',
                color: props.DColor ? '#000' : echartsColor.WordColor,
                formatter: function (value: number) {
                    return formatAxisLabel(value)
                }
            },
            splitLine: {
                lineStyle: {
                    color: [props.DColor ? '#000' : echartsColor.thread],
                    type: 'dashed',
                    opacity: 0.5
                }
            }
        },
        grid: {
            left: '60px',
            right: '45px',
            bottom: '40px',
            top: '60px'
            // containLabel: true
        },
        dataZoom: [
            {
                type: 'inside',
                height: 13,
                start: 0,
                bottom: '20px',
                end: 100
            },
            {
                start: 0,
                height: 13,
                bottom: '20px',
                end: 100
            }
        ],
        series: [
            {
                name: a,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#DAA520' },
                data: radata
            },
            {
                name: b,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#2E8B57' },
                data: rbdata
            },
            {
                name: c,
                type: 'line',
                smooth: true,
                symbol: 'none',
                sampling: 'average',
                itemStyle: { color: '#A52a2a' },
                data: rcdata
            }
        ]
    }

    myChartes.setOption(option)

    switch (step) {
        case 1:
            myChartess1.value = myChartes
            break
        case 2:
            myChartess2.value = myChartes
            break
        case 3:
            myChartess3.value = myChartes
            break
        case 4:
            myChartess4.value = myChartes
            break
        case 5:
            myChartess5.value = myChartes
            break
    }

    setTimeout(() => {
        myChartes.resize()
        loading.value = false
    }, 500)

    echarts.connect([myChartes1, myChartes])
}

const backbxlb = () => {
    waveDatas.value = []
    const charts = [
        myChartess.value,
        myChartess1.value,
        myChartess2.value,
        myChartess3.value,
        myChartess4.value,
        myChartess5.value
    ]

    charts.forEach(chart => {
        if (chart) {
            chart.dispose()
        }
    })

    myChartess.value = null
    myChartess1.value = null
    myChartess2.value = null
    myChartess3.value = null
    myChartess4.value = null
    myChartess5.value = null

    $('#rmsp').nextAll(`.${EXTRA_PANEL_CLASS}`).remove()
}

const getMax = (temp: number, tempA: number, tempB: number, tempC: number): number => {
    temp = temp > tempA ? temp : tempA
    temp = temp > tempB ? temp : tempB
    temp = temp > tempC ? temp : tempC
    return temp
}

const getMaxTwo = (temp: number, tempA: number, tempB: number): number => {
    temp = temp > tempA ? temp : tempA
    temp = temp > tempB ? temp : tempB
    return temp
}

const getMin = (temp: number, tempA: number, tempB: number, tempC: number): number => {
    temp = temp < tempA ? temp : tempA
    temp = temp < tempB ? temp : tempB
    temp = temp < tempC ? temp : tempC
    return temp
}

const getMinOpen = (temp: number, tempA: number, tempB: number): number => {
    temp = temp < tempA ? temp : tempA
    temp = temp < tempB ? temp : tempB
    return temp
}
</script>
