<template>
  <div class="box">
    <div class="kwh">
      <div class="block">
        <div
          class="current_kwh"
          :style="'width:' + powerP"
          :class="power > 30 ? 'green' : 'red'"
        />
      </div>
      {{ power }}%
    </div>
    <div>
      <!-- {{ curveInfo.id }} -->
      <div ref="chart" style="height: 300px; width: 100%" />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'CurveTableCH4',
  props:{
    title:{
      type: String,
      default:''
    },
    line: {
      type: Array,
      default:()=>[]
    },
    row:{
      type: Array,
      default:()=>[]
    },
    unit: {
      type: String,
      default:''
    },
    power: {
      type: Number,
      default:0
    }
  },
  data() {
    return {
      myChart: null,
      options: {
        title: {
          text: this.title,
          x: 'right'
        },
        tooltip: {},
        xAxis: {
          inverse: true,
          data: this.row,
          axisTick: {
            inside: true,
            alignWithLabel: true
          },
          axisLabel: {
            // interval:0,
            // rotate:-30, //x轴文字倾斜
            padding: [0, 0, 100, 0] // 文字左右定位
          },
          splitLine: {
            interval: '0'
          }
        },
        yAxis: { // y轴设置
          axisLine: {
            show: true // 隐藏y轴轴线
          },
          axisTick: {
            inside: true
          },
          type: 'value',
          name: this.unit,
          axisLabel: { // y轴设置为%
            show: true,
            interval: 'auto',
            formatter: '{value}'
          },
          max: 100, // 最大值
          min: 0 // 最小值
        },
        series: [
          {
            name: this.unit,
            type: 'line',
            data: this.line
          }
        ],
        grid: { left: 50 }
      }
    }
  },
  computed: {
    powerP() {
      const percent = this.power / 100
      return percent * 30 + 'px'
    }
  },
  watch: {
    row: {
      handler(newVal) {
        if (newVal) {
          this.options.xAxis.data = newVal
          this.options.series[0].data = this.line
          const max = Math.floor(Math.max(...this.line) * 1.5)
          this.options.yAxis.max = max>1?max:1
          this.refreshChart()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      this.myChart = echarts.init(this.$refs.chart)
      // 绘制图表
      this.myChart.setOption(this.options)
    },
    refreshChart(){
      this.myChart.setOption(this.options, true)
    }
  }
}
</script>

<style>
.box {
  position: relative;
}

.kwh {
  position: absolute;
  left: 16px;
  top: 6px;
}

.block {
  width: 30px;
  height: 13px;
  display: inline-block;
  border: 1px solid #000;
}

.current_kwh {
  height: 100%;
}

.green {
  background: green;
}

.red {
  background: red;
}
</style>
