<template>

    <div class="eqData_content">
        <div class="flex-row justify-center">

            <!-- 左侧选择器 -->
            <!-- <EqSelectedComponent @select-item="handleSelectItem" /> -->
            <div class="body_right">
                <div class="block">
                    <!-- 时间选择器 -->
                    <el-date-picker v-model="timeValue" type="datetimerange" :picker-options="pickerOptions"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
                        @change="handleTimeChange">
                    </el-date-picker>
                    <!-- 时间间隔选择器 -->
                    <el-select v-model="timeIntervalValue" clearable placeholder="请选择时间间隔"
                        @change="handleTimeIntervalChange">
                        <el-option v-for="item in timeIntervalOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <!-- 设备选择器 -->
                    <el-cascader ref="cascader" v-model="selectedOptions" :options="options" :props="props" clearable
                        filterable @change="handleChange" />
                </div>
                <div class="chart_box">
                    <div class="chart">
                        <div ref="chart1" class="chart_content" />
                    </div>
                </div>
                <!-- <el-row :gutter="10"> -->
                <!-- <el-col :xs="22" :sm="22" :md="22" :lg="20" :xl="21"> -->
                <!-- </el-col> -->

                <!-- </el-row> -->
            </div>
        </div>
    </div>
    <!-- </div> -->
</template>
<script>
import '@/css/dcs/style.css'
import EqSelectedComponent from '@/components/dcs/EqSelectedComponent.vue'
import config from '@/myConfig/config'
import * as echarts from 'echarts'
import { getChartsDataByTime } from '@/api/dcs/dcs.js'

