<template>
  <input class="limit-input"
         @input="input($event)"
         @compositionend="compositionend($event)"
         @compositionstart="compositionstart"
         :value="inputValue"
         :maxlength="maxlength"
         :disabled="disabled"
         :placeholder="placeholder" />
</template>

<script>
export default {
  name: 'LimitLengthInput',
  props: {
    maxlength: {
      type: Number,
      default: 12
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    defaultValue: {
      type: [String, Number],
      default: ''
    }
  },
  watch: {
    defaultValue: {
      handler(val, oldVal) {
        if (val) {
          this.inputValue = val;
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      inputLock: false,
      inputValue: '',
      keyCode: ''
    };
  },
  methods: {
    input(e) {
      if (!this.inputLock) {
        this.inputValue = e.target.value;
        if (this.checkLength()) {
          this.inputValue = this.getByteVal();
        }
        this.$emit('onLimitValue', this.inputValue);
      }
    },
    compositionstart() {
      this.inputLock = true;
    },
    compositionend(e) {
      this.inputLock = false;
      this.inputValue = e.target.value;
      if (this.checkLength()) {
        this.inputValue = this.getByteVal();
      }
      this.$emit('onLimitValue', this.inputValue);
    },
    checkLength() {
      return this.inputValue.replace(/[^\x20-\xff]/g, '**').length > this.maxlength;
    },
    getByteVal() {
      let returnValue = '';
      let byteValLen = 0;
      for (var i = 0; i < this.inputValue.length; i++) {
        if (this.inputValue[i].match(/[^\x20-\xff]/gi) !== null) byteValLen += 2;
        else byteValLen += 1;
        if (byteValLen > this.maxlength) break;
        returnValue += this.inputValue[i];
      }
      return returnValue;
    }
  }
};
</script>
