<template>
  <div class="chart_container">
    <div ref="chart" style="width: 100%; height: 500px;" />
    <button @click="getChartsData2">Fetch Data</button>
    <div ref="chart2" style="width: 100%; height: 500px;" />
    <div ref="chart3" style="width: 100%; height: 500px;" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import axios from 'axios'
import { getChartsData2 } from '@/api/dcs/dcs.js'

export default {
  name: 'EChartsComponent',
  data() {
    return {
      chartInstance: null, // ECharts 实例对象
      chartOptions: null, // ECharts 图表配置项

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

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

      interval: null,
      dateArr: [],
      dataArr: [],
      data: [],

      data2: [],
      data3: [],
      data4: [],
      data5: [],
      data6: [],

      apiUrl: 'http://192.168.110.83:38086/query',
      org: 'myorg',
      db: 'mybucket',
      query: 'SELECT MEAN(*) FROM "mybucket" WHERE time >= now() - 1h GROUP BY time(60s) FILL(none)',
      token: 'PRl4xM7wWDHeot7Lpih40qX4kTpvS5T1QyG2MNZ6YBR0InsOE_lN-McaHCDoJr-UxhZN_tEJbUPP02rHd5I5Cw=='
    }
  },
  mounted() {
    this.initChart()
    this.getChartsInterval()
    // this.getChartsData2()
  },
  beforeDestroy() {
    // 在组件销毁之前销毁 ECharts 实例
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
    if (this.chartInstance2) {
      this.chartInstance2.dispose()
    }
    if (this.chartInstance3) {
      this.chartInstance3.dispose()
    }
    clearInterval(this.interval)
  },
  methods: {
    // 初始化 ECharts 实例
    initChart() {
      this.chartInstance2 = echarts.init(this.$refs.chart2)
      this.chartInstance3 = echarts.init(this.$refs.chart3)

      this.chartInstance = echarts.init(this.$refs.chart)
      window.addEventListener('resize', this.resizeHandler)
    },
    // 更新 ECharts 图表配置项
    updateChartOptions() {
      this.chartOptions = {
        tooltip: {
          trigger: 'axis',
          position: function(pt) {
            return [pt[0], '10%']
          }
        },
        title: {
          left: 'center',
          text: '阀门开度、温度统计表'
        },
        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: [
          {
            name: 'KD1',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.data
          }
          // {
          //   name: 'KD2',
          //   type: 'line',
          //   smooth: true,
          //   symbol: 'none',
          //   areaStyle: {},
          //   data: this.data2
          // }
        ]
      }

      this.chartOptions2 = {
        xAxis: {
          type: 'category',
          data: this.dateArr
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.dataArr,
            type: 'line'
          }
        ]
      }

      this.chartOptions3 = {
        title: {
          text: '设备开度动态曲线'
        },
        tooltip: {
          trigger: 'axis',
          // formatter: function (params) {
          //   params = params[0];
          //   var date = new Date(params.name);
          //   return (
          //     date.getDate() +
          //     '/' +
          //     (date.getMonth() + 1) +
          //     '/' +
          //     date.getFullYear() +
          //     ' : ' +
          //     params.value[1]
          //   );
          // },
          axisPointer: {
            animation: false
          }
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          }
        },
        yAxis: [
          {
            name: '开度',
            type: 'value',
            // boundaryGap: [0, '100%'],
            // splitLine: { // 隐藏分行线
            //   show: false
            // }
            // inverse: true, // 关键：反转刻度方向
          },
          {
            name: '温度',
            type: 'value',
            // boundaryGap: [0, '100%'],
            splitLine: { // 隐藏分行线
              show: false
            }
          },
        ],
        series: [
          {
            name: '开度',
            type: 'line',
            yAxisIndex: 0,
            // lineStyle: {
            //   width: 1
            // },
            showSymbol: false,
            data: this.data2,
          },
          {
            name: '温度1',
            type: 'line',
            yAxisIndex: 1,
            showSymbol: false,
            data: this.data3,
          },
          {
            name: '温度2',
            type: 'line',
            yAxisIndex: 1,
            showSymbol: false,
            data: this.data4,
          },
          {
            name: '温度3',
            type: 'line',
            yAxisIndex: 1,
            showSymbol: false,
            data: this.data5,
          },
          {
            name: '温度4',
            type: 'line',
            yAxisIndex: 1,
            showSymbol: false,
            data: this.data6,
          }

        ]
      }
      if (this.chartInstance) {
        this.chartInstance.setOption(this.chartOptions)
      }
      if (this.chartInstance2) {
        this.chartInstance2.setOption(this.chartOptions2)
      }
      if (this.chartInstance3) {
        this.chartInstance3.setOption(this.chartOptions3)
      }
    },
    // 重置 ECharts 实例大小
    resizeHandler() {
      if (this.chartInstance) {
        this.chartInstance.resize()// 重置大小
      }
      if (this.chartInstance2) {
        this.chartInstance2.resize()
      }
      if (this.chartInstance3) {
        this.chartInstance3.resize()
      }
    },
    // 定时获取 ECharts 图表数据
    getChartsInterval() {
      this.interval = setInterval(() => {
        this.getChartsData2()
      }, 1000)
    },
    // 获取 ECharts 图表数据
    async getChartsData2() {
      getChartsData2().then(response => {
        // console.log(response);
        const dataArr = response.results[0].series[0].values
        // let d = [];
        // console.log('dataArr',dataArr);
        // console.log(this.getLocalizedTime(new Date(dataArr[0][0])));
        const d = []
        const d1 = []
        const d2 = []
        const d3 = []
        const d4 = []
        const d5 = []
        const d6 = []
        const d7 = []
        for (let i = 0; i < dataArr.length; i++) {
          d1.push(this.getLocalizedTime(new Date(dataArr[i][0])))
          d2.push(dataArr[i][1])

          d.push([new Date(dataArr[i][0]).getTime(), (dataArr[i][1])])

          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][60]
            ]
          })
          d5.push({
            name: new Date(dataArr[i][0]).toString(),
            value: [
              new Date(dataArr[i][0]),
              dataArr[i][59]
            ]
          })
          d6.push({
            name: new Date(dataArr[i][0]).toString(),
            value: [
              new Date(dataArr[i][0]),
              dataArr[i][58]
            ]
          })
          d7.push({
            name: new Date(dataArr[i][0]).toString(),
            value: [
              new Date(dataArr[i][0]),
              dataArr[i][57]
            ]
          })
        }
        this.data = d

        this.dataArr = d2
        this.dateArr = d1

        this.data2 = d3
        this.data3 = d4
        this.data4 = d5
        this.data5 = d6
        this.data6 = d7
        // console.log("data:", this.data2);
        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 scoped></style>
