<template>
    <Cn-page :loading="loading" noPadding>
        <view slot="body">
            <view class="realTime">
                <!-- 头部卡片 -->
                <view class="info-card-wrap">
                    <view class="info-card">
                        <view class="info-item">
                            监测点名称：<view>
                                <picker @change="lineChange" @cancel="selectProject = false" :value="lineKey"
                                    :range="lineList" range-key="name">
                                    <view class="nav-menu" @click="selectProject = true">
                                        {{ lineList[lineKey].name }}

                                        <uni-icons type="bottom" size="18" color="#fff"></uni-icons>
                                    </view>
                                </picker>
                            </view>
                        </view>
                        <view class="info-item">
                            所属工程：<view>{{ device.engineeringName }}</view>
                        </view>
                        <view class="info-item">
                            所属项目：<view>{{ device.projectName }}</view>
                        </view>
                        <view class="info-item">
                            所属设备：<view>{{ device.equipmentName }}</view>
                        </view>

                        <view class="info-item status">
                            通讯状态：<view class="status-normal"
                                :style="{ color: device.runStatus == 1 ? '#ff3b30' : '#00ff88' }">{{ device.runStatus ==
                                    1 ? '离线' : '在线' }}
                            </view>
                        </view>
                    </view>
                </view>
                <view>
                    <view class="time-bar">
                        <view class="time">
                            <u-icon name="clock" size="36"></u-icon>
                            <text>{{ realTime }}</text>
                        </view>
                        <button class="mini-btn" type="primary" :disabled="disabled" size="mini" @click="handleRefresh">
                            {{ disabled ? `刷新(${countdown}s)` : '刷新' }}
                        </button>
                    </view>

                    <!-- 仪表盘 -->
                    <view>
                        <view class="chartBox">
                            <view>
                                <view class="chart">
                                    <l-echart ref="echartV1"
                                        @finished="initChart('echartV1', 'echartsDataV1')"></l-echart>
                                </view>
                                <view class="chart">
                                    <l-echart ref="echartV2"
                                        @finished="initChart('echartV2', 'echartsDataV2')"></l-echart>
                                </view>
                                <view class="chart">
                                    <l-echart ref="echartV3"
                                        @finished="initChart('echartV3', 'echartsDataV3')"></l-echart>
                                </view>
                                <view class="text" style="left: 20rpx"> 电压有效值(kV) </view>
                            </view>
                            <view class="middle" style="width: 100%">
                                <l-echart class="echart1" ref="echart0"
                                    @finished="initChart('echart0', 'echartsData0')"></l-echart>
                                <l-echart class="echart1" ref="echart1"
                                    @finished="initChart('echart1', 'echartsData1')"></l-echart>
                                <view class="text text_center"> 基波电压/电流<br />幅值(相位) </view>
                            </view>
                            <view>
                                <view class="chart">
                                    <l-echart ref="echartA1"
                                        @finished="initChart('echartA1', 'echartsDataA1')"></l-echart>
                                </view>
                                <view class="chart">
                                    <l-echart ref="echartA2"
                                        @finished="initChart('echartA2', 'echartsDataA2')"></l-echart>
                                </view>
                                <view class="chart">
                                    <l-echart ref="echartA3"
                                        @finished="initChart('echartA3', 'echartsDataA3')"></l-echart>
                                </view>
                                <view class="text" style="right: 20rpx"> 电流有效值(A) </view>
                            </view>
                        </view>
                    </view>

                    <!-- 底部指标数据 -->
                    <view class="params-wrap ">
                        <view class="legend-row mt10">
                            <view class="legend-item" v-for="phase in phaseColors" :key="phase.name">
                                <view class="legend-dot" :style="{ background: phase.color }" />
                                <text class="legend-text">{{ phase.name }}</text>
                            </view>
                        </view>
                        <view class="params-section mb40">
                            <view v-for="(rowItems, rowIdx) in chunkedChildren(realTimeData)" :key="rowIdx"
                                class="double-row">
                                <view v-for="(child, childIdx) in rowItems" :key="childIdx" class="param-group">
                                    <view class="param-title">
                                        <text>{{ child.name }}</text>
                                    </view>
                                    <view class="phase-vertical">
                                        <view class="phase-item-vertical">
                                            <text class="phase-value-vertical"
                                                :style="{ color: phaseColors[0].color }">{{ child.A }}</text>
                                        </view>
                                        <view class="phase-divider" />
                                        <view class="phase-item-vertical">
                                            <text class="phase-value-vertical"
                                                :style="{ color: phaseColors[1].color }">{{ child.B }}</text>
                                        </view>
                                        <view class="phase-divider" />
                                        <view class="phase-item-vertical">
                                            <text class="phase-value-vertical"
                                                :style="{ color: phaseColors[2].color }">{{ child.C }}</text>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <hover-menu :btnList="content" @trigger="trigger"></hover-menu>
        </view>
    </Cn-page>
