<template>
  <div :id="id" ref="techy-bar-chart" class="techy-chart" />
</template>

<script>
import echarts from 'echarts'
import resize from '@/views/OperationalOverview/components/mixins/resize'

export default {
  name: 'TechyBarChart',
  mixins: [resize],
  /** Fn.1: 保证全屏切换时也刷新图表 ，应该在每个父组件为flex:1的echarts组件里都加上，以确保能正确地伸缩 */
  inject: ['resizeStatus'],
  /** End Fn.1 */
  props: {
    id: {
      type: String,
      default: 'default-id'
    },
    title: {
      type: String,
      default: 'default-title'
    },
    xData: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const colors = ['#61A5E8', '#7ECF51', '#EECB5F']

    return {
      chart: null,
      option: {
        // default option
        grid: {
          top: '20%',
          left: '8%',
          bottom: '16px',
          right: '8%'
        },
        title: {
          text: this.title,
          left: 'center',
          textStyle: {
            color: '#fffa',
            fontSize: 12
          }
        },
        xAxis: {
          type: 'category',
          data: this.xData,
          axisTick: {
            show: false
          },
          axisLabel: {
            fontSize: 8
            // rotate: 10
          },
          axisLine: {
            lineStyle: {
              color: '#fffa'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            fontSize: 10,
            align: 'left',
            color: '#fffa'
          },
          axisTick: { show: false },
          splitLine: {
            lineStyle: {
              color: '#fffa'
            }
          }
        },
        series: {
          type: 'bar',
          barMaxWidth: 30,
          data: this.seriesData.map((value, index) => ({
            itemStyle: {
              color: colors[index]
            },
            value
          }))
        }
      }
    }
  },
  computed: {
    shouldResize() {
      return this.resizeStatus()
    }
  },
  watch: {
    shouldResize(val, oldVal) {
      setTimeout(() => {
        this.chart.resize()
      }, 250)
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (!this.chart) this.chart = echarts.init(this.$refs['techy-bar-chart'])
      this.chart.setOption(this.option)
    })
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose()
    this.chart = null
  },
  methods: {}
}
</script>

<style scoped>
.techy-chart {
  height: 100%;
  width: 100%;
}

.techy-chart >>> div {
  width: 100% !important;
  height: 100% !important;
}
</style>
