<template>
    <div class="dcs">
        <div class="eqData_title">
            <div class="eqData_title_center"> 实时数据图表 </div>
        </div>
        <div class="eqSelector">
            <!-- 时间选择 -->
            <!-- <el-date-picker v-model="timeRangeValue" type="datetimerange" start-placeholder="开始时间"
                end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss" /> -->
            <!-- 起始时间范围选择器 -->
            <el-select v-model="startTimeRangeValue" placeholder="Select" style="width: 200px">
                <el-option v-for="item in startTimeRangeOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
            </el-select>
            <!-- 时间间隔选择器 -->
            <el-select v-model="timeIntervalValue" placeholder="Select" style="width: 200px">
                <el-option v-for="item in timeIntervalOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
            </el-select>
            <!-- 设备选择 -->
            <el-cascader ref="equipmentCascader" :props="props" clearable v-model="equipmentValue"
                placeholder="请选择要查询设备" :options="equipmentOptions" @change="handleChange" collapse-tags=true
                max-collapse-tags=3 />
            <el-button :icon="Search" circle @click="updateChartInterval" />
        </div>
        <div class="chart_box">
            <div class="chart">
                <div ref="chartRef1" class="chart_content" id="chart1" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getEquipmentSensorTree, queryWithFlux } from '@/api/dcs/equipment'
import { Search } from '@element-plus/icons-vue'
import { openElMessage } from '@/utils/message'
import * as echarts from 'echarts'
onMounted(() => {
    getEquipmentOptions();//获取设备选项列表
    initChart();
    window.addEventListener('resize', resizeChart)// 图表自适应
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart)
    if (myChart) {
        myChart.dispose()
    }
    if (interval.value) {
        clearInterval(interval.value)
        interval.value = null
    }
})

//时间范围选择
const startTimeRangeValue = ref('1m')
//时间范围选项
const startTimeRangeOptions = [
    {
        value: '1m',
        label: '最近1分钟',
    },
    {
        value: '10m',
        label: '最近10分钟',
    },
    {
        value: '1h',
        label: '最近1小时',
    },
    {
        value: '1d',
        label: '最近24小时',
    },
    {
        value: '3d',
        label: '最近3天',
    }
]
//时间间隔
const timeIntervalValue = ref('10s')
//时间间隔选项
const timeIntervalOptions = [
    {
        value: '1s',
        label: '1秒',
    },
    {
        value: '10s',
        label: '10秒',
    },
    {
        value: '1m',
        label: '1分钟',
    },
    {
        value: '1h',
        label: '1小时',
    }
]
const props = {
    multiple: true,
}
//设备选择
const equipmentValue = ref('')

//设备选项
const equipmentOptions = ref([])


//获取设备选项列表
function getEquipmentOptions() {
    getEquipmentSensorTree().then(res => {
        equipmentOptions.value = res.data
    })
}
const chartRef1 = ref(null) // 图表容器
let myChart; // 图表实例
const chartOptions = ref({}) // ECharts 图表配置项
//初始化图表
function initChart() {
    if (!chartRef1.value) return
    myChart = echarts.init(chartRef1.value)
    chartOptions.value = {
        // animation: false,// 关闭动画效果
        title: {
            left: 'center',
            text: '实时数据图表',
            textStyle: {
                color: '#fff',
                fontSize: 30
            },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                animation: false
            },
            formatter: function (params) {
                const date = new Date(params[0].value[0]);
                const timeStr = date.toTimeString().split(' ')[0]; // HH:MM:SS
                let tooltipStr = `${timeStr}<br/>`;
                params.forEach(p => {
                    const name = p.seriesName.split('-')[1]
                    let unit = '℃';
                    if (name.includes('压') || name.includes('MPa')) unit = 'MPa';
                    else if (name.includes('重') || name.includes('KG')) unit = 'KG';
                    tooltipStr += `${p.seriesName}: ${p.value[1]} ${unit}<br/>`;
                });
                return tooltipStr;
            }
        },
        xAxis: {
            type: 'time',
            splitLine: { show: false },
            axisLabel: {
                formatter: function (value) {
                    const date = new Date(value);
                    return (
                        date.getHours().toString().padStart(2, '0') + ':' +
                        date.getMinutes().toString().padStart(2, '0') + ':' +
                        date.getSeconds().toString().padStart(2, '0')
                    );
                }
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '℃',
                min: 0,
                max: 150,
                position: 'left',
                splitLine: {
                    show: false
                },
                //颜色
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                }
            },
            {
                type: 'value',
                min: -1,
                max: 1.6,
                name: 'Mpa',
                position: 'right',
                splitLine: {
                    show: false
                }
            },
            {
                type: 'value',
                min: 0,
                max: 10000,
                name: 'KG',
                position: 'right',
                offset: 60,// 右侧Y轴偏移
            }
        ],
        series: []
    }
};

