<template>
  <div>
    <el-tooltip :offset="30" :disabled="!tooltip" placement="top" effect="light">
      <template #content>
        <slot name="tooltip"></slot>
      </template>
      <div class="statistics-item-container">
        <div :style="{ textAlign: center ? 'center' : 'left' }" class="title">{{ title }}</div>
        <div :style="{ textAlign: center ? 'center' : 'left' }" class="value" ref="valueRef">{{ value }}</div>
      </div>
    </el-tooltip>
  </div>
</template>

<script>
import { CountUp } from 'countup.js'
import { formatBigNumber } from '../utils/utils'

export default {
  props: {
    title: {
      type: String,
      required: true
    },

    value: {
      type: [Number, String],
      required: true
    },

    numberAnimate: {
      type: Boolean,
      default: true
    },

    center: {
      type: Boolean,
      default: false
    },

    tooltip: {
      type: Boolean,
      default: false
    },

    format: {
      type: Function
    }
  },

  watch: {
    value: {
      handler() {
        this.init()
      },
      immediate: true
    }
  },

  methods: {
    init() {
      this.$nextTick(() => {
        let unit = ''
        let count = ''
        if (this.format && typeof this.format === 'function') {
          const res = this.format(this.value)
          unit = res.unit
          count = res.count
        } else {
          const numberInfo = formatBigNumber(this.value)
          unit = numberInfo.unit
          count = numberInfo.count
        }

        const countUpOptions = {}
        let scrollNUmber = ''
        if (count.includes('.') && count.split('.')[1].trim() === '00') {
          scrollNUmber = count.split('.')[0]
        } else {
          scrollNUmber = count
          countUpOptions.decimalPlaces = 2
        }
        if (unit) {
          countUpOptions.suffix = unit
        }

        const cu = new CountUp(this.$refs.valueRef, scrollNUmber, countUpOptions)
        cu.start()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-item-container {
  .title {
    color: #424e66;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 8px;

    @media (max-width: 1140px) {
      width: 100px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    @media (max-width: 1096px) {
      width: auto;
      white-space: none;
    }
  }

  .value {
    color: #141736;
    font-size: 24px;
    line-height: 1.5;
    margin-bottom: 8px;
    font-weight: bold;

    @media (max-width: 1540px) {
      font-size: 18px;
    }
  }
}
</style>
