<template>
  <div>
    <Caption v-bind="{title: 'Nhập mã duyệt'}"></Caption>
    <div class="field is-grouped mt-5">
      <div class="control mr-5" v-for="v in [1,2,3,4]">
        <input class="input is-dark" style="font-size: 18px; max-width: 40px; font-weight:bold; text-align: center;" type="password" 
        maxlength="1" :id="`input${v}`" v-model="data[v]" @keyup="changeNext(v)" />
      </div>
    </div>
    <div class="mt-4">
      <a @click="reset()">Nhập lại</a>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      data: {},
      code: undefined
    }
  },
  async created() {
    if(!this.approvalcode && this.$store.state.login.approval_code) this.approvalcode = this.$store.state.login.approval_code
    if(!this.approvalcode) {
      let user = await this.$getdata('user', {id: this.$store.state.login.id}, undefined, true)
      this.approvalcode = user.approval_code
    }
  },
  mounted() {
    this.reset()
  },
  computed: {
    approvalcode: {
      get: function() {return this.$store.state['approvalcode']},
      set: function(val) {this.$store.commit('updateStore', {name: 'approvalcode', data: val})}
    }
  },
  methods: {
    checkError() {
      if(Object.keys(this.data).length<4) return true
      let code = ''
      for (const [key, value] of Object.entries(this.data)) {
        if(!this.$empty(value)) code += value.toString() 
      }
      if(this.$empty(code) || !this.$isNumber(code)) return true
      this.code = code
      return false
    },
    checkValid() {
      if(this.checkError()) return this.$snackbar('Mã phê duyệt không hợp lệ')
      if(this.code!==this.approvalcode) return this.$snackbar('Mã phê duyệt không chính xác')
      this.$emit('modalevent', {name: 'approvalcode', data: this.code})
      this.$emit('close')
    },
    changeNext(v) {
      if(this.$empty(this.data[v])) return
      else if(v===4) return this.checkValid()
      let doc = document.getElementById(`input${v+1}`)
      if(doc) doc.focus()
    },
    reset() {
      this.data = {}
      let doc = document.getElementById(`input1`)
      if(doc) doc.focus()
    }
  }
}
</script>