const equipmentLabels = ref([]) // 设备选择器的选择的label，与value对应
const equipmentCascader = ref(null) // 设备选择器
//获取设备选择的label
function getEquipmentLabel() {
    equipmentLabels.value = []//初始化设备选择器的选择的label
    nextTick(() => {
        const checkedNodes = equipmentCascader.value?.getCheckedNodes?.(true) || []
        const labelMap = new Map()

        // 构建路径-value 到 label 映射
        checkedNodes.forEach(node => {
            const valuePath = node.pathValues?.join('@@')// 路径用@@分隔
            const labelPath = node.pathLabels || []
            labelMap.set(valuePath, labelPath)
        })

        // 根据 equipmentValue 顺序，还原 label
        equipmentLabels.value = equipmentValue.value.map(pathArr => {
            const key = pathArr.join('@@')
            return labelMap.get(key) || []
        })
    })
}

//定时器
const interval = ref(null)
//点击搜索按钮，定时更新图表数据
function updateChartInterval() {
    if (!(equipmentValue.value && startTimeRangeValue.value && timeIntervalValue.value)) {
        openElMessage('请选择设备、时间范围、时间间隔')
        return
    }
    //清空定时器
    if (interval.value) {
        clearInterval(interval.value)
        interval.value = null
    }
    interval.value = setInterval(() => {
        getEchartData()
    }, 1000)
}

//获取echart数据
function getEchartData() {
    //取出equipmentValue二维数组里面每个数组的最后一个值，组成一个数组
    const equipmentCodeArr = equipmentValue.value.map(item => item.at(-1))//获取设备编码数组
    getEquipmentLabel()//获取设备选择的label
    queryWithFlux({
        fields: equipmentCodeArr,
        measurement: 'data',//数据表名
        timeRangeStart: '-' + startTimeRangeValue.value,//时间范围
        windowPeriod: timeIntervalValue.value,
        aggregateFunction: 'mean',
    }).then(response => {
        // console.log('查询结果', response)
        const dataArr = response.data
        let echartDataArr = Array.from({ length: equipmentCodeArr.length }, () => []);//初始化echart数据数组
        let labelsArr = [];//初始化labels数组
        for (let i = 0; i < dataArr.length; i++) {
            echartDataArr[i] = dataArr[i].records.map(item => {
                const val = Number(item.value);
                return [item.time, isNaN(val) ? null : parseFloat(val.toFixed(3))];
            });

            // 处理labels数组，用于tooltip显示
            const index = equipmentCodeArr.findIndex(item => item === dataArr[i].records[0].field);
            labelsArr.push(equipmentLabels.value[index])
        }
        updateChart(echartDataArr, labelsArr)
    })
}

//更新图表
function updateChart(echartDataArr, labelsArr) {
    // console.log('更新图表', echartDataArr, labelsArr)
    chartOptions.value.series = []//清空series
    chartOptions.value.series = labelsArr.map((label, index) => ({
        name: `${label[0]}-${label[label.length - 1]}`,
        type: 'line',
        data: echartDataArr[index],
        yAxisIndex: getYAxisIndexByLabel(label),//y坐标轴选取 0温度，1压力，2体重
    }));

    // console.log('当前 chartOptions:', chartOptions.value);
    if (myChart) {
        myChart.setOption(chartOptions.value, true)//强制重绘,true是避免脏数据污染
    }
}

// 获取数据对应的y轴索引
function getYAxisIndexByLabel(name) {
    if (name.includes('温')) return 0;
    if (name.includes('压')) return 1;
    if (name.includes('重')) return 2;
    return 0; // 默认温度
}


// 图表自适应
function resizeChart() {
    if (myChart) {
        myChart.resize()// 重置图表大小
    }
}


</script>

<style lang="scss" scoped>
#app {
    width: 1920px;
    height: 1080px;

    .dcs {
        width: 1920px;
        height: 1080px;
        background-color: #141414;

        .eqData_title {
            background-image: url('@/assets/dcs/header.svg');
            background-size: 100% 100%;
            background-repeat: no-repeat;
            width: 1919.5px;
            height: 74.5px;
            flex-shrink: 0;
            position: relative;

            .eqData_title_center {
                font-family: PangMenZhengDao;
                font-size: 36px;
                font-style: normal;
                font-weight: 400;
                line-height: normal;
                letter-spacing: 7.2px;
                background: linear-gradient(180deg, #FFF 32.33%, #00ABFF 130.49%);
                background-clip: text;
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                text-align: center;
                // margin-top: 10px;
            }

            .eqData_title_right {
                position: absolute;
                right: 220px;
                top: 10px;
                display: inline-flex;
                padding: 4px 8px;
                justify-content: center;
                align-items: center;
                gap: 4px;
                border-radius: 5px;
                background: #446094;

                .eqData_title_right_icon {
                    width: 16px;
                    height: 16px;
                }

                .eqData_title_right_input {
                    width: 196px;
                    border: none;
                    background-color: transparent;
                    color: #B4C7D9 !important;
                    font-family: "PingFang SC";
                    font-size: 14px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: normal;
                }

                input:focus {
                    outline: none;
                }

            }
        }

        .eqSelector {
            margin: 10px auto;
            display: flex;
            gap: 10px;
            align-items: center;
            justify-content: center;
            width: 80%;

            :deep(.el-cascader) {
                width: 720px !important;
            }
        }

        .chart_box {

            display: flex;
            justify-content: center;

            .chart {
                width: 80%;
                background: rgba($color: #0c2839, $alpha: 0.3);

                .chart_content {
                    width: 100%;
                    height: 865px;
                    // height: 500px;
                }
            }
        }
    }


}
</style>