<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="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-select v-model="dataTypeValue" placeholder="请选择对应数据类型" style="width: 240px" @change="dataTypeChange">
                <el-option v-for="item in dataTypeOptions" :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=5 />
            <el-button :icon="Search" circle @click="getEchartData" />
        </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 { getEquipmentTreeByDataType, queryWithFlux } from '@/api/dcs/equipment'
import { Search } from '@element-plus/icons-vue'
import { openElMessage } from '@/utils/message'
import * as echarts from 'echarts'
onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart)// 图表自适应
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart)
    if (myChart) {
        myChart.dispose()
    }
})
//时间选择
const timeRangeValue = ref(['', ''])

//时间间隔
const timeIntervalValue = ref('1m')
//时间间隔选项
const timeIntervalOptions = [
    {
        value: '1s',
        label: '1秒',
    },
    {
        value: '10s',
        label: '10秒',
    },
    {
        value: '1m',
        label: '1分钟',
    },
    {
        value: '5m',
        label: '5分钟',
    },
    {
        value: '1h',
        label: '1小时',
    },
]
//数据类型
const dataTypeValue = ref('')
const props = {
    multiple: true,
    emitPath: true, // 保证 value 是路径数组
    checkStrictly: false, // 可选，是否可选中父节点
    value: 'value',
    label: 'label',
    children: 'children'
}

//数据类型选项
const dataTypeOptions = [
    {
        value: 'bool',
        label: '阀门开关量',
    },
    {
        value: 'data',
        label: '数值类型',
    },
    {
        value: 'string',
        label: '字符串类型',
    }
]
//设备选择
const equipmentValue = ref('')
//设备选项
const equipmentOptions = ref([])
//数据类型切换
function dataTypeChange() {
    // console.log('数据类型切换',dataTypeValue.value)
    if (dataTypeValue.value) {
        getEquipmentOptions()
    }
}

//获取设备选项列表
function getEquipmentOptions() {
    getEquipmentTreeByDataType(dataTypeValue.value).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 = {
        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            }
        },
        title: {
            left: 'center',
            text: '历史图表',
            textStyle: {
                color: '#fff',
                fontSize: 30
            },
        },
        toolbox: {
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'time',
            boundaryGap: false,// 保证两边留白
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, '100%']
        },
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 20
            },
            {
                start: 0,
                end: 20
            }
        ],
        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) || []
        })
        // console.log('value:', equipmentValue.value)
        // console.log('labels 对齐:', equipmentLabels.value)
    })
}

//获取Echart数据
function getEchartData() {
    if (!(dataTypeValue.value && equipmentValue.value && timeRangeValue.value[0] && timeRangeValue.value[1] && timeIntervalValue.value)) {
        openElMessage('请选择数据类型、设备、时间范围、时间间隔')
        return
    }
    // console.log('初始设备选择', equipmentValue.value)
    getEquipmentLabel()//获取设备选择的label
    //取出equipmentValue二维数组里面每个数组的最后一个值，组成一个数组
    //设备编码数组
    const equipmentCodeArr = equipmentValue.value.map(item => item.at(-1))//获取设备编码数组

    //时间范围数组
    const [start, end] = timeRangeValue.value
    const timeRangeArr = [new Date(start).toISOString(), new Date(end).toISOString()]
    // console.log('设备选择', equipmentCodeArr)
    // console.log('数据类型', dataTypeValue.value)
    // console.log('时间选择', timeRangeArr)
    //调用接口查询数据
    queryWithFlux({
        fields: equipmentCodeArr,
        measurement: dataTypeValue.value,
        timeRangeStart: timeRangeArr[0],
        timeRangeStop: timeRangeArr[1],
        windowPeriod: timeIntervalValue.value,
        aggregateFunction: dataTypeValue.value === 'data' ? 'mean' : 'last'
    }).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++) {
            if (dataTypeValue.value === 'bool') {
                //布尔类型数据处理:1为开，0为关
                echartDataArr[i] = dataArr[i].records.map(item => [item.time, item.value ? 1 : 0]);
            } else {
                echartDataArr[i] = dataArr[i].records.map(item => [item.time, parseFloat(item.value.toFixed(3))]);
            }
            //处理labels数组，用于tooltip显示
            const index = equipmentCodeArr.findIndex(item => item === dataArr[i].records[0].field);
            labelsArr.push(equipmentLabels.value[index])
        }
        // console.log('echartDataArr', echartDataArr)
        // console.log('labelsArr', labelsArr)
        updateChart(echartDataArr, labelsArr)
    })

}
//更新图表
function updateChart(echartDataArr, labelsArr) {
    console.log('更新图表', echartDataArr, labelsArr)
    // 设置 yAxis 根据数据类型动态切换
    const isBool = dataTypeValue.value === 'bool'
    chartOptions.value.yAxis = isBool
        ? {
            type: 'value',
            min: -1,
            max: 2,
            interval: 1,
            axisLabel: {
                formatter: val => {
                    if (val === 0) return '关';
                    if (val === 1) return '开';
                    return '';
                }
            }
        }
        : {
            type: 'value',
            boundaryGap: [0, '100%']
        }
    chartOptions.value.series = []//清空series
    chartOptions.value.series = labelsArr.map((label, index) => ({
        name: `${label[0]}-${label[label.length - 1]}`,
        type: 'line',
        data: echartDataArr[index]
    }));

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

// 图表自适应
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>