<template>
  <div>
    <div class="block">
      <el-cascader ref="cascader" v-model="selectedOptions" :options="options" :props="props" clearable filterable
        @change="handleChange" @visible-change="handleVisibleChange" @remove-tag="handleRemoveTag" />
    </div>
    <div class="chart">
      <div ref="chart3" style="width: 100%; height: 500px;" />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import config from '@/myConfig/config'

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


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

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

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

      dataArr: [],
      paramsArr: [],//查询参数数组
    }
  },
  mounted() {
    this.initOptions()
    this.initChart()
    this.getChartsInterval()
  },
  beforeDestroy() {
    // 在组件销毁之前销毁 ECharts 实例
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
    clearInterval(this.interval)
  },
  methods: {
    // 选择变化时触发
    handleChange(value) {
      //清空画布
      this.echartDataArr = []
      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)
    },
    // 菜单显示/隐藏时触发
    handleVisibleChange(visible) {
      if (!visible) {
        this.paramsArr = []//初始化查询参数数组
        console.log('菜单关闭', this.selectedOptions)

        const firstItems = this.selectedOptions.map(item => item[0]); // 提取每个子数组的第一个元素
        // 检查所有第一个元素是否都相等
        const allEqual = firstItems.every((val, i, arr) => val === arr[0]);
        if (allEqual) {
          const result = []
          result.push(firstItems[0])
          const params = this.selectedOptions.map(item => `MEAN("${item[2]}")`).join(", ").toString();
          result.push(params)
          this.paramsArr.push(result)
        } else {
          console.log('选择的设备不一致，不能合并');
          // const grouped = this.selectedOptions.reduce((acc, item) => {
          //   const key = item[0];
          //   if (!acc[key]) {
          //     acc[key] = [];
          //   }
          //   // 对于每个 item, 创建 "mean('value')" 字符串并添加到对应组中
          //   acc[key].push(`MEAN('${item[2]}')`);
          //   return acc;
          // }, {});

          // // 转换为所需输出格式
          // const result = Object.entries(grouped).map(([key, values]) =>
          //   [key, values.join(',')]
          // );
          // console.log('result:', result);
          // this.paramsArr=result
        }
        console.log('paramsArr:', this.paramsArr);
      }
    },
    // 标签移除时触发
    handleRemoveTag(tag) {
      // 移除标签
      const index = this.selectedOptions.findIndex(item => item.toString() === tag.toString())
      console.log('移除标签', tag, index)
      this.echartDataArr.splice(index, 1)//移除对应数据
      console.log('echartDataArr:', this.echartDataArr)
      console.log('selectedOptions:', this.selectedOptions)
      this.chartInstance.clear()//清空画布
      this.updateChartOptions()//更新画布配置项
      console.log('selectedOptions2:', this.selectedOptions)
    },
    // 初始化 options选项
    initOptions() {
      const mybucket = config.eqBucketNames
      const eqGroups = config.eqGroupNames
      const wdArr = config.WD_Code// 温度数组
      for (let i = 0; i < mybucket.length; i++) {
        const option = { value: mybucket[i], label: eqGroups[i], children: [] }
        const childOptionKD = { value: 'KD', label: '开度', children: [] }
        for (let j = 0; j < 26; j++) {
          childOptionKD.children.push({ value: 'opening_' + (j + 1), label: eqGroups[i] + '-' + (j + 1) })
        }
        const childOptionWD = { value: 'WD', label: '温度', children: [] }
        for (let k = 0; k < wdArr.length; k++) {
          childOptionWD.children.push({ value: 'temperature_' + (k + 1), label: eqGroups[i] + '-' + wdArr[k] })
        }
        option.children.push(childOptionKD)
        option.children.push(childOptionWD)
        this.options.push(option)
      }
      // console.log(this.options)
    },
    // 初始化 ECharts 实例
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart3)
      window.addEventListener('resize', this.resizeHandler)
    },
    // 更新 ECharts 图表配置项
    updateChartOptions() {
      this.chartOptions3 = {
        title: {
          text: '设备开/温度动态曲线'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          }
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          splitLine: {
            show: false
          }
        },
        // series: [
        //   {
        //     name: this.selectedOptions[0].toString(),
        //     type: 'line',
        //     showSymbol: false,
        //     data: this.echartDataArr[0]
        //   },
        //   {
        //     name: this.selectedOptions[1].toString(),
        //     type: 'line',
        //     showSymbol: false,
        //     data: this.echartDataArr[1]
        //   },
        //   {
        //     name: this.selectedOptions[2].toString(),
        //     type: 'line',
        //     showSymbol: false,
        //     data: this.echartDataArr[2]
        //   },
        //   {
        //     name: this.selectedOptions[3].toString(),
        //     type: 'line',
        //     showSymbol: false,
        //     data: this.echartDataArr[3]
        //   },
        //   {
        //     name: this.selectedOptions[4].toString(),
        //     type: 'line',
        //     showSymbol: false,
        //     data: this.echartDataArr[4]
        //   }

        // ]
        series: this.selectedOptions.slice(0, this.echartDataArr.length).map((option, index) => ({
          name: option.toString(),
          type: 'line',
          showSymbol: false,
          data: this.echartDataArr[index]
        }))

      }

      if (this.chartInstance) {
        this.chartInstance.setOption(this.chartOptions3)
      }
    },
    // 重置 ECharts 实例大小
    resizeHandler() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    },
    // 定时获取 ECharts 图表数据
    getChartsInterval() {
      this.interval = setInterval(() => {
        this.getChartsData()
      }, 1000)
    },
    // 获取 ECharts 图表数据
    async getChartsData() {
      if (this.paramsArr.length == 0) {
        console.log('params is empty');
        return;
      } else if (this.paramsArr.length == 1) {
        getNewChartsData(this.paramsArr[0][1], this.paramsArr[0][0], '60s').then(response => {
          // console.log(response);
          const dataArr = response.results[0].series[0].values
          // console.log('1111', dataArr);
          // const d3 = []
          // const d4 = []
          // const d5 = []
          // const d6 = []
          // const d7 = []
          // for (let i = 0; i < dataArr.length; i++) {
          //   for (let j = 0; j < this.selectedOptions.length; j++) {

          //   }
          //   d3.push({
          //     name: new Date(dataArr[i][0]).toString(),
          //     value: [
          //       new Date(dataArr[i][0]),
          //       dataArr[i][1]
          //     ]
          //   })
          //   d4.push({
          //     name: new Date(dataArr[i][0]).toString(),
          //     value: [
          //       new Date(dataArr[i][0]),
          //       dataArr[i][2]
          //     ]
          //   })
          //   d5.push({
          //     name: new Date(dataArr[i][0]).toString(),
          //     value: [
          //       new Date(dataArr[i][0]),
          //       dataArr[i][3]
          //     ]
          //   })
          //   d6.push({
          //     name: new Date(dataArr[i][0]).toString(),
          //     value: [
          //       new Date(dataArr[i][0]),
          //       dataArr[i][4]
          //     ]
          //   })
          //   d7.push({
          //     name: new Date(dataArr[i][0]).toString(),
          //     value: [
          //       new Date(dataArr[i][0]),
          //       dataArr[i][5]
          //     ]
          //   })
          // }
          // this.echartDataArr = [d3, d4, d5, d6, d7]
          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] // 注意这里是从 j+1 开始的，因为dataArr[i][0]是时间
                ]
              });
            }
          }
          this.echartDataArr = echartDataArr;

          this.updateChartOptions()
        }).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">
.el-popper {
  .el-cascader-menu {

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

}
</style>
