<template>
  <div class="el-input el-input--medium sweepCode"
       :style="{width:width+'px'}">
    <img src="~@/assets/icon2.png"
         class="sweepCode-img">
    <input ref="rootInput"
           type="text"
           :placeholder="placeholder"
           class="el-input__inner sweepCode-input"
           @keypress="onkeypress($event)"
           @focus="onfocus($event)" />
  </div>
</template>
<script>
export default {
  name: 'sweepCode',
  data () {
    return {
      code: '',
      clearFlag: false
    }
  },
  props: {
    placeholder: {
      type: String,
      default () {
        return '扫码处，请保持焦点并调整输入法为英文'
      }
    },
    width: {
      type: Number,
      default () {
        return 318
      }
    },
    autofocus: {
      type: Boolean,
      default () {
        return false
      }
    },
    isAppend: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      if (this.autofocus) {
        this.focus()
      }
    })
  },
  methods: {
    onkeypress (e) {
      if (this.clearFlag && !this.isAppend) {
        this.clearFlag = false
        this.code = ''
        e.target.value = ''
      }
      if (e.keyCode === 13) {
        const val = e.target.value
        if (val === this.code) {
          this.$emit('done', val)
        } else {
          this.$emit('error')
        }
        if (!this.isAppend) {
          this.clearFlag = true
        }
      } else {
        const keychar = String.fromCharCode(e.keyCode)
        this.code += keychar
      }
    },
    onfocus (e) {
      this.code = ''
      e.target.value = ''
    },
    focus () {
      this.$refs.rootInput.focus()
    }
  }
}
</script>
<style scoped>
img.sweepCode-img {
  width: 28px;
  margin-right: 6px;
}

.el-input.sweepCode {
  display: flex;
  align-items: center;
}
</style>
