<!-- 实时数据 - 谐波频谱页面 -->
<template>
    <div class="realtrend" v-loading="loading">
        <div class="select" v-if="!loading && !isInterharmonicTab">
            <div class="mr10">谐波次数</div>
            <el-select v-model.trim="selectValue" style="width: 100px" @change="selectChange">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div>
        <el-tabs type="border-card" v-if="tabsList.length != 0" v-model.trim="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="(item, index) in tabsList" :label="item.groupName" :name="index" :key="index">
                <div>
                    <div class="realtrend_top">
                        <!-- <div class="thead">
                            <ul v-for="(table, tableIndex) in newTableList" :key="tableIndex">
                                <li>
                                    {{ table[0].value }}
                                </li>
                            </ul>
                        </div>
                        <div class="table">
                            <ul v-for="(table, tableIndex) in newTableList" :key="tableIndex">
                                <span v-for="(key, keys) in table">
                                    <li v-if="keys != 0">
                                        {{ key?.value }}
                                    </li> 
                                </span>
                            </ul>
                        </div> -->
                        <div class="realtrend_table" v-if="Object.keys(tableData).length != 0">
                            <div class="thead_left">
                                <p style="font-weight: 700; background-color: #f3f6f9">
                                    {{ isInterharmonicTab ? '间谐波次数(次)' : '谐波次数(次)' }}
                                </p>
                                <p>{{ item.groupName }}{{ item.unit ? '(' + item.unit + ')' : '' }}</p>
                                <!-- <p>国标限值{{ item.unit ? '(' + item.unit + ')' : '' }}</p> -->
                            </div>
                            <div class="thead_right">
                                <div class="right_cell" v-for="(value, key, index) in tableData" :key="index">
                                    <p v-if="isInterharmonicTab" style="background-color: #f3f6f9">
                                        {{ getHarmonicOrder(key, true) }}
                                    </p>
                                    <p v-else style="background-color: #f3f6f9">
                                        <span>{{ getHarmonicOrder(key) }}</span>
                                    </p>
                                    <p>
                                        <span
                                            v-if="
                                                String(key).includes('data') &&
                                                String(key) != 'dataLevel' &&
                                                String(key) != 'dataTime'
                                            "
                                        >
                                            {{ value }}
                                        </span>
                                    </p>
                                    <!-- <p>
                                        <span v-if="
                                            String(key).includes('data') &&
                                            String(key) != 'dataLevel' &&
                                            String(key) != 'dataTime'
                                        ">
                                            {{ gbData[index]?.value || '/' }}
                                        </span>
                                    </p> -->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="tab_info" v-if="Object.keys(tableData).length != 0">
                        <div class="charts">
                            <MyEchart ref="barCharts" :options="echartsData" :isInterVal="true"></MyEchart>
                        </div>
                    </div>
                    <el-empty v-else style="margin: 0 auto" />
                </div>
            </el-tab-pane>
        </el-tabs>
        <!-- <el-empty v-else/> -->
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { VxeGridProps } from 'vxe-table'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import MyEchart from '@/components/echarts/MyEchart.vue'
const activeName = ref(0)
const emit = defineEmits(['changeTrendType'])
const tableList: any = []
const selectValue = ref('3')

const getHarmonicOrder = (key: string | number, interharmonic = false) => {
    const order = Number(String(key).replace('data', ''))
    return interharmonic ? order - 0.5 : order
}

const options = [
    {
        value: '3',
        label: '全部'
    },

    {
        value: '1',
        label: '奇次'
    },
    {
        value: '2',
        label: '偶次'
    }
]
interface RowVO {
    [key: string]: any
}
//谐波电压含有率
const gridOptions = ref<VxeGridProps<RowVO>>({
    border: true,
    showOverflow: true,
    showHeader: false,
    columns: [],
    data: [],
    columnConfig: {
        resizable: true
    },
    align: 'center'
})
gridOptions.value = { ...defaultAttribute, ...gridOptions.value }

