<template>
  <div>
    <div
        ref="chartContainer"
        :style="{width: '500px', height: '400px'}"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseLeave"
    ></div>
    <button @click="move('left')">左</button>
    <button @click="move('right')">右</button>
  </div>
</template>

<script>
export default {
  name: 'DynamicChart',
  data() {
    return {
      myChart: null,
      count: 11,
      categories: this.generateCategories(),
      categories2: Array.from({length: 10}, (_, i) => 10 - i - 1),
      data: Array.from({length: 10}, () => Math.round(Math.random() * 1000)),
      data2: Array.from({length: 10}, () => +(Math.random() * 10 + 5).toFixed(1)),
      isMouseDown: false,
      lastMousePosition: null
    };
  },
  mounted() {
    this.initChart();
    this.startDataUpdater();
  },
  beforeDestroy() {
    clearInterval(this.dataUpdater);
  },
  methods: {
    move(direction) {
      // 停止自动更新
      clearInterval(this.dataUpdater);

      if (direction === 'left') {
        this.data.unshift(Math.round(Math.random() * 1000));
        this.data.pop();

        this.data2.unshift(+(Math.random() * 10 + 5).toFixed(1));
        this.data2.pop();

        this.categories.unshift(new Date().toLocaleTimeString().replace(/^\D*/, ''));
        this.categories.pop();

        this.categories2.unshift(this.count--);
        this.categories2.pop();
      } else if (direction === 'right') {
        this.data.push(Math.round(Math.random() * 1000));
        this.data.shift();

        this.data2.push(+(Math.random() * 10 + 5).toFixed(1));
        this.data2.shift();

        this.categories.push(new Date().toLocaleTimeString().replace(/^\D*/, ''));
        this.categories.shift();

        this.categories2.push(this.count++);
        this.categories2.shift();
      }

      this.myChart.setOption({
        xAxis: [
          {data: this.categories},
          {data: this.categories2}
        ],
        series: [
          {data: this.data},
          {data: this.data2}
        ]
      });
    },
    generateCategories() {
      let now = new Date();
      let res = [];
      let len = 10;
      while (len--) {
        res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
        now = new Date(+now - 2000);
      }
      return res;
    },
    initChart() {
      // 初始化ECharts实例
      this.myChart = this.$echarts.init(this.$refs.chartContainer);

      const option = {
        title: {
          text: 'Dynamic Data'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        legend: {},
        dataZoom: {
          show: false,
          start: 0,
          end: 100
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: true,
            data: this.categories
          },
          {
            type: 'category',
            boundaryGap: true,
            data: this.categories2
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            name: 'Price',
            max: 30,
            min: 0,
            boundaryGap: [0.2, 0.2]
          },
          {
            type: 'value',
            scale: true,
            name: 'Order',
            max: 1200,
            min: 0,
            boundaryGap: [0.2, 0.2]
          }
        ],
        series: [
          {
            name: 'Dynamic Bar',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: this.data
          },
          {
            name: 'Dynamic Line',
            type: 'line',
            data: this.data2
          }
        ]
      };

      this.myChart.setOption(option);
    },
    startDataUpdater() {
      this.dataUpdater = setInterval(() => {
        let axisData = new Date().toLocaleTimeString().replace(/^\D*/, '');

        this.data.shift();
        this.data.push(Math.round(Math.random() * 1000));

        this.data2.shift();
        this.data2.push(+(Math.random() * 10 + 5).toFixed(1));

        this.categories.shift();
        this.categories.push(axisData);

        this.categories2.shift();
        this.categories2.push(this.count++);

        this.myChart.setOption({
          xAxis: [
            {data: this.categories},
            {data: this.categories2}
          ],
          series: [
            {data: this.data},
            {data: this.data2}
          ]
        });
      }, 2100);
    },
    handleMouseDown(event) {
      this.isMouseDown = true;
      this.lastMousePosition = event.clientX;
    },
    handleMouseMove(event) {
      if (!this.isMouseDown) return;

      const currentMousePosition = event.clientX;
      const threshold = 100; // 需要拖动多少像素才触发移动

      if (Math.abs(currentMousePosition - this.lastMousePosition) >= threshold) {
        if (currentMousePosition > this.lastMousePosition) {
          this.move('right');
        } else {
          this.move('left');
        }
        this.lastMousePosition = currentMousePosition;
      }
    },
    handleMouseUp() {
      this.isMouseDown = false;
      this.lastMousePosition = null;
    },
    handleMouseLeave() {
      this.isMouseDown = false;
      this.lastMousePosition = null;
    }
  }
};
</script>
