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

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    title: {
      type: String,
      default: 'line'
    },
    width: {
      type: String,
      default: '500px'
    },
    height: {
      type: String,
      default: '400px'
    },
    lineData: {
      type: Array,
      default: () => {
        return []
      }
    },
    description: {
      type: String,
      default: ''
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    format: {
      type: String,
      default: 'HH:mm:ss'
    },
    step: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    lineData: function(val) {
      this.updateChart(val)
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    dispatch(action) {
      this.chart.dispatchAction(action)
    },
    updateChart(data) {
      this.chart.setOption({
        series: [{
          type: 'line',
          showSymbol: false,
          clip: true,
          data: data
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      let config = {
        tooltip: {},
        xAxis: {
          name: 'x',
          minorTick: {
            show: true
          },
          splitLine: {
            lineStyle: {
              color: '#999'
            }
          },
          minorSplitLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        yAxis: {
          name: 'y',
          max: function(value) {
            return (value.max + 2).toFixed(2)
          },
          min: function(value) {
            return (value.min - 2).toFixed(2)
          },
          minorTick: {
            show: true
          },
          splitLine: {
            lineStyle: {
              color: '#999'
            }
          },
          minorSplitLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        series: [{
          type: 'line',
          showSymbol: false,
          clip: true,
          data: this.lineData
        }]
      }
      config = {
        ...config,
        ...this.config
      }

      this.chart.setOption(config)
      // this.chart.on('datazoom', (val) => {
      //   const params = {
      //     type: 'functionLine',
      //     val: val.batch[0]
      //   }
      //   this.$emit('datazoom', params)
      // })
    }
  }
}
</script>
