<template>
<div class="xp-count u-fontNumber" :style="options.wrapStyle">
  <span
    v-if="options.prefix" class="xp-count__prefix" :style="options.prefixStyle"
  >{{ options.prefix }}</span>
  <template v-for="(s, index) in str">
    <span
      v-if="s !== ',' && s !== '.'"
      class="xp-count__num"
      :style="options.intStyle"
    >{{ s }}</span>
    <span
      v-if="s === ','"
      class="xp-count__split"
      :style="options.splitStyle"
    >{{ s }}</span>
    <span
      v-if="s === '.'"
      class="xp-count__dot"
      :style="options.dotStyle"
    >{{ s }}</span>
  </template>
  <span
    v-if="options.suffix" class="xp-count__suffix" :style="options.suffixStyle"
  >{{ options.suffix }}</span>
</div>
</template>

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

  data() {
    return {
      str: [],
      options: {},
    }
  },

  props: {
    number: {
      type: [Number, String],
      default: 0,
    },
    settings: {
      type: Object,
      default: () => {},
    },
  },

  methods: {
    setBoolean(bool, ret) {
      if (bool === undefined) {
        bool = ret
      }
      return bool
    },
    toThousands(num = 0) { // 千分位函数
      num = num.toString()
      let float = ''
      let isFloat = num.indexOf('.') > -1
      if (isFloat) {
        let arr = num.split('.')
        num = arr[0]
        float = '.' + arr[1]
      }
      return num.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + float
    },
    setOptions() {
      let settings = this.settings || {}
      this.options = {
        number: settings.number || 0,
        isFloat: settings.isFloat || false, // 是否是浮点数
        fixed: settings.fixed || 2,
        split: this.setBoolean(settings.split, true), // 是否有千分位
        prefix: settings.prefix || '', // 前缀，一般为¥
        suffix: settings.suffix || '', // 后缀，一般为元
        wrapStyle: settings.wrapStyle || {}, // wrap样式
        intStyle: settings.intStyle || {}, // 整数样式
        splitStyle: settings.splitStyle || settings.intStyle || {}, // 千分位样式
        dotStyle: settings.dotStyle || settings.splitStyle || {}, // 小数点样式
        decimalStyle: settings.decimalStyle || {}, // 小数样式
        prefixStyle: settings.prefixStyle || {}, // 前缀样式
        suffixStyle: settings.suffixStyle || {}, // 后缀样式
      }
    },
    updateData() {
      this.setOptions(this.settings)
      let options = this.options
      let num = this.number || options.number
      if (options.isFloat) {
        num = num.toFixed(options.fixed)
      }
      if (options.split) {
        num = this.toThousands(num)
      }
      num = num.toString()
      this.str = num.split('')
    }
  },

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

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

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