<template>
  <div :id="id" :class="className" :style="{ height: height, width: 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'
    },
    width: {
      type: String,
      default: '600px'
    },
    height: {
      type: String,
      default: '400px'
    },
    title: {
      type: String,
      default: ''
    },
    desc: {
      type: String,
      default: ''
    },
    showTitle: {
      type: String,
      default: ''
    },
    seriesData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    legendData() {
      const data = Object.assign([], this.seriesData)
      const out = []
      data.map(item => {
        out.push(item.name)
      })
      return out
    },
    barData() {
      const data = Object.assign([], this.seriesData)
      const out = []
      data.map(item => {
        out.push(item.value)
      })
      return out
    }
  },
  watch: {
    seriesData: {
      handler(newVal, oldVal) {
        this.initChart()
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        this.chart = echarts.init(document.getElementById(this.id))
        this.chart.clear()
        this.chart.setOption({
          color: ['#3398DB'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: this.legendData,
              axisTick: {
                alignWithLabel: true
              }
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '订单数量',
              type: 'bar',
              barWidth: '60%',
              data: this.barData
            }
          ]
        })
        window.onresize = this.chart.resize
      })
    }
  }
}
</script>
