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

<script>

import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { parseTime } from '@/utils/index.js'
// import { emit } from 'cluster'
// eslint-disable-next-line no-unused-vars
const animationDuration = 6000

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
    },
    barPastureData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      sourceDate: []
    }
  },
  watch: {
    barPastureData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
        console.log(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.barPastureData)
    },
    setOptions({ sourceDate, text } = {}) {
      this.chart.setOption({
        title: {
          text: '最近12个月维修同期对比',
          subtext: ''
        },
        legend: { x: 'right' },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        dataset: {
          source: sourceDate
          // source: [
          //   ['product', '去年同期', '预算', '实际']
          //   // ['10月', 433, 85.8, 93.7],
          //   // ['9月', 83.1, 73.4, 55.1],
          //   // ['8月', 86.4, 65.2, 82.5],
          //   // ['7月', 72.4, 53.9, 39.1]
          // ]
        },
        xAxis: { type: 'category', name: '最近12个月', formatter: '' },
        yAxis: { name: '元' },
        grid: [
          { left: '15%', right: '17%' }
        ],
        series: [
          { type: 'bar' },
          { type: 'bar' },
          { type: 'bar' }
        ]
      })
      const that = this
      // 点击柱状图拿到对应内容
      this.chart.on('click', function(params) {
        // console.log(parseTime(new Date(), '{y}') + '-' + params.name.substring(0, 2))
        that.$emit('chartClick', parseTime(new Date(), '{y}') + '-' + params.name.substring(0, 2))
      })
    }
  }
}
</script>
