<template>
  <el-dialog
    title="请刷储值卡"
    :visible.sync="visible"
    width="600px"
    @close="handleClose"
    :close-on-click-modal="false"
    append-to-body>
    <div style="padding:20px">
      <ReaderInput
        type="IC"
        v-show="false"
        v-model="cardNo"
        is-pay
        @change="handleChange"
        ref="reader"></ReaderInput>

      <table
        class="infoTable"
        v-if="cardInfo">
        <tr>
          <th>卡号</th><td>{{ cardInfo.cardCode }}</td>
        </tr>
        <tr>
          <th>余额</th><td>{{ cardInfo.balance }}</td>
        </tr>
        <tr>
          <th>有效期</th><td>{{ cardInfo.validDate }}</td>
        </tr>
      </table>
      <div
        v-else
        class="info-box">
        正在读取。。。
      </div>
    </div>
    <span slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        :disabled="!cardInfo"
        @click="handleSubmit">确认消费</el-button>
    </span>
  </el-dialog>
</template>

<script>
import ReaderInput from '@/components/ReaderInput'
import { getCYCashCardInfo } from '@/api/valueCard'

export default {
  components: {
    ReaderInput
  },
  data () {
    return {
      cardNo: '',
      cardInfo: null,
      visible: false
    }
  },
  methods: {
    getCYCashCardInfo,
    show () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.reader.startRead()
      })
    },
    async handleChange (e) {
      console.log('卡号', e)
      // let cardNo = e.padEnd(15, '0')
      let cardNo = e
      try {
        this.cardInfo = await this.getCardInfo(cardNo)
        console.log(this.cardInfo)
      } catch (e) {
        console.log(e)
        this.handleClose()
      }
    },
    getCardInfo (cardNo) {
      return new Promise((resolve, reject) => {
        getCYCashCardInfo(cardNo).then(res => {
          resolve(res)
        }).catch(e => {
          reject(e)
        })
      })
    },
    handleClose () {
      this.visible = false
      this.$refs.reader.timer && clearTimeout(this.$refs.reader.timer)
      this.$refs.reader.finished = true
      this.$refs.reader.active = false

      this.$emit('close')
    },
    handleSubmit () {
      this.$emit('getInfo', this.cardInfo)
      this.handleClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.infoTable{
    width: 100%; border-collapse: collapse;
    th,td{
        border: 1px solid #ddd; padding: 10px;
    }
    th{
        background: #f0f0f0; text-align: right;
    }
}
.info-box{
    padding: 20px;  text-align: center;
}
</style>
