<template>
  <window-size>
    <div style="width: 100%; text-align: center; margin-top: 30px">
      {{ currentTime }}
    </div>
    <div id="qrCode" style="width: 100%; text-align: center; margin-top: 30px"></div>
    <div style="margin-top: 50px; padding: 0 30px">
      <van-button type="primary" block @click="toHealthCardHome">返回健康卡首页</van-button>
    </div>
    <div style="margin-top: 20px; width:100%; text-align: center">
      <span style="text-decoration: underline; color: #409eff" @click="myCardPacket">进入我的卡包</span>
    </div>
  </window-size>
</template>

<script setup>
import {onDeactivated, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {qrcanvas} from "qrcanvas";
import {getDateTime} from "@/utils/date";
import {getOrderIdByOutAppId} from '@/api/electronic-health-card'

const router = useRouter()
const card = ref({})

const currentTime = ref('')

let timeInterval = null
const refreshCurrentTime = () => {
  currentTime.value = getDateTime()
  timeInterval = setInterval(() => {
    currentTime.value = getDateTime()
  }, 1000)
}

const makeQrCode = () => {
  document.getElementById('qrCode').innerHTML=''
  const image = new Image();
  image.src = 'https://staticweb.hnthyy.cn/images/dzjkklogo.png';
  image.onload = () => {
    const canvas = qrcanvas({
      size: 200,
      data: card.value.qrCodeText,
      foreground: 'green',
      logo: {
        w: 65,
        h: 65,
        x: 90,
        y: 90,
        image,
      },
    });
    document.getElementById('qrCode').appendChild(canvas)
  };
}

const toHealthCardHome = () => {
  router.push('/electronicHealthCardHome')
}

const myCardPacket = () => {
  getOrderIdByOutAppId(card.value.qrCodeText).then(res => {
    const redirectUri = 'https://staticweb.hnthyy.cn/electronicHealthCardHome'
    window.location.href = `https://03-h5-health.tengmed.com/api/open/takeMsCard?order_id=${res}&redirect_uri=${redirectUri}`
  })
}

onDeactivated(() => {
  clearInterval(timeInterval)
})

onMounted(() => {
  const pathSplit = router.currentRoute.value.fullPath.split('?')
  if (pathSplit.length > 1) {
    const rawParams = pathSplit[1].split('&')
    rawParams.forEach(param => {
      const paramKeyVal = param.split('=')
      if (paramKeyVal[0] === 'card') {
        card.value = JSON.parse(decodeURIComponent(decodeURIComponent(paramKeyVal[1])))
        makeQrCode()
        refreshCurrentTime()
      }
    })
  }
})
</script>