<template>
  <div class="mm-statistic">
    <div
      v-if="title || $slots.title"
      class="mm-statistic-title">
      <slot name="title">
        {{ title }}
      </slot>
    </div>
    <div
      class="mm-statistic-content"
      :style="valueStyle">
      <div
        v-if="prefix || $slots.prefix"
        class="mm-statistic-content-prefix">
        <slot name="prefix">
          {{ prefix }}
        </slot>
      </div>
      <div class="mm-statistic-content-value">
        <slot>
          <span class="mm-statistic-content-value-integer">
            {{ realValue.integer }}
          </span>
          <span
            v-if="realValue.decimal"
            class="mm-statistic-content-value-decimal">
            {{ decimalSeparator }}{{ realValue.decimal }}
          </span>
        </slot>
      </div>
      <div
        v-if="suffix || $slots.suffix"
        class="mm-statistic-content-suffix">
        <slot name="suffix">
          {{ suffix }}
        </slot>
      </div>
    </div>
  </div>
</template>

<script>
import { padEnd, isNumber } from "lodash"
import config from "../../managers/config"
import { splitNumbers } from "../../utils/reg"

config.defaults({
  "Statistic.precision": 0,
  "Statistic.decimalSeparator": ".",
  "Statistic.thousandSeparator": ",",
  "Statistic.valueStyle": {},
})

const reg = /(\d)(?=(\d{3})+$)/g

export default {
  name: "mm-statistic",
  props: {
    title: String,
    value: {
      type: Number,
    },
    precision: {
      type: Number,
      default: () => config.get("Statistic.precision"),
    },
    decimalSeparator: {
      type: String,
      default: () => config.get("Statistic.decimalSeparator"),
    },
    thousandSeparator: {
      type: String,
      default: () => config.get("Statistic.thousandSeparator"),
    },
    prefix: {
      type: String,
      default: "",
    },
    suffix: {
      type: String,
      default: "",
    },
    valueStyle: {
      type: Object,
      default: () => config.get("Statistic.valueStyle"),
    },
  },
  computed: {
    realValue() {
      let formatValue = {
        negative: "",
        integer: "",
        decimal: "",
      }
      if (!isNumber(this.value)) {
        formatValue.integer = this.value
        return {
          ...formatValue,
          integer: this.value,
        }
      }

      const value = this.splitValue()
      return formatValue = {
        ...formatValue,
        integer: `${value.negative}${value.integer.replace(reg, `$1${this.thousandSeparator}`)}`,
        decimal: typeof this.precision === "number"
          ? padEnd(value.decimal, this.precision, "0").slice(0, this.precision)
          : value.decimal,
      }
    },
  },
  methods: {
    splitValue() {
      const strVal = String(this.value)
      const cells = strVal.match(/^(-?)(\d*)(\.(\d+))?$/)
      return {
        negative: cells[1],
        integer: cells[2] || "0",
        decimal: cells[4] || "",
      }
    },
  },
}
</script>
