<template>
    <div class="eqData flex-col">
        <div class="blur-background" />
        <div class="eqData_title">
            <div class="eqData_title_center"> 设备图表 </div>
        </div>
        <div class="eqData_content">
            <div class="flex-row justify-center">

                <!-- 左侧选择器 -->
                <img v-if="!showTable" :src="iconImg" class="image1 icon_pos" @click="handleTableShow">
                <div v-if="showTable" class="flex-col eqData_left">
                    <div class="eqData_left_title">
                        <img :src="iconImg" class="image1" @click="handleTableClose">
                        <span class="eqData_left_title_text">设备列表</span>
                    </div>
                    <el-col>
                        <el-menu :default-active="activeIndex" :unique-opened="true"
                            class="el-menu-vertical-demo eqData_left_content" background-color="transparent"
                            text-color="#0369A1" active-text-color="#18181B" @open="handleOpen" @close="handleClose"
                            @select="handleSelect">
                            <el-submenu index="1">
                                <template slot="title">
                                    <span>K生产线</span>
                                </template>
                                <el-menu-item-group>
                                    <el-menu-item v-for="(item, idx) in menuItems1" :key="idx" :index="item.index"
                                        :class="{ 'custom-active-class': isActive(item.index) }">
                                        {{ item.label }}
                                    </el-menu-item>
                                </el-menu-item-group>
                            </el-submenu>

                            <el-submenu index="2">
                                <template slot="title">
                                    <span>L生产线</span>
                                </template>
                                <el-menu-item-group>
                                    <el-menu-item v-for="(item, idx) in menuItems2" :key="idx" :index="item.index"
                                        :class="{ 'custom-active-class': isActive(item.index) }">
                                        {{ item.label }}
                                    </el-menu-item>
                                </el-menu-item-group>
                            </el-submenu>

                        </el-menu>
                    </el-col>
                </div>
                <div class="body_right">
                    <div class="block">
                        <el-cascader ref="cascader" v-model="selectedOptions" :options="options" :props="props"
                            clearable filterable @change="handleChange" />
                    </div>
                    <br />
                    <el-row :gutter="10">
                        <el-col :xs="22" :sm="22" :md="22" :lg="10" :xl="11" :offset="1">
                            <div class="chart">
                                <div ref="chart1" style="width: 100%; height: 400px;" />
                            </div>
                        </el-col>

                        <el-col :xs="22" :sm="22" :md="22" :lg="10" :xl="11">
                            <div class="chart">
                                <div ref="chart2" style="width: 100%; height: 400px;" />
                            </div>
                        </el-col>
                    </el-row>
                    <br />
                    <el-row :gutter="10">
                        <el-col :xs="22" :sm="22" :md="22" :lg="10" :xl="11" :offset="1">
                            <div class="chart">
                                <div ref="chart3" style="width: 100%; height: 400px;" />
                            </div>
                        </el-col>

                        <el-col :xs="22" :sm="22" :md="22" :lg="10" :xl="11">
                            <div class="chart">
                                <div ref="chart4" style="width: 100%; height: 400px;" />
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>
        <div class="eqData_footer">
            <div class="flex-row">
                <div class="flex-col items-center self-start" @click="$router.push('/equipment')">
                    <img class="footer_image" :src="footTabImg3">
                    <span class="footTab_text">主页</span>
                </div>
                <div class="flex-col items-center self-start" @click="$router.push('/equipment/eqData')">
                    <img class="footer_image" :src="footTabImg2">
                    <span class="footTab_text">数据</span>
                </div>
                <div class="flex-col items-center self-start" @click="$router.push('/equipment/eqSetting')">
                    <img class="footer_image" :src="footTabImg1">
                    <span class="footTab_text">设置</span>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import '@/css/dcs/style.css'
import ProgressBarComponent from '@/components/dcs/ProgressBarComponent.vue'
import config from '@/myConfig/config'
import * as echarts from 'echarts'


import { getNewChartsData } from '@/api/dcs/dcs.js'

