<template></template>
<script>
import axios from 'axios'

export default {
  name: 'IdCardReader',
  props: {
    enable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      service: null,
      response: {
        code: '', //返回值0成功，其他错误
        retcode: '', //状态值，第一个值为读卡状态，0x90成功，第二个值为照片解码状态，0x1成功
        retmsg: '', //返回值信息
        errmsg: '',
        name: '', //姓名
        sex: '', //性别
        nation: '', //民族或国籍(外国人居住证)
        born: '', //出生日期
        address: '', //住址
        cardno: '', //证件号码
        userlifeb: '', //有效期开始
        userlifee: '', //有效期结束
        police: '', //签发机关
        photobase64: '', //证件头像
      },
      polling: false,
      timer: null,
    }
  },
  watch: {
    enable(newValue, oldValue) {
      if (!oldValue && newValue) this.startListen()
      else if (oldValue && !newValue) this.stopListen()
    },
  },
  created() {
    this.service = axios.create({
      baseURL: this.$setting.IdCardReaderAddress,
      timeout: 1000,
    })
    if (this.enable) this.startListen()
  },
  destroyed() {
    this.stopListen()
  },
  methods: {
    startListen() {
      //console.log('startListen')
      this.polling = true
      this.pollReader()
    },
    pollReader() {
      if (this.service)
        this.service
          .get('/api/ReadMsg')
          .then((resp) => {
            if (resp.data.code == '0') {
              console.log(JSON.parse(JSON.stringify(resp.data)))
              // console.log(resp.data)
              if (this.response.cardno != resp.data.cardno) {
                this.$emit('output', JSON.parse(JSON.stringify(resp.data)))
              }
              this.response = resp.data
            } else {
              this.response.cardno = ''
            }
            //console.log(resp.data)
            if (this.polling) this.timer = setTimeout(this.pollReader, 500)
          })
          .catch((err) => {
            console.log(err)
          })
    },
    stopListen() {
      //console.log('stopListen')
      this.polling = false
      if (this.timer) clearTimeout(this.timer)
    },
  },
}
</script>
