<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'
echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    value: Object,
    text: String,
    subtext: String
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    getSeries () {
      let series = []
      let i = 0
      for (let data of this.value.seriesData) {
        let name = ''
        if (this.value.legend) {
          name = this.value.legend[i++]
        }
        series.push({
          name: name,
          type: 'bar',
          data: data
        })
      }
      return series
    },
    initBar () {
      // let legend = this.value.legend
      // let xAxisData = this.value.xAxisData
      // let series = this.getSeries()
      let { xAxisData, seriesData } = this.value
      let option = {
        title: {
          text: this.text,
          subtext: this.subtext,
          x: 'left'
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#47B7FF'
          // axisPointer: {
          //   type: 'cross'
          // }
        },
        grid: {
          bottom: 30
          // top: '15%',
          // left: '1.2%',
          // right: '3%',
          // bottom: '12%',
          // containLabel: true
        },
        // legend: {
        //   x: 'right',
        //   top: 'top',
        //   data: legend
        // },
        xAxis: {
          type: 'category',
          data: xAxisData,
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          show: true

        },
        series: [
          {
            name: '销量',
            type: 'bar',
            barWidth: 12,
            // label: {
            //   show: true, // 开启显示
            //   position: 'top' // 在上方显示
            // // textStyle: { // 数值样式
            // //   color: '#333',
            // //   fontSize: 18
            // // }
            // },
            data: seriesData
          }
        ]
      }
      this.dom = echarts.init(this.$refs.dom, 'tdTheme')
      this.dom.setOption(option)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initBar()
      on(window, 'resize', this.resize)
    })
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  },
  watch: {
    value () {
      this.$nextTick(() => {
        if (this.value) {
          this.initBar()
        }
      })
    }
  }
}
</script>
