<template>
  <window-size>
    <van-swipe :loop="false" @change="indexChange">
      <van-swipe-item v-for="card in healthCards">
        <electronic-health-card :card-info="card"></electronic-health-card>
      </van-swipe-item>
      <template #indicator="{ active, total }">
        <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
      </template>
    </van-swipe>

    <div style="width: 86%; margin-left: 7%; margin-top: 20px">
      <van-button block type="primary" @click="handleButtonClick">
        {{ cptBtnText }}
      </van-button>
    </div>

  </window-size>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {getRegisteredCards} from '@/api/electronic-health-card'
import ElectronicHealthCard from '@/components/electronic-health-card/index.vue'
import router from '@/router/index'

const healthCards = ref([])
const currentIndex = ref(0)
const indexChange = (index) => {
  currentIndex.value = index
}

const cptBtnText = computed(() => {
  if (healthCards.value.length === 0) {
    return '申领健康卡'
  }
  if (currentIndex.value === healthCards.value.length - 1) {
    if (!healthCards.value[currentIndex.value].healthCardId) {
      return '申领健康卡'
    }
  }
  return '出示二维码';
})

const handleButtonClick = () => {
  if (cptBtnText.value === '出示二维码') {
    router.push({
      name: 'showCardQrCode',
      query: {
        card: encodeURIComponent(JSON.stringify(healthCards.value[currentIndex.value]))
      }
    })
  } else {
    router.push('/addElectronicHealthCard')
  }
}

onMounted(() => {
  getRegisteredCards().then(res => {
    healthCards.value = res
    if (healthCards.value.length < 10) {
      healthCards.value.push({})
    }
  })
})
</script>

<style scoped>
.custom-indicator {
  position: absolute;
  right: 7%;
  bottom: 5px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}
</style>