<template>
  <section>
    <div class="chart-contain">
      <normal-echart v-if="echartsOption" :chart-id="id" :option="echartsOption" @onClick="chartClick" />
    </div>
  </section>
</template>
<script>
import normalEchart from '@/components/chart/normalEchart'
export default {
  components: { normalEchart },
  props: {
    id: {
      type: String,
      default: 'status-stay-chart',
      required: false
    },
    chartData: {
      type: Object,
      default: () => null,
      required: false
    }
  },
  data() {
    return {
      echartsOption: null
    }
  },
  watch: {
    chartData: {
      handler(newV) {
        this.setChart()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    setChart() {
      if (!this.chartData) return
      const newArr = this.chartData.yaxis.filter(item => { return item && (item.name !== '全部') })
      const colorArr = ['#409EFF', '#F8CE5C', '#F2904F', '#5EE2BE', '#D873F5', '#7479F5']
      let series = null
      if (this.chartData.type === '0') {
        const childArr = this.chartData.xaxis.map((item, index) => {
          return {
            value: this.chartData.yaxis[0] && this.chartData.yaxis[0].data[index] || 0,
            idList: this.chartData.yaxis[0] && this.chartData.yaxis[0].idList[index] || []
          }
        })
        series = [{
          name: '数量', type: 'bar', barWidth: '20px', data: childArr,
          itemStyle: { normal: { label: { show: true, formatter: '{c}', position: 'top' }}}
        }]
      } else {
        series = newArr.map(item => (
          { ...item, type: 'bar', stack: '总和', barWidth: '20px' }
        ))
      }
      this.echartsOption = {
        color: colorArr,
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'line' },
          formatter: params => {
            let total = 0
            let backString = ``
            params.map((item, index) => {
              total = total + item.value
              backString = backString + `<span style="color: ${colorArr[index] || ''}">${item.seriesName}</span>：${item.value}个</br>`
            })
            return backString + `<span style="color: #F04864">总和</span>：${total}个`
          }
        },
        legend: { data: newArr.map(item => { return item && (item.name !== '全部') }), left: 0, top: 0 },
        grid: { left: '0', right: '0', top: '8%', bottom: '0', containLabel: true },
        xAxis: { type: 'category', data: this.chartData.xaxis, axisTick: { alignWithLabel: true }, axisLabel: { interval: 0, rotate: 40 }},
        yAxis: { type: 'value', axisLine: { show: false }, splitLine: { lineStyle: { type: 'dashed' }}, axisLabel: { formatter: '{value}个' }},
        series
      }
    },
    chartClick(param) {
      this.$emit('onClick', param)
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-contain {
  position: relative;
  height: 320px;
  width: 84%;
  margin: 20px auto;
}

</style>
