<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
import resize from "@/views/dashboard/mixins/resize";
require('echarts/theme/macarons') // echarts theme

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    data: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    data: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.data)
    },
    setOptions(data) {
      let option = {
        grid: {
          top: 4,
          left: 4,
          right: 4,
          bottom: 4,
          show: false,
        },
        tooltip: {
          trigger: 'axis',
          show: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          show: false,
          data: data.map(item => item.x)
        },
        yAxis: {
          show: false,
          type: 'value',
          min: 'dataMin',
          max: 'dataMax',
        },
        series: [{
          name: "设备数量",
          color: '#165DFF',
          data: data.map(item => item.value),
          type: 'line',
          smooth: true
        }]
      };
      this.chart.setOption(option)
    }
  }
}
</script>