const tabsList: any = ref([
    {
        id: '6d5470f509ca271d7108a86e83bb283f',
        groupName: '谐波电压含有率',
        thdDataVOS: null,
        thdDataTdVODatas: null,
        unit: '%'
    },
    {
        id: '8dc260f16280184e2b57d26668dc00b1',
        groupName: '谐波电流幅值',
        thdDataVOS: null,
        thdDataTdVODatas: null,
        unit: 'A'
    },
    {
        id: 'ae31115b83f02f03a0d3bd65cb017121',
        groupName: '间谐波电压含有率',
        thdDataVOS: null,
        thdDataTdVODatas: null,
        unit: '%'
    }
])
const isInterharmonicTab = computed(() => {
    return tabsList.value[activeName.value]?.groupName?.includes('间谐波')
})
const loading: any = ref(true)
//接收参数
const params = ref({})
const open = async (val: any) => {
    loading.value = true
    //获取指标tab
    // tabsList.value = [
    //     {
    //         id: '6d5470f509ca271d7108a86e83bb283f',
    //         groupName: '谐波电压含有率',
    //         thdDataVOS: null,
    //         thdDataTdVODatas: null,
    //         unit: '%'
    //     },
    //     {
    //         id: '8dc260f16280184e2b57d26668dc00b1',
    //         groupName: '谐波电流幅值',
    //         thdDataVOS: null,
    //         thdDataTdVODatas: null,
    //         unit: 'A'
    //     },
    //     {
    //         id: 'ae31115b83f02f03a0d3bd65cb017121',
    //         groupName: '间谐波电压含有率',
    //         thdDataVOS: null,
    //         thdDataTdVODatas: null,
    //         unit: '%'
    //     }
    // ]
    if (tabsList.value.length != 0) {
        // activeName.value = tabsList.value[0]?.id
        activeName.value = val.activeTrendName || 0
    }
    params.value = { groupId: tabsList.value[activeName.value]?.id, ...val }
    init()

    // setTimeout(() => {
    //     loading.value = false
    // }, 1500)
    return
}
//根据指标tab查询实时趋势
//echarts数据
const chartsData: any = ref([])
const chartsYxiasData: any = ref([])

const echartsData: any = ref()
const barCharts = ref()
const gbData = ref([])
//加载echarts
const init = () => {
    let trendData: any = []
    for (let key in tableData.value) {
        trendData.push({
            name: key,
            value: tableData.value[key],
            count: String(key).replace('data', '')
        })
    }
    gbData.value = []
    for (let key in limitData.value) {
        gbData.value.push({
            name: key,
            value: limitData.value[key]
        })
    }
    if (!isInterharmonicTab.value && selectValue.value == '1') {
        gbData.value = gbData.value.filter((_, index: number) => index % 2 !== 0)
    } else if (!isInterharmonicTab.value && selectValue.value == '2') {
        gbData.value = gbData.value.filter((_, index: number) => index % 2 == 0)
    }
    let xAxisList: any = []
    chartsData.value.map((item: any, index: any) => {
        chartsYxiasData.value.map((vv: any, vvs: any) => {
            if (item.phase == vv.phase) {
                if (vvs == 0) {
                    vv.gbList.push(item.internationalValue)
                }
                vv.phaseList.push(item.statisticalData)
            }
        })
        xAxisList.push(item.frequency + '次')
    })
    xAxisList = [...new Set(xAxisList)]
    echartsData.value = {
        color: ['#2E8B57', '#DAA520'],
        xAxis: {
            name: isInterharmonicTab.value ? '间谐波次数' : '谐波次数',
            data: trendData.map((item: any) => {
                const count = isInterharmonicTab.value ? item.count - 0.5 : item.count
                return `${count}次`
            })
        },
        yAxis: {
            name: tabsList.value[activeName.value].unit
        },
        series: []
    }
    let list: any = [
        trendData.map((item: any) => {
            return item.value
        })
        // gbData.value.map((item: any) => {
        //     return item.value
        // }),
    ]
    let legendList = [tabsList.value[activeName.value]?.groupName]
    // let legendList = [tabsList.value[activeName.value]?.groupName, '国标限值',]
    // echartsData.value.legend.data = legendList
    list.map((item: any, index: any) => {
        echartsData.value.series.push({
            name: legendList[index],
            type: 'bar',
            data: item
        })
    })
    if (barCharts.value) {
        barCharts.value[activeName.value]?.initChart()
        loading.value = false
    } else {
        loading.value = true
    }
    return
}


const handleClick = (tab: any, event: any) => {
    tableData.value = []
    echartsData.value = {}
    loading.value = true
    params.value.groupId = tabsList.value[tab.index].id
    emit('changeTrendType', tab.index)
    activeName.value = tab.index
    init()
}
//获取mqtt传送的实时数据
const mqttMessage: any = ref()
const tableData: any = ref({})
const shouldIncludeHarmonicData = (numberPart: number) => {
    if (isInterharmonicTab.value) {
        return numberPart < 17
    }
    if (selectValue.value === '3') {
        return true
    }
    if (selectValue.value === '2') {
        return numberPart % 2 === 0
    }
    return numberPart % 2 !== 0
}

