<template>
  <div ref="chartsWrapperRef" class="diagrams-chart-container"></div>
</template>

<script>
import echarts from 'echarts'

export default {
  props: {
    rankingData: { type: Array, default: () => [] },
    categoryAlias: { type: String, default: 'productName' },
    valueAlias: { type: String, default: 'productTransactionTotal' },
    animate: { type: Boolean, default: false }
  },
  data() {
    return {
      instance: null,
      chartData: {},
      animateTimer: null,
      startIndex: 0
    }
  },
  watch: {
    rankingData: {
      handler(newData) {
        this.chartData = newData
        this.updateChartData()
      },

      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.init()
  },

  methods: {
    init() {
      this.instance = echarts.init(this.$refs.chartsWrapperRef)
      this.instance.setOption({
        grid: { left: '12%', right: '3%', top: '2%', bottom: '9%' },
        xAxis: { type: 'value', show: false },
        yAxis: {
          type: 'category',
          axisLine: { show: false },
          axisTick: { show: false }
        }
      })
      this.updateChartData()
    },

    updateChartData() {
      if (!this.instance || !this.instance.setOption) {
        return
      }
      this.instance.setOption({
        yAxis: {
          data: this.chartData.map((item) => item[this.categoryAlias]).slice(this.startIndex, this.startIndex + 5).reverse(),
          axisLabel: {
            color: '#A4A4A4',
            fontSize: 14,
            formatter(value) {
              const valueStr = value.length > 5 ? value.slice(0, 5) + '...' : value
              return '{lineHeight|' + valueStr + '}'
            },
            rich: { lineHeight: { lineHeight: 18, color: '#A4A4A4', fontSize: 14 } }
          }
        },
        series: [
          {
            zlevel: 100,
            name: '销量',
            type: 'bar',
            data: this.chartData.map((item) => item[this.valueAlias]).slice(this.startIndex, this.startIndex + 5).reverse(),
            barWidth: '16px',
            itemStyle: { borderRadius: 5, color: '#00CE7F' },
            label: { show: true, precision: 1, position: 'right', valueAnimation: true, fontFamily: 'monospace', color: '#3d3d3d' }
          }
        ]
      })
      this.animate && this.startAnimate()
    },

    startAnimate() {
      if (this.animateTimer) {
        this.stopAnimate()
      }
      this.animateTimer = setInterval(() => {
        if (this.startIndex >= 15) {
          this.startIndex = -1
        }
        this.startIndex += 1
        this.updateChartData()
      }, 1000)
    },

    stopAnimate() {
      clearInterval(this.animateTimer)
      this.animateTimer = null
    },

    resize() {
      this.instance.resize()
    }
  }
}
</script>

<style lang="scss" scoped>
.diagrams-chart-container {
  width: 729px;
  height: 265px;
}
</style>
