/**
* @Author think
* @Date 2019-09-09 14:29
*/

<template>
  <input
    :value="formatValue" :readonly="disable" type="text"
    @input="onInput($event.target.value)" @focus="onFocus" @blur="onBlur">
</template>

<script>
export default {
  name: 'CurrencyInput',
  props: {
    value: {
      type: Number,
      default: 0,
    },
    disable: {
      type: Boolean,
      default: false,
    },
  },

  data () {
    return {
      focused: false,
    }
  },
  filter: {
    uncurrency (val) {
      if (!val) return null
      return (Number((val).replace(/,/gi, ''))) === 0 ? null : Number((val).replace(/,/gi, ''))
    },
  },
  computed: {
    formatValue () {
      let currency = this.$options.filters['currency']
      if (!this.focused) {
        return currency(this.value)
      } else {
        return this.value
      }
    },
  },
  methods: {
    onInput: function (value) {
      let uncurrency = this.$options.filter['uncurrency']
      this.currencyValue = uncurrency(value)
      this.$emit('input', this.currencyValue)
    },
    onFocus (event) {
      this.focused = true
      setTimeout(function () {
        event.target.type = 'number'
        event.target.focus()
      }, 0)
    },
    onBlur (event) {
      event.target.type = 'text'
      this.focused = false
    },
  },
}
</script>

<style scoped lang="less">

</style>
