<template>
<div class="xp-rank u-fontNumber" :style="options.wrapStyle" ref="rank">
  <div
    ref="wrap"
    :class="{
      'xp-rank__wrap': true,
    }"
    :style="{
      msAnimationDuration: `${this.duration}s`,
      webkitAnimationDuration: `${this.duration}s`,
      animationDuration: `${this.duration}s`,
    }"
  >
    <div class="xp-rank__item" v-for="(item, index) in data" :style="options.itemStyle">
      <span class="xp-rank__itemIcon" :style="options.iconStyle">{{ index + 1 }}</span>
      <span class="xp-rank__itemName" :style="options.nameStyle">{{ item.name }}</span>
      <span class="xp-rank__itemValue" :style="options.valueStyle">{{ calcValue(item.value) }}</span>
      <span
        class="xp-rank__itemBar" v-show="options.showBar"
        :style="Object.assign({}, options.barStyle, {
          width: `${calcWidth(item.value)}%`
        })"
      ></span>
    </div>
  </div>
</div>
</template>

<script>
export default {
  name: 'XpRank',

  data() {
    return {
      options: {},
      timer: null,
      rankHeight: 0,
      wrapHeight: 0,
      active: false,
      duration: 0,
    }
  },

  props: {
    settings: {
      type: Object,
      default: () => {},
    },
    data: {
      type: Array,
      default: () => [],
    },
  },

  methods: {
    setBoolean(bool, ret) {
      if (bool === undefined) {
        bool = ret
      }
      return bool
    },
    setOptions() {
      let settings = this.settings || {}
      this.options = {
        autoPlay: settings.autoPlay || false, // 自动播放
        playDuration: settings.playDuration || 4000,
        isPercent: this.setBoolean(settings.isPercent, true), // 是否是百分数
        fixed: settings.fixed || 2,
        showBar: this.setBoolean(settings.showBar, true), // 是否展示进度条
        wrapStyle: settings.wrapStyle || {}, // wrap样式
        itemStyle: settings.itemStyle || {}, // item样式
        iconStyle: settings.iconStyle || {}, // icon样式
        nameStyle: settings.nameStyle || {}, // name样式
        valueStyle: settings.valueStyle || {}, // value样式
        barStyle: settings.barStyle || {}, // bar样式
      }
    },
    updateData() {
      this.setOptions()
      let options = this.options
      if (options.autoPlay) {
        this.active = true
        this.duration = options.playDuration || 20
      }
    },
    calcValue(val) {
      let options = this.options
      if (options.isPercent) {
        return `${val}%`
      }
      return val
    },
    calcWidth(val, sum) {
      if (!sum) {
        sum = this.data.map(item => item.value).reduce((prev, next) => prev + next, 0)
      }
      return val / sum * 100
    },
  },

  watch: {
    settings(newVal) {
      this.updateData()
    }
  },

  mounted() {
    this.updateData()
  },
}
</script>