export default {
    components: { ProgressBarComponent },
    props: {},
    data() {
        return {
            props: {
                multiple: true
            },
            options: [],
            maxSelections: 5, // 最多选择的项数
            selectedOptions: [], // 显示的选择结果
            displayedSelectedOptions: [], // 真实的选择结果

            chartInstance1: null, // ECharts 实例对象
            chartOptions1: null, // ECharts 图表配置项

            chartInstance2: null, // ECharts 实例对象
            chartOptions2: null, // ECharts 图表配置项

            chartInstance3: null, // ECharts 实例对象
            chartOptions3: null, // ECharts 图表配置项

            chartInstance4: null, // ECharts 实例对象
            chartOptions4: null, // ECharts 图表配置项

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

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

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

            activeIndex: config.eqBucketNames[0], // 菜单激活项
            menuItems1: [
                { index: config.eqBucketNames[0], label: 'K1组' },
                { index: config.eqBucketNames[1], label: 'K2组' },
                { index: config.eqBucketNames[2], label: 'K3组' },
                { index: config.eqBucketNames[3], label: 'K4组' }
            ],
            menuItems2: [
                { index: config.eqBucketNames[4], label: 'L1组' },
                { index: config.eqBucketNames[5], label: 'L2组' },
                { index: config.eqBucketNames[6], label: 'L3组' },
                { index: config.eqBucketNames[7], label: 'L4组' }
            ],

            showTable: true, // 是否显示表格
        }
    },
    mounted() {
        this.initOptions()
        this.initChart()
        this.getChartsInterval()
    },
    beforeDestroy() {
        // 在组件销毁之前销毁 ECharts 实例
        if (this.chartInstance1) {
            this.chartInstance1.dispose()
        }
        if (this.chartInstance2) {
            this.chartInstance2.dispose()
        }
        if (this.chartInstance3) {
            this.chartInstance3.dispose()
        }
        if (this.chartInstance4) {
            this.chartInstance4.dispose()
        }
        clearInterval(this.interval)
    },

    methods: {


        handleOpen(key, keyPath) {
            console.log(key, keyPath)
        },
        handleClose(key, keyPath) {
            console.log(key, keyPath)
        },
        // 左侧菜单项点击时触发
        handleSelect(key, keyPath) {
            this.activeIndex = key
            this.paramsObj.bucketName = key
            this.initOptions()
        },
        isActive(index) {
            return this.activeIndex === index
        },
        // 左侧选择器显示/隐藏
        handleTableClose() {
            this.showTable = false
        },
        handleTableShow() {
            this.showTable = true
        },

        // 选择变化时触发
        handleChange(value) {
            //清空画布
            // this.echartDataArr = []
            this.clearChart()

            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
        },

        // 初始化 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.activeIndex)
            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.chartInstance1 = echarts.init(this.$refs.chart1)
            this.chartInstance2 = echarts.init(this.$refs.chart2)
            this.chartInstance3 = echarts.init(this.$refs.chart3)
            this.chartInstance4 = echarts.init(this.$refs.chart4)
            window.addEventListener('resize', this.resizeHandler)
        },
        // 更新 ECharts 图表配置项
        updateChartOptions() {
            const chartOptions = {
                title: {
                    text: '设备开/温度动态曲线',
                    textStyle: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        animation: false
                    }
                },
                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
                        },
                    },
                ],
                // series: series,
            }
            this.chartOptions1 = JSON.parse(JSON.stringify(chartOptions)) //复制对象 深拷贝
            this.chartOptions2 = JSON.parse(JSON.stringify(chartOptions))
            this.chartOptions3 = JSON.parse(JSON.stringify(chartOptions))
            this.chartOptions4 = JSON.parse(JSON.stringify(chartOptions))

            if (this.chartInstance1) {
                this.chartOptions1.xAxis.minInterval = 11 * 1000 // 设定 11 图表自动取10 如果设定 10 图表会取 5
                this.chartOptions1.title.text = '分钟 开/温度动态曲线'
                this.getChartsData('60s', '1s').then(res => {
                    this.chartOptions1.series = res
                    this.chartInstance1.setOption(this.chartOptions1)
                })
            }
            if (this.chartInstance2) {
                this.chartOptions2.title.text = '小时 开/温度动态曲线'
                this.getChartsData('1h', '10s').then(res => {
                    this.chartOptions2.series = res
                    this.chartInstance2.setOption(this.chartOptions2)
                })
            }
            if (this.chartInstance3) {
                this.chartOptions3.title.text = '每日 开/温度动态曲线'
                this.getChartsData('1d', '4m').then(res => {
                    this.chartOptions3.series = res
                    this.chartInstance3.setOption(this.chartOptions3)
                })
            }
            if (this.chartInstance4) {
                this.chartOptions4.title.text = '每周 开/温度动态曲线'
                this.getChartsData('7d', '30m').then(res => {
                    this.chartOptions4.series = res
                    this.chartInstance4.setOption(this.chartOptions4)
                })
            }
        },
        clearChart() {
            this.chartInstance1.clear()//清空画布
            this.chartInstance2.clear()//清空画布
            this.chartInstance3.clear()//清空画布
            this.chartInstance4.clear()//清空画布
        },
        // 重置 ECharts 实例大小
        resizeHandler() {
            if (this.chartInstance1) {
                this.chartInstance1.resize()
            }
            if (this.chartInstance2) {
                this.chartInstance2.resize()
            }
            if (this.chartInstance3) {
                this.chartInstance3.resize()
            }
            if (this.chartInstance4) {
                this.chartInstance4.resize()
            }
        },
        // 定时获取 ECharts 图表数据
        getChartsInterval() {
            this.interval = setInterval(() => {
                // this.getChartsData('60s')
                this.updateChartOptions()
            }, 1000)
        },
        // 获取 ECharts 图表数据
        async getChartsData(time, step) {
            // console.log('paramsObj:', this.paramsObj);
            // console.log('echartDataArr: ', echartDataArr);
            return new Promise((resolve, reject) => {
                if (this.paramsObj.bucketName == '' || this.paramsObj.paramStr == '') {
                    return
                }
                getNewChartsData(this.paramsObj.paramStr, this.paramsObj.bucketName, time, step).then(response => {
                    // console.log('NewChartsData:', 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({
                                name: new Date(dataArr[i][0]).toString(),
                                value: [
                                    new Date(dataArr[i][0]),
                                    dataArr[i][j + 1].toFixed(2) // 注意这里是从 j+1 开始的，因为dataArr[i][0]是时间
                                ]
                            });
                        }
                    }
                    const serie = this.selectedOptions
                        // .slice(0, this.echartDataArr.length)
                        .map((option, index) => {
                            let serie = {
                                name: option[1],
                                type: 'line',
                                yAxisIndex: 1,
                                showSymbol: false,
                                data: echartDataArr[index]
                            }
                            if (option[0] == '开度') {
                                serie.yAxisIndex = 0;
                            }
                            return serie
                        })
                    resolve(serie)
                }).catch(error => {
                    console.error('There was an error fetching the data!', error)
                })
            })
        },
        // 获取本地化时间
        getLocalizedTime(date) {
            if (!(date instanceof Date) || isNaN(date.getTime())) {
                throw new Error('Invalid date')
            }
            return new Intl.DateTimeFormat(undefined, {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false // 使用24小时制
            }).format(date)
        }


    }
}
</script>
<style lang="scss">
.color_red {
    color: #FF444B !important;
    font-size: 15px;
}

