<template>
  <div class="j-bar-chart" ref="jBarChart"></div>
</template>

<script>
import echarts from 'echarts4'
export default {
  props: {
    title: {
      type: Object,
      default: () => ({
        text: ''
      })
    },
    grid: {
      type: Array,
      default: () => ['15%', '2%', '2%', '2%']
    },
    color: {
      type: Array,
      default: () => ['#5EC2D0', '#61D2B9', '#F67F51', '#7851F6']
    },
    xData: {
      required: true,
      type: Array,
      default: () => []
    },
    yData: {
      type: Array,
      default: () => []
    },
    series: {
      type: Array,
      default: () => []
    }
  },
  mounted() {
    this.jBarChart = echarts.init(this.$refs.jBarChart)
    this.createChart()
  },
  data() {
    return { jBarChart: null }
  },
  methods: {
    createChart() {
      const { title, grid, color, xData, yData, series } = this
      const configSeries = (series => {
        if (series.length) {
          return series.map(item => ({ data: item.data, type: 'bar', barWidth: 15 }))
        } else {
          return [{ data: yData, type: 'bar', barWidth: 15 }]
        }
      })(series)

      const option = {
        title: {
          text: title.text,
          right: 20,
          textStyle: {
            fontSize: '14px',
            color: '#5EC2D0',
            fontWeight: 'normal'
          }
        },
        grid: {
          top: grid[0],
          right: grid[1],
          bottom: grid[2],
          left: grid[3],
          containLabel: true
        },
        color,
        xAxis: {
          type: 'category',
          data: xData,
          axisLine: {
            show: true,
            lineStyle: {
              type: [5, 10]
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#fff'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          splitNumber: 4,
          splitLine: {
            show: true,
            lineStyle: {
              type: [5, 10],
              color: '#323D50'
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              type: [5, 10]
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#fff'
            }
          },
          axisTick: {
            show: false
          }
        },
        series: configSeries
      }
      this.jBarChart.setOption(option)
    }
  }
}
</script>

<style>
.j-bar-chart {
  width: 100%;
  height: 100%;
}
</style>
