<template>
    <div class="pt50">
        <el-button class="shutDown" icon="el-icon-Back" @click="emit('shutDown')">返回</el-button>
        <div class="select">
            <el-form :model="searchForm" id="history_select">
                <el-form-item label="稳态指标">
                    <el-select
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        v-model.trim="searchForm.index"
                        placeholder="请选择统计指标"
                        :multiple-limit="3"
                        value-key="id"
                        @change="change"
                        filterable
                    >
                        <el-option
                            v-for="(item, index) in indexOptions"
                            :label="item.name"
                            :key="index"
                            :value="item"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <div v-loading="loading" id="trend">
            <div :style="height" v-for="(item, index) in searchForm.index" :key="index">
                <MyEchart ref="MyEchartRef" :options="item.echartsData" :isInterVal="true"   @group="group"></MyEchart>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import MyEchart from '@/components/echarts/MyEchart.vue'
import { mainHeight } from '@/utils/layout'
import { timeFormat } from '@/utils/common'
import { useConfig } from '@/stores/config'
import { yMethod } from '@/utils/echartMethod'
import html2canvas from 'html2canvas'
import * as echarts from 'echarts' // 全引入
const config = useConfig()
const props = defineProps({
    ptName: {
        type: String
    }
})
const loading = ref(true)
const emit = defineEmits(['shutDown'])
const searchForm: any = ref({ index: [] })
const timeList = ref([])
const MyEchartRef = ref()
const height = ref(mainHeight(150, 2))
//统计指标
const indexOptions: any = ref([
    {
        id: 0,
        name: '电压总有效值(kV)',
        children: [
            { name: 'vRmsA', phase: props.ptName == 'star' ? 'A相' : 'AB相', data: [] },
            { name: 'vRmsB', phase: props.ptName == 'star' ? 'B相' : 'BC相', data: [] },
            { name: 'vRmsC', phase: props.ptName == 'star' ? 'C相' : 'CA相', data: [] }
        ],
        color: ['#DAA520', '#2E8B57', '#A52a2a'],
        unit: 'kV',
        data: []
    },
    {
        id: 1,
        name: '电流总有效值(A)',
        children: [
            { name: 'iRmsA', phase: 'A相', data: [] },
            { name: 'iRmsB', phase: 'B相', data: [] },
            { name: 'iRmsC', phase: 'C相', data: [] }
        ],
        color: ['#DAA520', '#2E8B57', '#A52a2a'],
        unit: 'A',
        data: []
    },
    {
        id: 2,
        name: '有功功率(kW)',
        children:
            props.ptName == 'star'
                ? [
                      { name: 'pA', phase: 'A相', data: [] },
                      { name: 'pB', phase: 'B相', data: [] },
                      { name: 'pC', phase: 'C相', data: [] },
                      { name: 'pTot', phase: '总', data: [] }
                  ]
                : [{ name: 'pTot', phase: '总', data: [] }],
        color: props.ptName == 'star' ? ['#DAA520', '#2E8B57', '#A52a2a', '#000'] : ['#000'],
        unit: 'kW',
        data: []
    },
    {
        id: 3,
        name: '无功功率(kW)',
        children:
            props.ptName == 'star'
                ? [
                      { name: 'qA', phase: 'A相', data: [] },
                      { name: 'qB', phase: 'B相', data: [] },
                      { name: 'qC', phase: 'C相', data: [] },
                      { name: 'qTot', phase: '总', data: [] }
                  ]
                : [{ name: 'qTot', phase: '总', data: [] }],
        color: props.ptName == 'star' ? ['#DAA520', '#2E8B57', '#A52a2a', '#000'] : ['#000'],
        unit: 'kW',
        data: []
    },

    {
        id: 4,
        name: '基波电压总有效值(kV)',
        children: [
            { name: 'v1A', phase: props.ptName == 'star' ? 'A相' : 'AB相', data: [] },
            { name: 'v1B', phase: props.ptName == 'star' ? 'B相' : 'BC相', data: [] },
            { name: 'v1C', phase: props.ptName == 'star' ? 'C相' : 'CA相', data: [] }
        ],
        color: ['#DAA520', '#2E8B57', '#A52a2a'],
        unit: 'kV',
        data: []
    },
    {
        id: 5,
        name: '基波电流总有效值(A)',
        children: [
            { name: 'i1A', phase: 'A相', data: [] },
            { name: 'i1B', phase: 'B相', data: [] },
            { name: 'i1C', phase: 'C相', data: [] }
        ],
        color: ['#DAA520', '#2E8B57', '#A52a2a'],
        unit: 'A',
        data: []
    },
    {
        id: 6,
        name: '频率(Hz)',
        children: [
            { name: 'freq', phase: '频率', data: [] },
            { name: 'freqDev', phase: '频率偏差', data: [] }
        ],
        color: [config.layout.elementUiPrimary[0], '#00BFF5'],
        unit: 'Hz',
        data: []
    },
    {
        id: 7,
        name: '电压不平衡度(%)',
        children: [{ name: 'vUnbalance', phase: '电压不平衡度', data: [] }],
        color: [config.layout.elementUiPrimary[0]],
        unit: '%',
        data: []
    },
    {
        id: 8,
        name: '电流不平衡度(%)',
        children: [{ name: 'iUnbalance', phase: '电流不平衡度', data: [] }],
        color: [config.layout.elementUiPrimary[0]],
        unit: '%',
        data: []
    }
])
const group = (e: any) => {
    e.group = 'group'
}
const change = () => {
    height.value = mainHeight(150, searchForm.value.index.length)
    // let name = searchForm.value.index.map(item => item.name)
    // let list = indexOptions.value.filter(item => !name.includes(item.name))
    loading.value = true
    searchForm.value.index.forEach((item: any) => {
        item.echartsData.xAxis.data = []
        item.echartsData.series.forEach((child: any) => {
            child.data = []
        })
    })

    // console.log("🚀 ~ change ~ MyEchartRef.value[0]?.getChart():", MyEchartRef.value[0]?.getChart())
}
onMounted(() => {
    setEcharts()
    searchForm.value.index.push(...[indexOptions.value[0], indexOptions.value[1]])
})
const init = (row: any) => {
    // timeList.value.push(timeFormat(row.TIME - 0))
    searchForm.value.index.forEach((item: any, index: any) => {
        // item.echartsData.xAxis.data.push(timeFormat(row.TIME - 0))
        let time = timeFormat(row.TIME - 0)
        switch (item.name) {
            case '电压总有效值(kV)':
                item.echartsData.series[0].data.push([
                    time,
                    Math.floor((props.ptName == 'star' ? row.V.A?.VRMS : row.V.A?.VRMS_LVR) * 100) / 100
                ])
                item.echartsData.series[1].data.push([
                    time,
                    Math.floor((props.ptName == 'star' ? row.V.B?.VRMS : row.V.B?.VRMS_LVR) * 100) / 100
                ])
                item.echartsData.series[2].data.push([
                    time,
                    Math.floor((props.ptName == 'star' ? row.V.C?.VRMS : row.V.C?.VRMS_LVR) * 100) / 100
                ])
                break
            case '电流总有效值(A)':
                item.echartsData.series[0].data.push([time, Math.floor(row.I.A?.IRMS * 100) / 100])
                item.echartsData.series[1].data.push([time, Math.floor(row.I.B?.IRMS * 100) / 100])
                item.echartsData.series[2].data.push([time, Math.floor(row.I.C?.IRMS * 100) / 100])
                break
            case '有功功率(kW)':
                if (props.ptName == 'star') {
                    item.echartsData.series[0].data.push([time, Math.floor(row.PQ.A?.P * 100) / 100])
                    item.echartsData.series[1].data.push([time, Math.floor(row.PQ.B?.P * 100) / 100])
                    item.echartsData.series[2].data.push([time, Math.floor(row.PQ.C?.P * 100) / 100])
                    item.echartsData.series[3].data.push([time, Math.floor(row.PQ.T?.P * 100) / 100])
                } else {
                    item.echartsData.series[0].data.push([time, Math.floor(row.PQ.T?.P * 100) / 100])
                }

                break
            case '无功功率(kW)':
                if (props.ptName == 'star') {
                    item.echartsData.series[0].data.push([time, Math.floor(row.PQ.A?.Q * 100) / 100])
                    item.echartsData.series[1].data.push([time, Math.floor(row.PQ.B?.Q * 100) / 100])
                    item.echartsData.series[2].data.push([time, Math.floor(row.PQ.C?.Q * 100) / 100])
                    item.echartsData.series[3].data.push([time, Math.floor(row.PQ.T?.Q * 100) / 100])
                } else {
                    item.echartsData.series[0].data.push([time, Math.floor(row.PQ.T?.Q * 100) / 100])
                }

                break
            case '基波电压总有效值(kV)':
                item.echartsData.series[0].data.push([time, Math.floor(row.V.A?.V1 * 100) / 100])
                item.echartsData.series[1].data.push([time, Math.floor(row.V.B?.V1 * 100) / 100])
                item.echartsData.series[2].data.push([time, Math.floor(row.V.C?.V1 * 100) / 100])
                break
            case '基波电流总有效值(A)':
                item.echartsData.series[0].data.push([time, Math.floor(row.I.A?.I1 * 100) / 100])
                item.echartsData.series[1].data.push([time, Math.floor(row.I.B?.I1 * 100) / 100])
                item.echartsData.series[2].data.push([time, Math.floor(row.I.C?.I1 * 100) / 100])
                break
            case '频率(Hz)':
                item.echartsData.series[0].data.push([time, Math.floor(row.V.T?.FREQ * 100) / 100])
                item.echartsData.series[1].data.push([time, Math.floor(row.V.T?.DELTA_FREQ * 100) / 100])
                break
            case '电压不平衡度(%)':
                item.echartsData.series[0].data.push([time, Math.floor(row.V.T?.V_UNBAN * 100) / 100])

                break
            case '电流不平衡度(%)':
                item.echartsData.series[0].data.push([time, Math.floor(row.I.T?.I_UNBAN * 100) / 100])
                break
        }
        item.echartsData.series.forEach((item1: any) => {
            if (item1.data.length > 60) {
                item1.data.shift()
            }
        })

        let [min, max] = yMethod([].concat(...item.echartsData.series.map(k => k.data).map(k1 => k1.map(k2 => k2[1]))))
        item.echartsData.yAxis.min = min
        item.echartsData.yAxis.max = max
    })

    MyEchartRef.value[0]?.setOptions(searchForm.value.index[0].echartsData)
    MyEchartRef.value[1]?.setOptions(searchForm.value.index[1].echartsData)
    MyEchartRef.value[2]?.setOptions(searchForm.value.index[2].echartsData)
    if (loading.value) {
        echarts.connect('group')
    }

    loading.value = false
}
const setEcharts = () => {
    indexOptions.value.forEach((item: any, index: any) => {
        item.echartsData = {
            title: {
                text: item.name
            },

            xAxis: {
                name: '时间',
                type: 'time',
                axisLabel: {
                    interval: 0, // 强制显示所有标签
                    formatter: {
                        day: '{MM}-{dd}',
                        month: '{MM}',
                        year: '{yyyy}'
                    }
                },

                data: []
            },

            yAxis: {
                // type: 'value',
                name: item.unit,
                splitNumber: 5,
                minInterval: 1,
                alignTicks: true // 强制对齐刻度
            },
            toolbox: {
                right: 20,
                top: 15,
                show: index == 0 ? true : false,
                feature: {
                    // 移除默认的 saveAsImage
                    // saveAsImage: { title: '保存图片' }
                    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: function () {
                            html2canvas(document.getElementById('trend'), {
                                scale: 1
                            }).then(function (canvas) {
                                // 创建a标签，实现下载
                                let creatIMg = document.createElement('a')
                                creatIMg.download = '实时趋势.png' // 设置下载的文件名，
                                creatIMg.href = canvas.toDataURL() // 下载url
                                creatIMg.click()
                                creatIMg.remove() // 下载之后把创建的元素删除
                            })
                        }
                    }
                }
            },

            tooltip: {
                axisPointer: {
                    type: 'cross',
                    label: {
                        color: '#fff',
                        fontSize: 16
                    }
                },
                textStyle: {
                    color: '#fff',
                    fontStyle: 'normal',
                    opacity: 0.35,
                    fontSize: 14
                },
                backgroundColor: 'rgba(0,0,0,0.55)',
                borderWidth: 0,
                formatter(params: any) {
                  
                    const xname = params[0].value[0]
                    let str = `${xname}<br>`
                    params.forEach((el: any, index: any) => {
                        let marker = ''

                        // if (el.value[3] == 'dashed') {
                        //     for (let i = 0; i < 3; i++) {
                        //         marker += `<span style="display:inline-block;border: 2px ${el.color} solid;margin-right:5px;width:10px;height:0px;background-color:#ffffff00;"></span>`
                        //     }
                        // } else {
                        //     marker = `<span style="display:inline-block;border: 2px ${el.color} ${el.value[3]};margin-right:5px;width:40px;height:0px;background-color:#ffffff00;"></span>`
                        // }
                        str += `${el.marker} ${el.seriesName.split('(')[0]}：${
                            el.value[1] ? el.value[1] + ' ' + (el.value[2] || '') : '-'
                        }<br>`
                    })
                    return str
                }
            },
            series: []
        }
        item.children.map((zz: any, zzIndex: any) => {
            item.echartsData.series.push({
                name: zz.phase,
                type: 'line',
                increment: true,
                itemStyle: {
                    barBorderRadius: [3, 3, 0, 0],
                    color: [...item.color][zzIndex]
                },
                data: [],
                smooth: true, // 这里设置平滑曲线
                symbol: 'none' // 设置为 'none' 去掉折点小圆
            })
        })
    })
}
onBeforeUnmount(() => {
    echarts.disconnect('group')
})
defineExpose({
    init
})
</script>
<style lang="scss" scoped>
.shutDown {
    position: absolute;
    right: 10px;
    top: 10px;
}
.select {
    position: absolute;
    top: 10px;
    display: flex;
    align-items: center;
    font-size: 14px;
}
</style>
