<template>
  <div class='kb-content' :class='!keyboardShow && "kb-hide"'>
    <div class='kb-left'>
      <div v-for="(item, index) in keyArr" class='kb-item kb-left-item b-r' :class="index < 9 && 'b-b'"
           :style="{height: itemH + 'px', lineHeight: itemH + 'px'}" @click="handleInput(item)">{{item}}
      </div>
      <div class='kb-item kb-left-item b-r' :style="{height: itemH + 'px', lineHeight: itemH + 'px'}" @click='keyboardToggle(false)'>
        <img class='submit-icon' :src="require('./images/hide.png')"/>
      </div>
    </div>
    <div class='kb-right'>
      <div @click='handleDelete' class='kb-item kb-right-item k-cancel b-b' :style="{height: itemH * 2 + 'px', lineHeight: itemH * 2 + 'px'}">
        <img class='delete-icon' :src="require('./images/delete.png')"/>
      </div>
      <div @click='handleSubmit' class='kb-item kb-right-item k-submit' :style="{height: itemH * 2 + 'px', lineHeight: itemH * 2 + 'px'}">确定</div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'ElKeyboard',
  props: {
    spKey: String,
    random: {
      type: Boolean,
      default: false
    },
    max: Number
  },
  data() {
    return {
      winW: window.innerWidth < 500 ? window.innerWidth : 500,
      baseArr: [],
      inputStr: '',
      keyboardShow: true
    };
  },
  computed: {
    keyArr() {
      this.handleInit();
      return this.baseArr;
    },
    itemH() {
      return this.winW / 4 * 0.66;
    }
  },
  methods: {
    handleInit() {
      let spKey = this.spKey;
      this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
      if (spKey === undefined || spKey === 'undefined' || spKey == null) {
        spKey = '';
      }
      if (this.random && this.random !== 'false') {
        this.baseArr.sort(() => {
          return Math.random() - Math.random();
        });
      }
      this.baseArr.splice(this.baseArr.length - 1, 0, spKey);
    },
    handleInput(value) {
      if (value === '' || value === undefined || value == null) {
        return;
      }
      let max = Number(this.max);
      if (!isNaN(max) && this.inputStr.length + 1 > max) {
        return;
      }
      this.inputStr += value;
      this.$emit('change-event', this.inputStr, value);
    },
    handleDelete() {
      let str = this.inputStr;
      if (!str.length) return;
      this.inputStr = str.substring(0, str.length - 1);
      this.$emit('change-event', this.inputStr);
    },
    keyboardToggle(type) {
      this.keyboardShow = type;
    },
    handleSubmit() {
      this.$emit('submit-event');
    },
    handleClear() {
      this.inputStr = '';
      this.$emit('change-event', this.inputStr, '');
    }
  }
}
</script>