<template>
  <div class="has-text-left">
    <input class="input" type="text" placeholder="" @keyup="change" v-model="text" @keyup.enter="doClick()" id="refinput">
    <p class="help has-text-danger mt-1" v-if="error">{{ error }}</p>
    <div class="mt-5 pt-3">
      <button class="button is-primary" @click="doClick()">Cập nhật</button>
      <button class="button is-danger ml-5" @click="remove()">Xóa</button>
    </div>
  </div>
</template>
<script>
export default {
  props: ['note'],
  data() {
    return {
      text:  this.note? this.$copy(this.note) : '',
      error: false,
      timer: undefined
    }
  },
  mounted() {
    document.getElementById('refinput').focus()
  },
  beforeDestroy() {
    if(this.timer) clearTimeout(this.timer)
    this.timer = undefined
  },
  methods: {
    changeNote() {
      this.$emit('modalevent', {name: 'changenumber', data: {note: this.$empty(this.text)? null : this.text}})
    },
    change(e) {
      if(this.timer) {
        clearTimeout(this.timer)
        this.timer = setTimeout(()=>this.checkNumber(e.target.value), 1000)
      } else this.timer = setTimeout(()=>this.checkNumber(e.target.value), 1000)
    },
    checkNumber(text) {
      this.error = undefined
      if(!this.$empty(text) && !this.$isNumber(text)) return this.error = 'Số không hợp lệ'
      this.text = this.$numtoString(text)
    },
    doClick() {
      this.checkNumber(this.text)
      if(this.error) return
      this.$emit('modalevent', {name: 'changenote', data: {note: this.$empty(this.text)? null : this.text}})
    },
    remove() {
      this.text = null
      this.doClick()
    }
  }
}
</script>