export default {
    components: { EqSelectedComponent },
    props: {},
    data() {
        return {
            //时间选择器
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            timeValue: '',//时间选择器值
            //时间间隔选择器
            timeIntervalOptions: [{
                value: '1s',
                label: '1s'
            }, {
                value: '10s',
                label: '10s'
            }, {
                value: '60s',
                label: '60s'
            }],
            timeIntervalValue: '60s',//时间间隔选择器值
            //设备阀门选择器
            props: {
                multiple: true
            },
            options: [],
            maxSelections: 5, // 最多选择的项数
            selectedOptions: [], // 显示的选择结果
            displayedSelectedOptions: [], // 真实的选择结果

            // ECharts图表
            chartInstance: null, // ECharts 实例对象
            chartOptions: null, // ECharts 图表配置项

            // echartDataArr: [],//echart数据数组

            paramsObj: {
                bucketName: 'mybucket',
                paramStr: '',
                timeArr: []
            },//查询参数对象

            footTabImg1: require('@/assets/dcs/eqName/footTab1.svg'), // 主页图标
            footTabImg2: require('@/assets/dcs/eqName/footTab2.svg'), // 设备图标
            footTabImg3: require('@/assets/dcs/eqName/footTab3.svg'), // 控制图标

        }
    },
    mounted() {
        this.initOptions()
        this.initChart()
        // this.getChartsInterval()
    },
    computed: {
        eqBucketName() {
            return this.$store.getters.eqBucketName;  // 通过计算属性获取 Vuex 的 getter
        }
    },
    watch: {
        eqBucketName(newVal, oldVal) {
            // console.log('bucketName 变化:', newVal, '从:', oldVal);
            this.paramsObj.bucketName = newVal; // 更新 paramsObj 中的 bucketName
            this.getChartsData()
        }
    },
    beforeDestroy() {
        // 在组件销毁之前销毁 ECharts 实例
        if (this.chartInstance) {
            this.chartInstance.dispose()
        }
        clearInterval(this.interval)
    },

    methods: {
        // 时间选择器变化时触发
        handleTimeChange(value) {
            // console.log('时间选择器变化', value)   
            // console.log('时间选择器变化', new Date(value[0]).toISOString())
            const timeArr = [];
            timeArr.push(new Date(value[0]).toISOString());
            timeArr.push(new Date(value[1]).toISOString());
            this.paramsObj.timeArr = timeArr;
            this.getChartsData()
        },
        // 时间间隔选择器变化时触发
        handleTimeIntervalChange(value) {
            // this.timeIntervalValue = value
            console.log('时间间隔选择器变化', value)
            this.getChartsData()
        },
        // 阀门选择变化时触发
        handleChange(value) {
            //清空画布
            // this.echartDataArr = []
            this.chartInstance.clear()
            if (value.length > this.maxSelections) {
                this.$message.warning(`最多只能选择 ${this.maxSelections} 项`)
                // 不更新 selectedOptions 和 displayedSelectedOptions，保持原样
                this.selectedOptions = this.displayedSelectedOptions.slice()
            } else {
                // 更新真实的选择结果
                this.selectedOptions = value
                this.displayedSelectedOptions = value
            }
            console.log('选择变化', this.selectedOptions)
            const params = this.selectedOptions.map(item => `MEAN("${item[1]}")`).join(", ").toString();
            this.paramsObj.paramStr = params
            this.getChartsData()
        },
        // 初始化 options选项
        initOptions() {
            const eqGroups = config.eqGroupNames
            const eqBucketNames = config.eqBucketNames
            const wdArr = config.WD_Code// 温度数组
            const newOptions = []
            const childOptionKD = { value: '开度', label: '开度', children: [] }
            let i = eqBucketNames.findIndex(item => item == this.paramsObj.bucketName)
            for (let j = 0; j < 26; j++) {
                childOptionKD.children.push({ value: 'opening_' + (j + 1), label: eqGroups[i] + '-' + (j + 1) })
            }
            const childOptionWD = { value: '温度', label: '温度', children: [] }
            for (let k = 0; k < wdArr.length; k++) {
                childOptionWD.children.push({ value: 'temperature_' + (k + 1), label: eqGroups[i] + '-' + wdArr[k] })
            }
            newOptions.push(childOptionKD)
            newOptions.push(childOptionWD)
            this.options = newOptions
        },
        // 初始化 ECharts 实例
        initChart() {
            this.chartInstance = echarts.init(this.$refs.chart1)
            // 监听浏览器窗口大小变化
            window.addEventListener('resize', this.resizeHandler)
            this.chartInstance.on('restore', () => {
                // console.log('图表已还原');
                this.clearSelected()
            });
        },
        //清空选择器
        clearSelected() {
            this.selectedOptions = []
            this.displayedSelectedOptions = []
            this.timeIntervalValue = ''
            this.timeValue = ''
            this.paramsObj.paramStr = ''
            this.paramsObj.timeArr = []
        },
        // 更新 ECharts 图表配置项
        updateChartOptions(echartDataArr) {
            // this.getChartsData()
            this.chartOptions = {
                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',
                    splitLine: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#eee'
                        }
                    },
                },
                yAxis: [
                    {
                        name: '开度',
                        type: 'value',
                        nameTextStyle: {
                            color: '#fff'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#eee'
                            }
                        },
                        // splitLine: { // 隐藏分行线
                        //   show: false
                        // }
                    },
                    {
                        name: '温度',
                        type: 'value',
                        nameTextStyle: {
                            color: '#fff'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#eee'
                            }
                        },
                        splitLine: { // 隐藏分行线
                            show: false
                        },
                    },
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 20
                    },
                    {
                        start: 0,
                        end: 20
                    }
                ],
                series: this.selectedOptions.map((option, index) => {
                    const serie = {
                        name: option[1],
                        type: 'line',
                        yAxisIndex: 1,
                        showSymbol: false,
                        data: echartDataArr[index]
                    }
                    if (option[0] == '开度') {
                        serie.yAxisIndex = 0;
                    }
                    return serie
                })
            };

            if (this.chartInstance) {
                this.chartInstance.setOption(this.chartOptions)
            }

        },
        // 重置 ECharts 实例大小
        resizeHandler() {
            if (this.chartInstance) {
                this.chartInstance.resize()
            }

        },
        // 获取 ECharts 图表数据
        async getChartsData() {
            console.log('paramsObj:', this.paramsObj);
            if (this.paramsObj.bucketName == '' || this.paramsObj.paramStr == '' || this.paramsObj.timeArr.length == 0 || this.timeIntervalValue == '') {
                return
            }
            getChartsDataByTime(this.paramsObj.paramStr, this.paramsObj.bucketName, this.paramsObj.timeArr, this.timeIntervalValue).then(response => {
                console.log(response);
                const dataArr = response.results[0].series[0].values
                const echartDataArr = Array.from({ length: this.selectedOptions.length }, () => []);
                for (let i = 0; i < dataArr.length; i++) {
                    for (let j = 0; j < this.selectedOptions.length; j++) {
                        echartDataArr[j].push([
                            +new Date(dataArr[i][0]),
                            dataArr[i][j + 1] // 注意这里是从 j+1 开始的，因为dataArr[i][0]是时间
                        ]
                        );
                    }
                }
                // this.echartDataArr = echartDataArr;
                console.log('echartDataArr:', echartDataArr);
                this.updateChartOptions(echartDataArr)
            }).catch(error => {
                console.error('There was an error fetching the data!', error)
            })
        },

    }
}
</script>
<style lang="scss">
// .eqData {
.eqData_content {
    // width: 1587px;
    height: 905px;

    .body_right {
        width: 1587px;
        z-index: 999;

        .block {
            display: flex;
            justify-content: center;

            .el-cascader {
                width: 700px;
                background-color: #192E4F;
                color: #fefefe;
            }
        }

        .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;
                }
            }
        }
    }
}

// }

.el-popper {
    .el-cascader-menu {

        &:first-child {
            .el-scrollbar__wrap {
                .el-cascader-menu__list {
                    .el-cascader-node {
                        label.el-checkbox {
                            display: none !important;
                        }
                    }
                }
            }
        }
    }

}
</style>