<template>
  <div class="ems-web-input-money">
    <Input
      v-bind="$attrs"
      type="text"
      :value="val"
      @on-change="handleChange"
      @on-focus="handleFocus"
      @on-blur="handleBlur"
    ></Input>
  </div>
</template>

<script>
import accounting from 'accounting';
accounting.settings = {
  currency: {
    symbol: '', // default currency symbol is '$'
    format: '%s%v', // controls output: %s = symbol, %v = value/number (can be object: see below)
    decimal: '.', // decimal point separator
    thousand: ',', // thousands separator
    precision: 2 // decimal places
  },
  number: {
    precision: 0, // default precision on numbers is 0
    thousand: ',',
    decimal: '.'
  }
};

export default {
  name: 'InputMoney',
  props: {
    value: {
      type: [Number, String],
      default: ''
    },
    symbol: {
      type: [Number, String],
      default: ''
    },
    index: {
      type: [Number, String],
      default: ''
    },
    isNegative: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      val: ''
    };
  },
  watch: {
    value: function(newVal, oldVal) {
      this.val = accounting.formatMoney(newVal);
    }
  },
  created() {
    accounting.settings.currency.symbol = this.symbol;
    this.val = accounting.formatMoney(this.value);
  },
  methods: {
    handleFocus() {
      this.val = this.val == 0 ? null : accounting.unformat(this.val);
    },
    handleBlur() {
      this.val = accounting.formatMoney(this.val);
      this.$emit('blur', accounting.unformat(this.val));
      this.$emit('blurIndex', [accounting.unformat(this.val), this.index]);
    },
    handleChange(event) {
      const targetVal = Number(event.target.value);
      if (isNaN(targetVal) || (targetVal < 0 && !this.isNegative)) {
        return false;
      } else {
        this.val = targetVal;
        this.$emit('input', accounting.unformat(this.val));
        this.$emit('change', accounting.unformat(this.val));
      }
    }
  }
};
</script>

<style>
.ems-web-input-money .ivu-input {
  text-align: right;
}
</style>
