<template>
  <el-tooltip
    :disabled="!tempValue"
    transition="none"
    :content="tempValue"
    placement="right">
    <el-input
      ref="input"
      placeholder="读取卡号"
      class="readerInput"
      clearable
      @blur="$emit('blur')"
      @keyup.enter.native="$emit('enter')"
      @change="handleChange"
      v-model="tempValue">
      <span
        class="readCard"
        slot="suffix"
        :class="{active:active}"
        @click="startRead"
      >
        <div class="inner">
          <span class="wave"></span>

          <svg-icon icon-class="idCard" /> {{ active?'停止':'读取' }}
        </div>
      </span>
    </el-input>
  </el-tooltip>
</template>

<script>
import { getComName, getIccard, getIdInfo } from '@/api/ZTKReaderApi'

export default {
  data () {
    return {
      active: false,
      finished: false,
      tempValue: '',
      comName: '' // 身份证阅读器端口号
    }
  },
  props: {
    type: {
      type: String,
      default: 'ID'
    },
    value: {
      type: [String, Object],
      default: ''
    },
    // 是否是用于支付的加密储值卡
    isPay: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    focus () {
      this.$refs.input.focus()
    },
    getComName () {
      return getComName().then(res => {
        if (res.data.ret === 0) {
          return res.data.data.name
        } else {
          return this.$localStore.get('mock') ? 'COM3' : ''
        }
      }).catch(e => {
        return ''
      })
    },
    handleChange (e) {
      this.$emit('input', e)
    },
    async startRead () {
      if (this.active) {
        this.active = false
        this.finished = true
        this.timer && clearTimeout(this.timer)
        return
      }

      this.finished = false
      this.comName = await this.getComName()

      if (!this.comName) {
        this.$message.error('未获取到设备端口')
        return
      }

      this.getDevice()
    },
    getDevice () {
      this.active = true
      switch (this.type) {
        case 'ID':
          getIdInfo()
            .then(this.handleReadSuccess)
            .catch(this.handleError)
          break
        case 'IC':
          getIccard(this.comName[3], this.isPay)
            .then(this.handleReadSuccess)
            .catch(this.handleError)
          break
      }
    },
    handleReadSuccess (data) {
      console.log(data)
      switch (data.ret) {
        case 0:
          if (this.type === 'IC') {
            if (this.isPay) {
              if (data.data.ICdata) {
                this.$message.success('读取成功！')
                this.tempValue = data.data.ICdata.replace(/F/g, '')

                this.$emit('input', this.tempValue)
                this.$emit('change', this.tempValue)
              } else {
                this.$message.error('卡号获取失败')

                this.retry()
              }

              return
            }
            this.$message.success('读取成功！')
            this.tempValue = data.data.ICSnr
            this.$emit('input', data.data.ICSnr)
            this.$emit('change', data.data.ICSnr)
          } else {
            this.$message.success('读取成功！')
            this.tempValue = data.Certificate.IDNumber
            this.$emit('input', data.Certificate.IDNumber)
            this.$emit('change', data.Certificate)
          }

          break
        case 1:
          this.$message.error('未连接读卡器，请检查设备后重试。')
          break
        case 201:
        case 11:
          this.retry()
          return
      }
      this.active = false
    },
    retry () {
      if (this.finished) return
      this.timer = setTimeout(() => {
        this.getDevice()
      }, 2000)
    },
    handleError (e) {
      e && console.log(e)
      this.$message.error('未连接读卡器，请检查设备后重试。')
      this.active = false
    }
  },
  watch: {
    value: {
      handler (val) {
        this.tempValue = val
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.readerInput {
  ::v-deep .el-input__clear {
    position: relative;  z-index: 10;
  }
  ::v-deep .el-input__inner{
    padding-right: 80px;
  }
}
.readCard {
  position: absolute;  display: flex; height: 100%; font-size: 12px; color: #fff; cursor: pointer;align-items: center; width: 72px; right: 0px; z-index: 0;
  .inner {
    display: flex; height: 80%; padding: 0 5px;  background: $blue; border-radius: 5px; align-items: center;padding-right: 22px;
  }

  .wave {
    position: absolute;top: 50%; left: 50%;display: none; width: 20px;height: 20px;box-sizing: border-box;margin-top: -10px;margin-left: -10px; background: rgba(255, 255, 255, .384); border: 1px solid red; border-radius: 50%; opacity: 0; animation: wave infinite linear 1s forwards;
  }
  .wave2 {
    opacity: 0;  animation: wave infinite 2s 1s forwards;
  }
  .svg-icon {
    position: relative;  width: 16px; height: 16px; margin-right: 5px;font-size: 16px;
  }
  &.active {
    .wave {
      display: block;
    }
    .svg-icon {
      color: #fff;
    }
  }
}

@keyframes wave {
  0% {
    opacity: 0; transform: scale(3);
  }
  50% {
    opacity: .5; transform: scale(1);
  }
  100% {
    opacity: 0; transform: scale(0);
  }
}
</style>
