<template>
  <div class="search-list-wrap">
    <div class="search-wrap">
      <!-- <el-input
        style="width:320px; margin-bottom:10px"
        v-model="cardInput"
        placeholder="输入IC卡号"></el-input> -->
      <ReaderInput
        type="IC"
        v-model="cardInput"
        style="margin-bottom:10px">
      </ReaderInput>

      <!-- :disabled="!cardInput" -->
      <el-button
        style="width:320px; margin-bottom:10px;"
        @click="handleHandAdd"
        type="primary">
        添加
      </el-button>

      <!-- <el-button
        :icon="reading?'el-icon-loading':''"
        @click="start"
        style="width:320px; margin-bottom:10px; margin-left:0"
        :type="reading?'danger':'primary'">
        {{ reading?'停止读卡':'开始读取IC卡' }}
      </el-button> -->
    </div>
    <div class="list-wrap custom-scroll">
      <el-table
        border
        stripe
        :data="cardList">
        <el-table-column
          label="卡号"
          prop="iccard"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          label="类型"
          prop="type"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDelete(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// import moment from 'moment'
import { getIccardInfo } from '@/api/member'
import { getComName, getIccard } from '@/api/ZTKReaderApi'
import ReaderInput from '@/components/ReaderInput'

const mockData = [
  123451,
  123452,
  123453,
  123454,
  123455,
  123456,
  123457
]

export default {
  components: {
    ReaderInput
  },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      cardInput: '',
      reading: false,
      cardType: null,
      cardList: [],

      searchInput: '',
      scenicList: [],
      memberList: [],
      infoDialogVisible: false,
      memberTypeInfo: {},
      currentTypeIndex: 0,
      currentType: null
    }
  },
  filters: {
    checkPattern (input) {
      switch (input) {
        case 'count':
          return '单人按次'
        case 'time':
          return '按有效期'
        default:
          return ''
      }
    }
  },
  computed: {
    tableData () {
      if (this.searchInput) {
        return this.memberList.filter(row => row.name.indexOf(this.searchInput) !== -1)
      } else {
        return this.memberList
      }
    }
  },
  watch: {
    // '$store.getters.quickSearch' (val) {
    //   this.keyword = val
    // }
    value (val) {
      this.cardList = val
    },
    tableData (val) {
      let index = val.findIndex(item => {
        return item.id === this.currentType.id
      })
      // let n = index === -1 ? 0 : index
      this.$nextTick(() => {
        // this.$refs.ticketTable.setCurrentRow(val[index])
        this.currentTypeIndex = index
      })
    },
    currentType (val) {
      let index = this.tableData.findIndex(item => {
        return item.id === val.id
      })
      this.$nextTick(() => {
        this.currentTypeIndex = index
      })
    }
  },
  mounted () {
    // this.$store.commit('setQuickSearch', '')
    // document.getElementById('quick-search').focus()
  },
  methods: {
    handleHandAdd () {
      if (!this.cardInput) return this.$message.error('请输入卡号')
      this.handleAddCard(this.cardInput)
      this.cardInput = ''
    },
    getComName () {
      return getComName().then(res => {
        if (res.data.ret === 0) {
          return res.data.data.name
        } else {
          return ''
        }
      }).catch(e => {
        return ''
      })
    },
    getCardInfo (num) {
      return getIccardInfo(num).then(res => {
        return res
      }).catch(e => {
        return false
      })
    },
    async start () {
      if (!this.reading) {
        this.comName = await this.getComName()

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

        console.log('开始读卡')

        this.readICCard()
        // this.mockRead()
      }
      this.reading = !this.reading
    },
    // 模拟读卡
    mockRead () {
      this.mockIdx = 0
      this.timer = setInterval(async () => {
        await this.handleAddCard(mockData[this.mockIdx])
        this.mockIdx++

        if ((this.mockIdx > mockData.length - 1) || !this.reading) {
          this.timer && clearInterval(this.timer)
        }
      }, 300)
    },
    readICCard () {
      getIccard(this.comName[3])
        .then(this.handleReadSuccess)
        .finally(() => {
          if (!this.reading) return

          setTimeout(() => {
            this.readICCard()
          }, 500)
        })
    },
    handleReadSuccess (data) {
      switch (data.ret) {
        case 0:
          this.handleAddCard(data.data.ICSnr)
          break
        case 1:
          this.$message.error('未连接读卡器，请检查设备后重试。')
          break
        case 11:
          this.$message.error('读卡失败。')
      }

      this.active = false
    },
    async handleAddCard (num) {
      if (this.cardList.find(i => i.iccard === num)) {
        this.$message.error('重复卡')
        return
      }

      let cardInfo = await this.getCardInfo(num)
      let isInStorage = cardInfo.member && cardInfo.member.isActive === 0
      // 是否在入库记录内
      if (isInStorage) {
        if (this.cardList.length && (cardInfo.memberType.name !== this.cardList[0].type)) {
          this.$message.error('每次出库操作，只能有一种会员类型')
          return
        }

        // 保存卡类型
        if (!this.cardType) {
          this.cardType = cardInfo.memberType
          this.$emit('setType', this.cardType)
        }

        this.cardList.push({
          type: cardInfo.memberType.name,
          iccard: num
        })

        this.$emit('input', this.cardList)
      }
    },
    handleDelete (index) {
      this.cardList.splice(index, 1)
    }
  },
  beforeDestroy () {
    this.reading = false
    this.timer && clearInterval(this.timer)
  }
}
</script>

<style lang="scss" scoped>
.list-item{
  .price-inner{
    margin-top: 3px;
    b{
      font-size: 1.2em;
    }
  }
}

</style>