</template>
<script>
const echarts = require('../../../uni_modules/lime-echart/static/echarts.min')
import { MQTT_IP, MQTT_OPTIONS } from '@/common/js/mqtt.js'
import mqtt from 'mqtt/dist/mqtt.js'
import { getBaseRealData } from '@/common/api/harmonic.js'
import hoverMenu from '@/hover-menu/components/hover-menu/hover-menu.vue'
import { queryTopologyDiagram, deleteDevice, cancelDebug, finishDebug } from '@/common/api/device'
export default {
    components: { hoverMenu },
    props: {},
    data() {
        return {
            loading: true,
            phaseColors: [
                { name: 'A相', color: '#F1B22E' },
                { name: 'B相', color: '#2BA471' },
                { name: 'C相', color: '#D54941' },
            ],
            deviceInfo: {},
            // 使用上面定义的图表配置项
            option: {},
            echartsData0: {},
            echartsData1: {},
            echartsDataV1: {},
            echartsDataV2: {},
            echartsDataV3: {},
            echartsDataA1: {},
            echartsDataA2: {},
            echartsDataA3: {},
            // 图表实例，用于后续操作
            echart0: null,
            echart1: null,
            echartV1: null,
            echartV2: null,
            echartV3: null,
            echartA1: null,
            echartA2: null,
            echartA3: null,
            ptName: 'star',
            client: null,
            timer: null,
            numTimer: null,
            userInfo: {},
            realTime: '',
            realTimeData: [
                { name: '电压有效值(kV)', A: '-', B: '-', C: '-' },
                { name: '电流有效值(A)', A: '-', B: '-', C: '-' },
                { name: '基波电压幅值(kV)', A: '-', B: '-', C: '-' },
                { name: '基波电流幅值(A)', A: '-', B: '-', C: '-' },
                { name: '基波电压相位(°)', A: '-', B: '-', C: '-' },
                { name: '基波电流相位(°)', A: '-', B: '-', C: '-' },
                { name: '电压偏差(%)', A: '-', B: '-', C: '-' },
                { name: '电压总谐波畸变率(%)', A: '-', B: '-', C: '-' },
            ],
            phaseColors: [
                { name: 'A相', color: '#F1B22E' },
                { name: 'B相', color: '#2BA471' },
                { name: 'C相', color: '#D54941' },
            ],
            disabled: false,
            countdown: 30,
            lineId: '00B78D00A87A1',
            lineKey: 0,
            lineList: [],
            connection: false,
            content: [
                {
                    iconPath: '/static/tongji.png',
                    text: '事件',
                },
                {
                    iconPath: '/static/about.png',
                    text: '详情',
                },
            ],
            device: {},
        }
    },
    onLoad(options) {
        this.device = JSON.parse(options.device)
        this.lineKey = 0
        this.lineList = this.device.lineList
        this.lineId = this.lineList[0].lineId
        this.userInfo = uni.getStorageSync(this.$cacheKey.userInfo)
        this.echartsData0 = this.initEcharts0()
        this.echartsData1 = this.initEcharts1()
        this.echartsDataV1 = this.initEcharts('#DAA520', 0, 'A相')
        this.echartsDataV2 = this.initEcharts('#2E8B57', 0, 'B相')
        this.echartsDataV3 = this.initEcharts('#A52a2a', 0, 'C相')
        this.echartsDataA1 = this.initEcharts('#DAA520', 1, 'A相')
        this.echartsDataA2 = this.initEcharts('#2E8B57', 1, 'B相')
        this.echartsDataA3 = this.initEcharts('#A52a2a', 1, 'C相')
        this.loading = false
        this.$nextTick(() => {
            this.setMqtt(0)
            this.initMqtt()
        })
        if (this.device.isPrimaryUser == 1) {
            this.content.splice(
                0,
                0,
                {
                    iconPath: '/static/transfer.png',
                    text: '移交',
                },

                {
                    iconPath: '/static/delate.png',
                    text: '删除',
                },
            )
            if (this.userInfo.authorities === 'app_vip_user') {
                this.content.splice(3, 0, {
                    iconPath: '/static/share.png',
                    text: '分享',
                })
            }
        }
        if (this.userInfo.authorities !== 'tourist' && this.device.isPrimaryUser === '1') {
            this.content.splice(0, 0, {
                iconPath: '/static/subordinate.png',
                text: '用户',
            })
        }
    },
    onUnload() {
        const charts = [
            this.echart0,
            this.echart1,
            this.echartV1,
            this.echartV2,
            this.echartV3,
            this.echartA1,
            this.echartA2,
            this.echartA3,
        ]
        charts.forEach((chart) => {
            if (chart && chart.dispose) {
                chart.dispose()
                chart = null
            }
        })
        clearInterval(this.timer)
        this.client && this.client.end()
    },

    methods: {
        // 将指标列表按每行两个分组
        chunkedChildren(children) {
            const result = []
            for (let i = 0; i < children.length; i += 2) {
                result.push(children.slice(i, i + 2))
            }
            return result
        },
        initEcharts0() {
            return {
                tooltip: { show: false },
                toolbox: {
                    show: false,
                },
                series: [
                    // 外圈电压 内圈电流
                    {
                        zlevel: 2,
                        name: '基波电流相位',
                        type: 'gauge',
                        // 表盘最小值
                        min: 180,
                        // 表盘最大值
                        max: -180,
                        // 表盘分割数
                        splitNumber: 6,
                        // 圆心位置
                        center: ['50%', '50%'],
                        // 半径
                        radius: '60%',
                        startAngle: 180,
                        endAngle: -179.99,

                        // 指针方向
                        clockWise: true,
                        title: false,
                        // 表盘外框
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: [
                                    [0.25, '#9D322D'],
                                    [0.5, '#9D322D'],
                                    [0.75, '#9D322D'],
                                    [1, '#9D322D'],
                                ],
                                width: 2,
                            },
                        },
                        // 表盘细分数
                        axisTick: {
                            show: true,
                            splitNumber: 5,
                            distance: 0,
                            length: 4,
                            lineStyle: {
                                color: '#9D322D',
                                width: 1,
                                type: 'solid',
                            },
                        },
                        // 分割线
                        splitLine: {
                            show: true,
                            length: 10,
                            distance: 0,
                            lineStyle: {
                                color: '#9D322D',
                                width: 2,
                                type: 'solid',
                            },
                        },
                        // 分割线标识
                        axisLabel: {
                            show: true,
                            distance: 2,
                            fontSize: 10,
                            formatter: function (v) {
                                switch (v + '') {
                                    case '-180':
                                        return ''
                                    default:
                                        return v
                                }
                            },
                        },

                        // 指针设置
                        pointer: {
                            icon: 'path://m368.01136,209.80637l173.00807,-193.72679c19.14653,-21.43943 50.16392,-21.43943 69.31045,0l172.93149,193.72679c1.22537,1.37213 1.22537,3.51607 0,4.8882l-47.63657,53.34133c-1.22538,1.37213 -3.14003,1.37213 -4.36541,0l-113.65381,-127.26452c-1.91465,-2.14395 -5.20785,-0.60031 -5.20785,2.40122l0,731.94254c0,1.88667 -1.37855,3.43031 -3.06345,3.43031l-67.39579,0c-1.6849,0 -3.06345,-1.54364 -3.06345,-3.43031l0,-731.94254c0,-3.08728 -3.2932,-4.54517 -5.20785,-2.40122l-113.65381,127.26452c-1.22538,1.37213 -3.14003,1.37213 -4.36541,0l-47.63657,-53.34133c-1.22537,-1.37213 -1.22537,-3.51607 0,-4.88819l0,-0.00001M539,861.23064h73v800h-73z',
                            length: '90%',
                            width: 15,
                            opacity: 1,
                        },
                        detail: {
                            show: false,
                        },
                        //数值位置

                        data: [
                            {
                                value: 0,
                                name: 'A相',
                                itemStyle: {
                                    color: '#DAA520',
                                },
                            },
                            {
                                value: 0,
                                name: 'B相',
                                itemStyle: {
                                    color: '#2E8B57',
                                },
                            },
                            {
                                value: 0,
                                name: 'C相',
                                itemStyle: {
                                    color: '#A52a2a',
                                },
                            },
                        ],
                    },
                ],
            }
        },
        initEcharts1() {
            let _this = this
            let color = '#DAA520'
            return {
                tooltip: { show: false },
                toolbox: {
                    show: false,
                },
                series: [
                    {
                        zlevel: 1,
                        name: '基波电压相位',
                        type: 'gauge',
                        // 表盘最小值
                        min: 180,
                        // 表盘最大值
                        max: -180,
                        // 表盘分割数
                        splitNumber: 6,
                        // 圆心位置
                        center: ['50%', '50%'],
                        // 半径
                        radius: '100%',
                        startAngle: 180,
                        endAngle: -179.99,

                        // 指针方向
                        clockWise: true,
                        title: false,
                        // 表盘外框
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: [
                                    [0.25, '#9D322D'],
                                    [0.5, '#9D322D'],
                                    [0.75, '#9D322D'],
                                    [1, '#9D322D'],
                                ],
                                width: 1.5,
                            },
                        },
                        // 表盘细分数
                        axisTick: {
                            show: true,
                            splitNumber: 5,
                            distance: 0,
                            length: 6,
                            lineStyle: {
                                color: '#9D322D',
                                width: 1,
                                type: 'solid',
                            },
                        },
                        // 分割线
                        splitLine: {
                            show: true,
                            length: 10,
                            distance: 0,
                            lineStyle: {
                                color: '#9D322D',
                                width: 2,
                                type: 'solid',
                            },
                        },
                        // 分割线标识
                        axisLabel: {
                            show: true,
                            distance: 2,
                            fontSize: 10,
                            formatter: function (v) {
                                switch (v + '') {
                                    case '-180':
                                        return ''
                                    default:
                                        return v
                                }
                            },
                        },

                        // 指针设置
                        pointer: {
                            icon: 'path://m368.01136,209.80637l173.00807,-193.72679c19.14653,-21.43943 50.16392,-21.43943 69.31045,0l172.93149,193.72679c1.22537,1.37213 1.22537,3.51607 0,4.8882l-47.63657,53.34133c-1.22538,1.37213 -3.14003,1.37213 -4.36541,0l-113.65381,-127.26452c-1.91465,-2.14395 -5.20785,-0.60031 -5.20785,2.40122l0,731.94254c0,1.88667 -1.37855,3.43031 -3.06345,3.43031l-67.39579,0c-1.6849,0 -3.06345,-1.54364 -3.06345,-3.43031l0,-731.94254c0,-3.08728 -3.2932,-4.54517 -5.20785,-2.40122l-113.65381,127.26452c-1.22538,1.37213 -3.14003,1.37213 -4.36541,0l-47.63657,-53.34133c-1.22537,-1.37213 -1.22537,-3.51607 0,-4.88819l0,-0.00001M539,861.23064h73v800h-73z',
                            length: '90%',
                            width: 15,
                            opacity: 1,
                        },
                        detail: {
                            show: false,
                        },
                        data: [
                            {
                                value: 0,
                                name: 'A相', //'A相',
                                itemStyle: {
                                    color: '#DAA520',
                                },
                            },
                            {
                                value: 0,
                                name: 'B相', //'B相',
                                itemStyle: {
                                    color: '#2E8B57',
                                },
                            },
                            {
                                value: 0,
                                name: 'C相', //'C相',
                                itemStyle: {
                                    color: '#A52a2a',
                                },
                            },
                        ],
                    },
                ],
            }
        },
        initEcharts(color, key, name) {
            return {
                tooltip: { show: false },
                toolbox: {
                    show: false,
                },
                series: [
                    {
                        type: 'gauge',
                        startAngle: key == 0 ? 180 : 90,
                        endAngle: key == 0 ? 90 : 0,
                        min: 0,
                        max: key == 0 ? 12 : 200,
                        radius: '150%',
                        center: key == 0 ? ['90%', '75%'] : ['10%', '75%'],
                        splitNumber: 2, //刻度数量
                        axisLine: {
                            show: true,
                            lineStyle: {
                                width: 3,
                                color: [
                                    [0.3, color],
                                    [0.7, color],
                                    [1, color],
                                ],
                            },
                        },
                        color: color,
                        // 表盘细分数
                        axisTick: {
                            show: true,
                            distance: -2,
                            length: 8,
                            lineStyle: {
                                color: color,
                                width: 1,
                                type: 'solid',
                            },
                        },
                        axisLabel: {
                            textStyle: {
                                color: color,
                                fontSize: 10,
                            },
                        },
                        splitLine: {
                            show: true,
                            distance: -2,
                            length: 12,

                            lineStyle: {
                                color: color,
                                width: 2,
                                type: 'solid',
                            },
                        },

                        //标题位置
                        title: {
                            fontWeight: 'bolder',
                            fontSize: 10,
                            offsetCenter: key == 0 ? ['-80%', '-100%'] : ['85%', '-100%'],
                        },
                        //数值位置
                        detail: {
                            fontSize: 10,
                            valueAnimation: true,
                            formatter: '{value}',
                            offsetCenter: key == 0 ? ['-40%', '25%'] : ['40%', '25%'],
                            color: color,
                        },

                        // 指针设置
                        pointer: {
                            length: '80%',
                            width: 2,
                        },
                        data: [
                            {
                                value: 0,
                                name: name,
                                itemStyle: {
                                    color: color,
                                },
                            },
                        ],
                    },
                ],
            }
        },

        // 初始化图表
        async initChart(key, value) {
            // console.log('🚀 ~ key,value:', key, value)
            if (!this.$refs[key]) return

            try {
                this[key] = await this.$refs[key].init(echarts)
                this[key].setOption(this[value])
            } catch (error) {
                console.error('图表初始化失败:', error)
            }
        },

        // 更新图表数据
        updateChart(newOption) {
            if (this.chartInstance) {
                this.chartInstance.setOption(newOption)
            } else if (this.$refs.chartRef) {
                this.$refs.chartRef.setOption(newOption)
            }
        },
        // 调整图表大小
        resizeChart() {
            if (this.$refs.chartRef) {
                this.$refs.chartRef.resize()
            }
        },
        // 页面卸载时销毁图表实例
        beforeUnmount() {
            if (this.$refs.chartRef) {
                this.$refs.chartRef.dispose()
            }
        },
        // 刷新
        handleRefresh() {
            this.disabled = true
            this.client && this.client.end()
            this.setMqtt(1)
            this.initMqtt()
            if (this.numTimer) {
                clearInterval(this.numTimer)
            }

            // 设置定时器，每秒执行一次
            this.numTimer = setInterval(() => {
                this.countdown--

                // 倒计时结束
                if (this.countdown <= 0) {
                    clearInterval(this.numTimer) // 清除定时器
                    this.disabled = false // 启用按钮
                    this.countdown = 30 // 重置倒计时
                    this.numTimer = null // 清空定时器标识
                }
            }, 1000)
        },
        async setMqtt(e) {
            uni.showLoading({
                title: '连接中,请稍等...',
                mask: true,
            })
            this.clear()
            this.connection = false
            await getBaseRealData(this.lineId)
                .then((res) => {
                    if (res.code == 'A0000') {
                        this.connection = true

                        this.$util.toast(e == 0 ? '连接成功！' : '刷新成功！')
                        if (this.timer) {
                            clearInterval(this.timer)
                            this.timer = null
                        }

                        this.timer = setInterval(() => {
                            getBaseRealData(this.lineId)
                                .then((res) => {
                                    this.connection = true
                                    console.log(res, '获取基础实时数据')
                                })
                                .catch(() => {
                                    this.connection = false
                                    this.clear()
                                })
                        }, 30000)
                    }
                })
                .catch(() => {
                    this.countdown = 30 // 重置倒计时
                    this.disabled = false
                    this.connection = false
                    this.clear()
                })
        },

        initMqtt() {
            MQTT_OPTIONS.clientId = uni.getStorageSync('devCode')
            // #ifdef APP-PLUS
            this.client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS)
            // #endif
            // #ifdef H5

            this.client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
            // #endif
            this.client
                .on('connect', () => {
                    console.log('连接成功')
                    this.client.subscribe(`/Web/RealData/+`, (err) => {
                        if (!err) {
                            console.log(`订阅成功:/Web/RealData/+`)
                        }
                    })

                    // this.client.subscribe(`/zl/devData/${this.device.equipmentId}/${id}`, (err) => {
                    //     if (!err) {
                    //         console.log(`订阅成功:/zl/devData/${this.device.equipmentId}/${id}`)

                    //         // 默认推送
                    //         this.client.publish(`/zl/askDevData/${this.device.equipmentId}/${id}`)
                    //         this.client.publish(`/zl/askTemperData/${this.device.equipmentId}`)
                    //         if (this.timer) {
                    //             clearInterval(this.timer)
                    //             this.timer = null
                    //         }
                    //         this.timer = setInterval(() => {
                    //             console.log('askDevData')
                    //             this.client.publish(`/zl/askDevData/${this.device.equipmentId}/${id}`)
                    //             this.client.publish(`/zl/askTemperData/${this.device.equipmentId}`)
                    //         }, 1000 * 60)
                    //     }
                    // })
                })
                .on('reconnect', function (error) {
                    console.log(error)
                    // console.log('正在重连...', that.topic)
                })
                .on('error', function (error) {
                    console.log('连接失败...', error)
                })
                .on('end', function () {
                    console.log('连接断开')
                })
                .on('message', (topic, message) => {
                    // console.log('接收推送信息：', JSON.parse(message.toString()), topic)
                    if (!this.connection) return
                    // console.log('🚀 ~ .on ~ topic:', topic, this.userInfo.userIndex)

                    if (
                        topic == `/Web/RealData/${this.lineId}` ||
                        topic == `/Web/RealData/${this.userInfo.userIndex}`
                    ) {
                        let list = JSON.parse(message.toString())
                        if (list.lineId != this.lineId) return
                        // if (list.userId == this.userInfo.userIndex) {
                        // console.log(list)
                        this.realTime = list.dataTime
                        let pt = list.pt || 0
                        let ct = list.ct || 0

                        let data = {
                            vRmsA: ((list.vRmsA * pt) / 1000).toFixed(2),
                            vRmsB: ((list.vRmsB * pt) / 1000).toFixed(2),
                            vRmsC: ((list.vRmsC * pt) / 1000).toFixed(2),
                            iRmsA: (list.iRmsA * ct).toFixed(2),
                            iRmsB: (list.iRmsB * ct).toFixed(2),
                            iRmsC: (list.iRmsC * ct).toFixed(2),
                            v1A: ((list.v1A * pt) / 1000).toFixed(2),
                            v1B: ((list.v1B * pt) / 1000).toFixed(2),
                            v1C: ((list.v1C * pt) / 1000).toFixed(2),
                            v1AngA: list.v1AngA.toFixed(2),
                            v1AngB: list.v1AngB.toFixed(2),
                            v1AngC: list.v1AngC.toFixed(2),

                            i1A: (list.i1A * ct).toFixed(2),
                            i1B: (list.i1B * ct).toFixed(2),
                            i1C: (list.i1C * ct).toFixed(2),
                            i1AngA: list.i1AngA.toFixed(2),
                            i1AngB: list.i1AngB.toFixed(2),
                            i1AngC: list.i1AngC.toFixed(2),
                            vDevA: list.vDevA.toFixed(2),
                            vDevB: list.vDevB.toFixed(2),
                            vDevC: list.vDevC.toFixed(2),
                            vThdA: list.vThdA.toFixed(2),
                            vThdB: list.vThdB.toFixed(2),
                            vThdC: list.vThdC.toFixed(2),
                        }
                        this.realTimeData = [
                            { name: '电压有效值(kV)', A: data.vRmsA, B: data.vRmsB, C: data.vRmsC },
                            { name: '电流有效值(A)', A: data.iRmsA, B: data.iRmsB, C: data.iRmsC },
                            { name: '基波电压幅值(kV)', A: data.v1A, B: data.v1B, C: data.v1C },
                            { name: '基波电流幅值(A)', A: data.i1A, B: data.i1B, C: data.i1C },
                            { name: '基波电压相位(°)', A: data.v1AngA, B: data.v1AngB, C: data.v1AngC },
                            { name: '基波电流相位(°)', A: data.i1AngA, B: data.i1AngB, C: data.i1AngC },
                            { name: '电压偏差(%)', A: data.vDevA, B: data.vDevB, C: data.vDevC },
                            { name: '电压总谐波畸变率(%)', A: data.vThdA, B: data.vThdB, C: data.vThdC },
                        ]
                        // 电压
                        let vMax =
                            Math.ceil(
                                (Math.max(
                                    ...[
                                        Math.floor(data.vRmsA * 100) / 100 || 1,
                                        Math.floor(data.vRmsB * 100) / 100 || 1,
                                        Math.floor(data.vRmsC * 100) / 100 || 1,
                                    ],
                                ) *
                                    1.2) /
                                10,
                            ) * 10
                        this.echartsDataV1.series[0].max = vMax
                        this.echartsDataV2.series[0].max = vMax
                        this.echartsDataV3.series[0].max = vMax
                        this.echartsDataV1.series[0].data[0].value = data.vRmsA
                        this.echartsDataV2.series[0].data[0].value = data.vRmsB
                        this.echartsDataV3.series[0].data[0].value = data.vRmsC

                        // 电流
                        let aMax =
                            Math.ceil(
                                (Math.max(
                                    ...[
                                        Math.floor(data.iRmsA * 100) / 100 || 1,
                                        Math.floor(data.iRmsB * 100) / 100 || 1,
                                        Math.floor(data.iRmsC * 100) / 100 || 1,
                                    ],
                                ) *
                                    1.2) /
                                10,
                            ) * 10
                        this.echartsDataA1.series[0].max = aMax
                        this.echartsDataA2.series[0].max = aMax
                        this.echartsDataA3.series[0].max = aMax
                        this.echartsDataA1.series[0].data[0].value = data.iRmsA
                        this.echartsDataA2.series[0].data[0].value = data.iRmsB
                        this.echartsDataA3.series[0].data[0].value = data.iRmsC

                        this.echartsData0.series[0].data[0].value = data.i1AngA
                        this.echartsData0.series[0].data[1].value = data.i1AngB
                        this.echartsData0.series[0].data[2].value = data.i1AngC

                        this.echartsData1.series[0].data[0].value = data.v1AngA
                        this.echartsData1.series[0].data[1].value = data.v1AngB
                        this.echartsData1.series[0].data[2].value = data.v1AngC

                        const charts = [
                            { instance: this.echart0, data: this.echartsData0 },
                            { instance: this.echart1, data: this.echartsData1 },
                            { instance: this.echartV1, data: this.echartsDataV1 },
                            { instance: this.echartV2, data: this.echartsDataV2 },
                            { instance: this.echartV3, data: this.echartsDataV3 },
                            { instance: this.echartA1, data: this.echartsDataA1 },
                            { instance: this.echartA2, data: this.echartsDataA2 },
                            { instance: this.echartA3, data: this.echartsDataA3 },
                        ]

                        charts.forEach(({ instance, data }) => {
                            if (instance && instance.setOption) {
                                instance.setOption(data, true)
                            }
                        })

                        // this.echart0.setOption(this.echartsData0, true)
                        // this.echart1.setOption(this.echartsData1, true)
                        // this.echartV1.setOption(this.echartsDataV1, true)
                        // this.echartV2.setOption(this.echartsDataV2, true)
                        // this.echartV3.setOption(this.echartsDataV3, true)
                        // this.echartA1.setOption(this.echartsDataA1, true)
                        // this.echartA2.setOption(this.echartsDataA2, true)
                        // this.echartA3.setOption(this.echartsDataA3, true)
                        // }
                    }
                })
        },
        // 清空数据
        clear() {
            this.realTime = ''
            this.realTimeData = [
                { name: '电压有效值(kV)', A: '-', B: '-', C: '-' },
                { name: '电流有效值(A)', A: '-', B: '-', C: '-' },
                { name: '基波电压幅值(kV)', A: '-', B: '-', C: '-' },
                { name: '基波电流幅值(A)', A: '-', B: '-', C: '-' },
                { name: '基波电压相位(°)', A: '-', B: '-', C: '-' },
                { name: '基波电流相位(°)', A: '-', B: '-', C: '-' },
                { name: '电压偏差(%)', A: '-', B: '-', C: '-' },
                { name: '电压总谐波畸变率(%)', A: '-', B: '-', C: '-' },
            ]
            this.echartsDataV1.series[0].data[0].value = 0
            this.echartsDataV2.series[0].data[0].value = 0
            this.echartsDataV3.series[0].data[0].value = 0
            this.echartsDataA1.series[0].data[0].value = 0
            this.echartsDataA2.series[0].data[0].value = 0
            this.echartsDataA3.series[0].data[0].value = 0
            this.echartsData0.series[0].data[0].value = 0
            this.echartsData0.series[0].data[1].value = 0
            this.echartsData0.series[0].data[2].value = 0
            this.echartsData1.series[0].data[0].value = 0
            this.echartsData1.series[0].data[1].value = 0
            this.echartsData1.series[0].data[2].value = 0
            const charts = [
                { instance: this.echart0, data: this.echartsData0 },
                { instance: this.echart1, data: this.echartsData1 },
                { instance: this.echartV1, data: this.echartsDataV1 },
                { instance: this.echartV2, data: this.echartsDataV2 },
                { instance: this.echartV3, data: this.echartsDataV3 },
                { instance: this.echartA1, data: this.echartsDataA1 },
                { instance: this.echartA2, data: this.echartsDataA2 },
                { instance: this.echartA3, data: this.echartsDataA3 },
            ]

            charts.forEach(({ instance, data }) => {
                if (instance && instance.setOption) {
                    instance.setOption(data, true)
                }
            })
        },
        // 监测点变化
        async lineChange(e) {
            await this.clear()
            this.disabled = false
            this.countdown = 30

            this.lineKey = e.detail.value
            this.lineId = this.lineList[e.detail.value].lineId
            await (this.client && this.client.end())
            await this.setMqtt(0)
            await this.initMqtt()
        },
        trigger(e) {
            console.log(e)
            if (e.text === '分享') {
                uni.navigateTo({ url: '/pages/device/share?id=' + this.lineId })
            } else if (e.text === '删除') {
                uni.showModal({
                    title: '提示',
                    content: '确定删除该设备吗？',
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            deleteDevice(this.device.equipmentId).then((res) => {
                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'none',
                                })
                                setTimeout(() => {
                                    uni.navigateBack()
                                }, 1500)
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                        }
                    },
                })
            } else if (e.text === '记录') {
                uni.navigateTo({ url: '/pages/device/APF/record' })
            } else if (e.text === '事件') {
                uni.setStorageSync('messageParams', {
                    engineeringName: this.device.engineeringName,
                    engineeringId: this.device.engineeringId, //工程ID
                    projectName: this.device.projectName,
                    projectId: this.device.projectId, //項目ID
                    deviceName: this.device.equipmentName,
                    deviceId: this.device.equipmentId, //设备ID
                    lineName: '',
                    lineId: '', //测点ID
                    type: 0,
                })
                uni.switchTab({
                    url: '/pages/index/message1',
                })
                // uni.navigateTo({ url: '/pages/device/APF/report?id=' + this.device.equipmentId })
            } else if (e.text === '详情') {
                uni.navigateTo({ url: '/pages/device/APF/about?id=' + this.device.equipmentId })
            } else if (e.text === '移交') {
                uni.navigateTo({ url: '/pages/device/transfer?id=' + this.device.equipmentId })
            } else if (e.text === '反馈') {
                uni.navigateTo({ url: '/pages/device/feedback' })
            } else if (e.text === '用户') {
                uni.navigateTo({
                    url:
                        '/pages/device/user?id=' +
                        this.device.equipmentId +
                        '&isPrimaryUser=' +
                        this.device.isPrimaryUser,
                })
            }
            // this.$refs.fab.close()
        },
    },

    computed: {},

    watch: {},
}
</script>
<style lang="scss" scoped>
.realTime {
    .info-card-wrap {
        padding: 20rpx;
        background-color: #fff;
    }

    // padding: 20rpx;
    .info-card {
        background-image: url('/static/background.png');
        background-position: center center;
        /* 水平+垂直居中 */
        background-repeat: no-repeat;
        /* 不平铺 */
        background-size: 100% 100%;
        /* 覆盖整个容器（可选，根据需求调整） */
        color: #fff;
        padding: 20rpx 40rpx;
        border-radius: 20rpx;

        .info-item {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            margin-bottom: 10rpx;

            view {
                // font-size: 28rpx;
                // .nav-menu {
                //     font-size: 32rpx;
                // }
            }

            &:last-child {
                margin-bottom: 0rpx;
            }
        }

        .status {
            .status-normal {
                // font-weight: bold;
            }
        }
    }

    .params-wrap {
        margin-top: 20rpx;
        background-color: #fff;
        border-radius: 10rpx;
        overflow: hidden;
    }

    .legend-row {
        display: flex;
        gap: 20rpx;
        align-items: center;
        justify-content: flex-end;
        padding: 0rpx 20rpx 0;
        background-color: #fff;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
    }

    .legend-dot {
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
    }

    .legend-text {
        font-size: 24rpx;
        color: #666666;
    }

    .params-section {
        padding: 16rpx 16rpx 20rpx;
    }

    .double-row {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16rpx;
        margin-bottom: 16rpx;

        &:last-child {
            margin-bottom: 0;
        }
    }

    .param-group {
        min-width: 0;
        background: #f3f3f3;
        border-radius: 16rpx;
        padding: 16rpx 8rpx 12rpx;
    }

    .param-title {
        font-size: 26rpx;
        color: #666666;
        margin-bottom: 8rpx;
        padding-left: 4rpx;
    }

    .phase-vertical {
        display: flex;
        align-items: stretch;
    }

    .phase-item-vertical {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4rpx;
    }

    .phase-value-vertical {
        font-size: 28rpx;
        font-weight: 700;
    }

    .phase-divider {
        width: 1px;
        background: #d2d2d2;
        margin: 8rpx 0;
    }

    .time-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background-color: #fff;
        margin: 20rpx 0 0;
        border-radius: 10rpx;

        .time {
            display: flex;
            align-items: center;
            flex: 1;
            font-size: 28rpx;

            text {
                margin-left: 20rpx;
            }
        }
    }
}

.chartBox {
    background-color: #fff;
    padding: 0 0rpx 20rpx;
    display: flex;
    padding-bottom: 55rpx;

    .middle {
        display: flex;
        position: relative;
        height: 600rpx;
        margin: 0 10rpx;
        flex: 1;

        .echart1 {
            position: absolute;
            height: 500rpx;
            top: 0;
        }
    }

    .chart {
        width: 170rpx;
        height: 200rpx;
        margin-bottom: 5rpx;
    }

    .text {
        text-align: center;
        font-size: 28rpx;
        position: absolute;
    }

    .text_center {
        bottom: -5px;
        left: 50%;
        transform: translateX(-50%) translateY(50%);
    }
}

.mini-btn {
    font-size: 24rpx;
    border-radius: 45rpx;
    height: 45rpx;
    line-height: 45rpx;
}

.legend-row {
    display: flex;
    gap: 20rpx;
    align-items: center;
    justify-content: end;
    padding: 16rpx 20rpx;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 8rpx;
}

.legend-dot {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
}

.legend-text {
    font-size: 24rpx;
    color: #666666;
}
</style>
