<template>
<chart class="xp-pie" :options="options" ref="pie" auto-resize></chart>
</template>

<script>
import { setOptions } from './options'

export default {
  name: 'XpPie',

  data() {
    return {
      options: {},
      timer: null, // 轮播timer
    }
  },

  props: {
    settings: {
      type: Object,
      default: () => {}
    },
    callback: {
      type: Function,
      default: () => {}
    },
    outerPlay: {
      type: Boolean,
      default: false
    },
    outerIndex: { // 外部index
      type: Number,
      default: -1
    },
  },

  methods: {
    doAutoPlay() {
      let pie = this.$refs.pie
      let series = this.options.series[0]
      let dataIndex = 0
      let dataLen = series.data.length
      clearInterval(this.timer)
      if (this.options.autoPlay) {
        this.timer = setInterval(() => {
          pie.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex
          })
          dataIndex = (dataIndex + 1) % dataLen
          pie.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex
          })
        }, this.options.playDuration)
        // 联动外部函数
        this.callback && this.callback(dataIndex, series.data[dataIndex])
      } else {
        clearInterval(this.timer)
      }
    }
  },

  watch: {
    settings(newVal) {
      if (!this.timer) {
        this.options = setOptions(this.settings)
        this.doAutoPlay()
      }
    },
    outerIndex(newVal) {
      let pie = this.$refs.pie
      let series = this.options.series[0]
      pie.dispatchAction({
        type: 'downplay',
        seriesIndex: 0,
      })
      pie.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: newVal,
      })
      // 联动外部函数
      this.callback && this.callback(newVal, series.data[newVal])
    },
  },

  mounted() {
    this.options = setOptions(this.settings)
    this.doAutoPlay()
  },

  beforeDestroy() {
    this.timer && clearInterval(this.timer)
  },
}
</script>