const setRealTrendData = (val: any) => {
    mqttMessage.value = {}
    if (!val) {
        loading.value = false
        return
    }
    loading.value = true
    tableData.value = {}
    mqttMessage.value = val
    for (let key in val) {
        if (String(key).includes('data') && String(key) != 'dataLevel' && String(key) != 'dataTime') {
            const numberPart = parseInt(key.replace('data', ''))
            if (shouldIncludeHarmonicData(numberPart)) {
                tableData.value[key] = val[key].toFixed(2)
            }
        }
    }

    if (!isInterharmonicTab.value) {
        delete tableData.value.data1
    }
    if (Object.keys(tableData.value).length != 0) {
        init()
        loading.value = false
    } else {
        emit('changeTrendType', activeName.value)
    }
}
const selectChange = () => {
    if (isInterharmonicTab.value) return
    if (mqttMessage.value && Object.keys(mqttMessage.value).length) {
        setRealTrendData(mqttMessage.value)
    }
}
//获取国标限值
const limitData: any = ref()
const setOverLimitData = (val: any) => {
    // limitData.value = {}
    // for (let key in val) {
    //     if (activeName.value == 0) {
    //         if (String(key).includes('uharm')) {
    //             if (key.startsWith('uharm')) {
    //                 limitData.value[key] = val[key]
    //             }
    //         }
    //     } else if (activeName.value == 1) {
    //         if (String(key).includes('iharm')) {
    //             limitData.value[key] = val[key]
    //         }
    //     } else {
    //         if (String(key).includes('inuharm')) {
    //             limitData.value[key] = val[key]
    //         }
    //     }
    // }
}
onMounted(() => {})
defineExpose({ open, setRealTrendData, setOverLimitData })
</script>
<style lang="scss" scoped>
.realtrend {
    width: 100%;
    height: 100%;
    position: relative;

    .select {
        position: absolute;
        top: -36px;
        display: flex;
        align-items: center;
        font-size: 14px;
    }

    .realtrend_top {
        width: 100%;
        height: auto;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table {
            flex: 1;
            // min-height: 80px;
            cursor: pointer;
            min-height: 90px;
            max-height: 170px;
            border: 1px solid #eee;
            overflow-x: auto;
            overflow-y: hidden;
            position: relative;

            ul {
                width: auto;
                height: 40px;
                display: flex;

                li {
                    flex: none;
                    width: 100px;
                    line-height: 40px;
                    border: 1px solid #eee;
                    text-align: center;
                    list-style: none;
                }
            }

            ul:nth-child(1) {
                li {
                    font-weight: 800;
                    background: #f4f6f9;
                }
            }
        }

        // .table::-webkit-scrollbar {
        //     display: none;
        // }

        .realtrend_table {
            width: 100%;
            height: auto;
            max-height: 150px;
            display: flex;
            border: 2px solid #eee;
            cursor: pointer;
            font-size: 13px;

            .thead_left {
                width: 150px;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                align-items: center;
                line-height: 50px;

                padding-bottom: 5px;

                p {
                    width: 100%;
                    height: 100%;
                    text-align: center;
                    border: 1px solid #eee;
                    line-height: 38px;
                    margin: 0 !important;
                }
            }

            .thead_right {
                flex: 1;
                align-items: center;
                overflow-x: auto;
                overflow-y: hidden;
                display: flex;
                padding-bottom: 5px;

                .right_cell {
                    width: 100%;
                    display: flex;
                    flex-direction: column;

                    p {
                        flex: none;
                        min-width: 60px;
                        height: 100%;
                        text-align: center;
                        border: 1px solid #eee;
                        line-height: 38px;
                        margin: 0 !important;
                    }

                    p:nth-child(1) {
                        font-weight: 800;
                    }
                }
            }
        }
    }
}

.reverse-table .vxe-body--row .vxe-body--column:first-child {
    background-color: #f8f8f9;
}

::v-deep .vxe-table--render-wrapper {
    height: 90px !important;
    max-height: 90px !important;
    overflow-x: auto !important;
    min-height: 0 !important;
}

::v-deep .body--wrapper {
    height: 90px !important;
    max-height: 90px !important;
    min-height: 0 !important;
}

.tab_info {
    width: 100%;

    // height: calc(100vh - 450px);
    // overflow: auto;
    // padding-bottom: 20px;
    .charts {
        width: 100%;
        margin-top: 10px;
        height: calc(100vh - 535px);
    }
}

:deep(.el-select) {
    min-width: 100px;
}
</style>
