<template>
    <div class="input-keyboard">
        <input
        v-model="inputValue"
        :autofocus="autofocus"
        :class="inputClass"
        :type="type"
        :show-password="showPassword"
        :disabled="disabled"
        :maxlength="maxlength"
        :placeholder="placeholder"
        @focus="focusInput($event)"
        @input="inputFun"
        >
        <SimpleKeyboard
        :ref="keyboardClass"
        :keyboardClass="keyboardClass"
        @onChange="onChange"
        @onKeyPress="onKeyPress"
        :input="inputValue"
        :maxLength="maxlength"
        />
    </div>
</template>

<script>
import SimpleKeyboard from './SimpleKeyboard'
export default {
  name: 'keyboard-input',
  components: {
    SimpleKeyboard
  },
  props: {
    keyboardClass: String,
    autofocus: Boolean,
    value: {
      default: ''
    },
    inputClass: String,
    type: {
      type: String,
      default: 'text'
    },
    showPassword: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    maxlength: Number,
    placeholder: String
  },
  data () {
    return {
      input: null,
      inputEle: null
    }
  },
  computed: {
    inputValue: {
      get () {
        return this.value
      },
      set (value) {
        this.$emit('inputChange', value)
      }
    }
  },
  methods: {
    inputChange () {
      this.$emit('inputChange')
    },
    inputFun () {
      this.$emit('input')
    },
    focusInput (e) {
      this.inputEle = e.srcElement
      // 关闭所有keyboard
      let arr = document.querySelectorAll('.hg-theme-default')
      arr.forEach((ele) => {
        ele.style.visibility = 'hidden'
      })
      // 打开当前输入框的keyboard
      let currentKeyborad = this.$refs[this.keyboardClass]
      currentKeyborad.$el.style.visibility = 'visible'
      this.$nextTick(() => {
        this.$emit('focus')
      })
      setTimeout(() => {
        this.$emit('focus')
      }, 0)
    },
    onChange (input) {
      this.inputValue = input
      this.$nextTick(() => {
        this.inputEle.focus()
      })
      setTimeout(() => {
        this.inputEle.focus()
      }, 0)
    },
    onKeyPress (button) {
      if (button === '{lock}' || button === '{shift}' || button === '{change}' || button === '{bksp}' || button === '{clear}') {
        this.$nextTick(() => {
          this.inputEle.focus()
        })
        setTimeout(() => {
          this.inputEle.focus()
        }, 0)
      }
      if (button === '{clear}') {
        this.inputValue = ''
      }
      console.log('onKeyPress', button)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@style/mixin'
.input-keyboard
    width 100%
.login-input
  width 100%
  _font(30px, 78px, #fff,,)
  background: rgba(45,88,184,0.1);
  border: 1px solid #4980BD;
  padding 0 22px
  &:focus
    background: rgba(45,88,184,0.25);
    border: 2px solid #21D0F2;
    line-height 76px
</style>
