<template>
  <div class="goods-ranking-chart" ref="goodsRankingChartRef"></div>
</template>

<script>
import echartsMixin from '../mixin/echarts'
export default {
  mixins: [echartsMixin('goodsRankingChartRef')],
  data() {
    return {
      staticOptions: {
        grid: { left: '30%', right: '3%', top: '0%', bottom: '1%' },
        xAxis: { type: 'value', show: false },
        yAxis: {
          type: 'category',
          axisLine: { show: false },
          axisTick: { show: false },
          data: [],
          axisLabel: {
            color: '#A4A4A4',
            fontSize: 12,
            formatter(value) {
              const MAX_LENGTH = 7
              const SPLIT_LENGTH = 5
              if (value.length <= MAX_LENGTH) {
                return value
              }
              const pattern = new RegExp(`(.{${SPLIT_LENGTH}})(.{1,${SPLIT_LENGTH}})`)
              const replacement = '$1\n$2'
              return value.replace(pattern, replacement) + (value.length > SPLIT_LENGTH * 2 ? '...' : '')
            }
          }
        },
        series: {
          zlevel: 100,
          name: '销量',
          type: 'bar',
          data: [],
          barWidth: '16px',
          itemStyle: { borderRadius: 10, color: '#FFC117' },
          label: { show: true, precision: 1, position: 'right', valueAnimation: true, fontFamily: 'monospace', color: '#3d3d3d' }
        }
      },

      timer: null
    }
  },

  methods: {
    update(data) {
      if (!data || (Array.isArray(data) && !data.length)) return
      if (this.timer) this.clearTimer()
      let index = 0

      this.setChartData(data, index)

      this.timer = setInterval(() => {
        if (data.length - 9 === index) {
          index = 0
        }
        this.setChartData(data, index)
        index++
      }, 1000)
    },

    clearTimer() {
      clearInterval(this.timer)
      this.timer = null
    },

    setChartData(data, index) {
      const d = data.slice(index, index + 9)
      const goodsName = []
      const goodsCount = []

      d.forEach((item) => {
        goodsName.push(item.productName)
        goodsCount.push(item.productTransactionTotal)
      })

      this.instance.setOption({
        yAxis: { data: goodsName.reverse() },
        series: { data: goodsCount.reverse() }
      })
    }
  },

  beforeDestroy() {
    this.clearTimer()
  }
}
</script>

<style lang="scss" scoped>
.goods-ranking-chart {
  height: 370px;
}
</style>
