<template>
  <div>
    <el-dialog
      title="请扫码（社保卡二维码）"
      :visible.sync="visible"
      :close-on-click-modal="false"
      append-to-body
      width="50%"
      @close="closeQrcodeDialog">
      <div class="wrap">
        <el-input
          clearable
          v-model="qrcode"
          @blur="$refs.qrcodeInput.focus()"
          ref="qrcodeInput"></el-input>
        <el-button
          @click="reload"
          style="margin-left:10px">
          重新扫码
        </el-button>
        <el-button
          @click="submit"
          type="primary"
          style="margin-left:10px">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSSCList } from '@/api/icCard'
export default {
  data () {
    return {
      qrcode: '',
      visible: false,
      resetQrcode: false,
      timer: null
    }
  },
  methods: {
    show () {
      // 扫码时，不再重复触发弹窗初始化。
      if (this.visible) return

      this.visible = true
      this.qrcode = ''

      this.$nextTick(() => {
        this.$refs.qrcodeInput.focus()
      })
    },
    closeQrcodeDialog () {
      this.visible = false
      this.resetQrcode = true
      this.qrcode = ''
    },
    reload () {
      this.qrcode = ''
      this.resetQrcode = true
      this.$refs.qrcodeInput.focus()
    },
    handleInput (e) {
      this.timer && clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        if (this.qrcode.length > 20) {
          getSSCList(this.qrcode).then(res => {
            this.$emit('getSSCList', res)
            this.qrcode = ''
            this.visible = false
          }).catch(() => {
            this.$message.error('获取失败')
            this.qrcode = ''
          })
        }
      }, 200)
    },
    submit () {
      this.$refs.qrcodeInput.blur()
      this.handleInput()
    }
  },
  watch: {
    qrcode (newName, oldName) {
      this.handleInput()
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap{
    padding: 20px; display: flex;
}

</style>
