<template>
  <text class="zui-amount" :class="classBind">
    <template v-if="!isCapital">{{ Number(value || 0) | doPrecision(legalPrecision, isRoundUp) | doFormat(hasSeparator, separator) }}</template>
    <template v-else>{{ Number(value || 0) | doPrecision(4, isRoundUp) | doCapital }}</template>
  </text>
</template>

<script>
import { formatValueByGapStep } from '@/utils/format-value.js';
import numberCapital from '@/utils/number-capital.js';

export default {
	name: 'zui-amount',
	props: {
		value: {
			type: [Number, String],
			default: 0
		},
		precision: {
			type: Number,
			default: 2
		},
		isRoundUp: {
			type: Boolean,
			default: true
		},
		hasSeparator: {
			type: Boolean,
			default: false
		},
		separator: {
			type: String,
			default: ','
		},
		isCapital: {
			type: Boolean,
			default: false
		},
	},
  computed: {
    classBind: function() {
      const normalClass = !this.isCapital ? 'numerical' : '';
      if (this.$options && this.$options.propsData && this.$options.propsData.className) {
        return normalClass + ' ' + this.$options.propsData.className;
      }
      return normalClass;
    },
    legalPrecision: function() {
      return this.precision > 0 ? this.precision : 0
    },
  },
  filters: {
    doPrecision: function(value, precision, isRoundUp) {
      const exponentialForm = Number(`${value}e${precision}`)
      const rounded = isRoundUp ? Math.round(exponentialForm) : Math.floor(exponentialForm)
      return Number(`${rounded}e-${precision}`).toFixed(precision)
    },
    doFormat: function(value, hasSeparator, separator) {
      if (!hasSeparator) {
        return value
      }

      const numberParts = value.split('.')
      let integerValue = numberParts[0]
      const decimalValue = numberParts[1] || ''

      let sign = ''
      if (integerValue.startsWith('-')) {
        integerValue = integerValue.substring(1)
        sign = '-'
      }

      const formateValue = formatValueByGapStep(3, integerValue, separator, 'right', 0, 1)
      return decimalValue ? `${sign}${formateValue.value}.${decimalValue}` : `${sign}${formateValue.value}`
    },
    doCapital: function(value) {
      return numberCapital(value)
    },
  },
};
</script>

<style lang="scss">
@import './index.scss';
</style>
