<template>
  <!-- 图表容器，设置固定高度360px -->
  <div id="chartContainer" style="width: 100%; height: 360px;"></div>
</template>

<script>
import moment from 'moment'
import {getAction} from "@api/manage";
export default {
  name: 'DynamicLineChart',
  data() {
    return {
      chart: null,
      data: [],
      xAxisData: [],
      intervalId: null,
      url: {
        getAirQualityOnline: "/device/buDeviceOnline/getAirQualityOnline",
      },
      // 存储所有气体数据
      allGasData: {
        time: [],
        o2: [],
        co: [],
        ch4: [],
        h2s: []
      }
    };
  },
  props: {
    deviceId: {
      type: String,
      required: true,
    },
    gasType: {
      type: String,
      default: 'o2'
    }
  },
  watch: {
    deviceId(newVal, oldVal) {
      if (newVal != null) {
        this.selectQuery(newVal);
      }
    },
    gasType(newVal, oldVal) {
      // 当气体类型改变时，更新图表显示的数据
      this.updateChartDataByGasType(newVal);
    }
  },
  mounted() {
    this.initChart();
  },
  created() {
    this.setCreateData()
  },
  methods: {
    moment,
    initChart() {
      this.drawChart();
    },
    drawChart() {
      this.chart = this.$echarts.getInstanceByDom(document.getElementById("chartContainer"));
      if (!this.chart) {
        this.chart = this.$echarts.init(document.getElementById("chartContainer"));
      }

      // 根据当前气体类型获取对应的数据
      const currentGasData = this.allGasData[this.gasType] || this.data;

      const option = {
        title: {
          left: 'center',
          text: this.getChartTitle(this.gasType)
        },
        dataZoom: [
          {
            type: 'inside'
          },
        ],
        xAxis: {
          name: "时间",
          type: 'category',
          data: this.xAxisData,
          silent: false,
        },
        yAxis: {
          name: this.getYAxisName(this.gasType),
          type: 'value',
        },
        series: [
          {
            data: currentGasData,
            markLine: {
              data: [{ yAxis: this.getRiskThreshold(this.gasType),
                label: {
                  position: 'end',
                  formatter: '风险提示下限' + this.getRiskThreshold(this.gasType) + this.getGasUnit(this.gasType)
                },
                lineStyle: { color: "rgb(255,0,0)" }
              }
              ]
            },
            type: 'line',
            smooth: true,
          },
        ],
      };
      this.chart.setOption(option);
    },
    // 获取图表标题
    getChartTitle(gasType) {
      const titles = {
        'o2': '地坑氧气含量统计(当日)',
        'co': '地坑一氧化碳含量统计(当日)',
        'ch4': '地坑可燃性气体含量统计(当日)',
        'h2s': '地坑硫化氢含量统计(当日)'
      };
      return titles[gasType] || '地坑气体含量统计(当日)';
    },
    // 获取Y轴名称
    getYAxisName(gasType) {
      const names = {
        'o2': '体积浓度/%VOL',
        'co': '体积浓度/ppm',
        'ch4': '体积浓度/%LEL',
        'h2s': '体积浓度/ppm'
      };
      return names[gasType] || '体积浓度';
    },
    // 获取气体单位
    getGasUnit(gasType) {
      const units = {
        'o2': '%VOL',
        'co': 'ppm',
        'ch4': '%LEL',
        'h2s': 'ppm'
      };
      return units[gasType] || '';
    },
    // 获取风险阈值
    getRiskThreshold(gasType) {
      const thresholds = {
        'o2': 19.5,
        'co': 30,      // 示例值，可根据实际调整
        'ch4': 25,     // 示例值，可根据实际调整
        'h2s': 10      // 示例值，可根据实际调整
      };
      return thresholds[gasType] || 0;
    },
    setCreateData() {
      for (let i = 0; i < 20; i++) {
        let nowTime = this.setTime(i)
        this.xAxisData.push(nowTime)
        this.data.push(0);
      }
    },
    setTime(i) {
      let now = new Date();
      let hour = now.getHours();
      let minute = now.getMinutes();
      now.setSeconds(now.getSeconds() - 20 + i);
      let second = now.getSeconds();
      let nowTime = this.fillZero(hour) + ':' + this.fillZero(minute) + ':' + this.fillZero(second)
      return nowTime;
    },
    fillZero(str) {
      var realNum;
      if (str < 10) {
        realNum = '0' + str;
      } else {
        realNum = str;
      }
      return realNum;
    },
    selectQuery(deviceId) {
      this.xAxisData = []
      this.data = []
      // 清空所有气体数据
      this.allGasData = {
        time: [],
        o2: [],
        co: [],
        ch4: [],
        h2s: []
      };

      let param = { deviceId: deviceId };
      getAction(this.url.getAirQualityOnline, param, 'get').then(res => {
        var obj = res.result;

        // 存储所有气体数据
        if (obj["time"] != null) {
          this.allGasData.time = obj["time"];
          var timeValues = obj["time"];
          timeValues.forEach(time => {
            this.xAxisData.push(time.slice(-8));
          })
        }

        // 存储各种气体数据
        if (obj["o2"] != null) {
          this.allGasData.o2 = obj["o2"];
        }
        if (obj["co"] != null) {
          this.allGasData.co = obj["co"];
        }
        if (obj["ch4"] != null) {
          this.allGasData.ch4 = obj["ch4"];
        }
        if (obj["h2s"] != null) {
          this.allGasData.h2s = obj["h2s"];
        }

        // 根据当前选择的气体类型更新图表
        this.updateChartDataByGasType(this.gasType);
      })
    },
    // 根据气体类型更新图表数据
    updateChartDataByGasType(gasType) {
      // 获取对应气体的数据
      const gasData = this.allGasData[gasType] || [];

      // 更新图表
      this.chart.setOption({
        title: {
          text: this.getChartTitle(gasType)
        },
        yAxis: {
          name: this.getYAxisName(gasType)
        },
        xAxis: {
          data: this.xAxisData,
        },
        series: [{
          data: gasData,
          markLine: {
            data: [{
              yAxis: this.getRiskThreshold(gasType),
              label: {
                position: 'end',
                formatter: '风险提示下限' + this.getRiskThreshold(gasType) + this.getGasUnit(gasType)
              },
              lineStyle: {
                color: "rgb(255,0,0)"
              }
            }]
          }
        }],
      });
    },
    startDynamicData(deviceId) {
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
      this.intervalId = setInterval(() => {
        this.xAxisData.shift();
        this.data.shift();
        let param = { deviceId: deviceId };
        getAction(this.url.getAirQualityOnline, param, 'get').then(res => {
          var obj = res.result;
          if (obj["value"] != null) {
            var timeValues = obj["time"];
            timeValues.forEach(time => {
              this.xAxisData.push(time.slice(-8));
            })
            console.log("this.xAxisData", this.xAxisData)
            this.data.push(obj["value"]);
          } else {
            if (this.intervalId) {
              clearInterval(this.intervalId);
              this.intervalId = null;
            }
            if (this.chart) {
              this.chart.dispose();
              this.xAxisData = []
              this.data = []
              this.setCreateData()
              this.initChart();
            }
          }
        })
        this.chart.setOption({
          xAxis: {
            data: this.xAxisData,
          },
          series: [{
            data: this.data,
          }],
        });
      }, 1000);
    },
    redoChart() {
      if (this.chart) {
        this.chart.dispose();
        this.xAxisData = []
        this.data = []
        this.setCreateData()
        this.initChart();
      }
    },
  },

};
</script>

<style scoped>

</style>