.border_changing {
    border: 1px solid #72E0FF !important;

    .eqData_rt_boxs1_box_text {
        .eqData_rt_boxs1_box_text1 {
            .eqData_rt_boxs1_box_text1_2 {
                color: #fcc764 !important;
            }
        }
    }
}

.eqData {
    width: 1920px;
    height: 1080px;
    flex-shrink: 0;
    background: rgba(0, 0, 0, 0.70);
    backdrop-filter: blur(2px);

    .blur-background {
        position: absolute;
        /* 绝对定位，用于全屏覆盖 */
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-image: url('~@/assets/dcs/homeBg.svg');
        background-size: cover;
        /* 确保背景图覆盖整个区域 */
        background-position: center;
        /* 使背景图居中 */
        background-repeat: no-repeat;
        /* 防止背景图重复 */
        filter: blur(8px);
        /* 设置模糊值，可以根据需求调整 */
        z-index: -1;
        /* 确保模糊背景在内容下方 */
    }

    .eqData_title {
        background-image: url('../../../assets/dcs/eqData/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;
            }

        }
    }

    .eqData_content {
        .icon_pos {
            position: absolute;
            left: 2%;
        }

        .eqData_left {
            width: 270px;
            height: 755px;
            flex-shrink: 0;
            border-radius: 4px;
            border: 1px solid rgba(37, 147, 228, 0.50);
            opacity: 0.9;
            background: rgba(9, 23, 50, 0.90);
            box-shadow: 0px 0px 8.8px 3px rgba(126, 230, 246, 0.20) inset;

            .eqData_left_title {
                display: flex;
                height: var(--height-h-14, 56px);
                padding: 0px var(--spacing-6, 24px);
                align-items: center;
                gap: var(--spacing-2, 8px);
                flex-shrink: 0;
                align-self: stretch;

                .image1 {
                    width: 24px;
                    height: 24px;
                }

                .eqData_left_title_text {
                    color: var(--tailwind-colors-sky-500, #0EA5E9);
                    font-family: "PingFang SC";
                    font-size: var(--typography-base-sizes-small-font-size, 14px);
                    font-style: normal;
                    font-weight: 400;
                    line-height: var(--typography-base-sizes-small-line-height, 20px);
                }
            }

            .eqData_left_content {
                /* display: flex;  */
                padding: 0px var(--spacing-4, 16px);
                border: none;
                flex: 1 0 0;
                align-self: stretch;
                cursor: default !important;

                .el-menu-item:hover,
                .el-submenu__title:hover {
                    background-color: transparent !important;
                }

                .el-menu {
                    padding: 0 18px;
                }

                .el-submenu__title span {
                    padding-left: 20px;
                }

                .el-menu-item {
                    transition: none !important;
                }

                .el-menu-item:hover {
                    border-radius: var(--border-radius-lg, 8px) !important;
                    background: #9DF !important;
                }

                .custom-active-class {
                    /* transition: border-color 0s, background-color 0.3s, color 0.3s !important; */
                    border-radius: var(--border-radius-lg, 8px) !important;
                    background: #9DF !important;
                }

            }
        }

    }

    .body_right {
        width: 1587px;
        height: 902px;

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

            .el-cascader {
                width: 1400px;

                input {
                    background-color: #192E4F;
                    color: #D8E0E6;
                    border-color: #224275;
                }

                .el-cascader__tags {
                    .el-tag {
                        background-color: #23a5dd !important;
                        color: #eee !important;
                    }
                }
            }
        }

        .chart {
            //透明度
            // opacity: 0.7;
            background: rgba($color: #0c2839, $alpha: 0.3);
            //背景颜色
            // background-color: #fefefe;
        }
    }

    .eqData_footer {
        background-image: url('../../../assets/dcs/eqName/footTab.svg');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: bottom;
        margin: 48px auto 0;
        ;
        display: flex;
        /* 使用flex布局 */
        justify-content: center;
        /* 水平居中对齐子元素 */
        width: 961.5px;
        height: 52px;
        flex-shrink: 0;

        .footer_image {
            width: 157px;
            height: 58px;
            margin-top: -31px;
        }

        .footTab_text {
            font-size: 14.08px;
            font-family: PingFang SC;
            line-height: 12.96px;
            color: #ffffff;
        }

    }

}

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

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

}
</style>