<template>
  <div class="event-bar-chart" :style="{ height, width }" />
</template>

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

export default {
  name: 'EventBarChart',
  mixins: [resize],
  props: {
    width: { type: String, default: '100%' },
    height: { type: String, default: '240px' },
    chartData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return { chart: null }
  },
  watch: {
    chartData: { deep: true, handler() { this.setOptions() } }
  },
  mounted() {
    this.$nextTick(() => this.initChart())
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, null, { devicePixelRatio: window.devicePixelRatio || 1 })
      this.setOptions()
    },
    setOptions() {
      if (!this.chart) return
      const { dates = [], values = [], barColor = '#2563eb' } = this.chartData
      this.chart.setOption({
        animation: true,
        animationDuration: 800,
        animationEasing: 'cubicOut',
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '3%', top: '12%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          data: dates,
          axisTick: { show: false },
          axisLine: { lineStyle: { color: '#e2e8f0' } }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { type: 'dashed', color: '#e2e8f0' } }
        },
        series: [
          {
            name: '事件量',
            type: 'bar',
            barMaxWidth: 32,
            data: values,
            itemStyle: {
              color: barColor,
              borderRadius: [4, 4, 0, 0]
            }
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.event-bar-chart { width: 100%; }
</style>
