<template>
  <section>
    <div class="chart-contain">
      <normal-echart v-if="echartsOption" :chart-id="id" :option="echartsOption" @onClick="getCode" />
    </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,
      dayList: []
    }
  },
  watch: {
    chartData: {
      handler(newV) {
        this.setChart()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getCode(val) {
      this.$emit('code', val, this.dayList, this.chartData)
    },
    setChart() {
      if (!this.chartData) return
      this.dayList = this.chartData.yaxis.map(item => { return item.name })
      const newArr = this.chartData.yaxis.filter(item => { return item.name !== '全部' })
      const colorArr = ['#409EFF', '#F8CE5C', '#F2904F', '#5EE2BE', '#D873F5', '#7479F5']
      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.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: newArr.map(item => ({ ...item, type: 'bar', stack: '总和', barWidth: '20px' }))
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-contain {
  position: relative;
  height: 400px;
  width: 84%;
  margin: 20px auto;
}

</style>
