<template>
  <window-size>
    <div style="width: 100%; text-align: center; margin-top: 50px">
      <div v-if="resultCode === 0">
        <span style="
          border-radius: 25px;
          background-color: rgb(10,199,111);
          color: white;
          font-size: 34px;
          text-align: center;
          padding: 7px 9px;
        ">
          <van-icon name="success"/>
        </span>
        <div style="font-size: 20px; font-weight: bold; margin-top: 30px">
          健康卡添加成功
        </div>
        <div style="margin-top: 100px">
          <van-button type="primary" plain style="width: 120px" @click="linkDone">完成</van-button>
        </div>
      </div>

      <div v-if="resultCode === -1">
        <span style="
          border-radius: 25px;
          background-color: rgb(250,66,66);
          color: white;
          font-size: 34px;
          text-align: center;
          padding: 7px 9px;
        ">
          <van-icon name="cross" />
        </span>
        <div style="font-size: 20px; font-weight: bold; margin-top: 30px">
          {{ resultMessage }}
        </div>
        <div style="margin-top: 100px">
          <van-button type="primary" plain style="width: 120px" @click="goLastPage">返回上一页</van-button>
        </div>
      </div>
    </div>
  </window-size>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {linkHealthCard} from '@/api/electronic-health-card'
import {getPatientIdByOpenid} from "@/api/patient-id-cards";
import store from "@/store";

const router = useRouter()

const resultCode = ref(null)
const resultMessage = ref(null)

const healthCodeAction = (val) => {
  switch (val) {
    case 0:
    case '0':
      const isvAppId = '4c84fdd3b55e43c780f407a49d4d0cd4';
      const redirectUri = encodeURI('https://staticweb.hnthyy.cn/newUserRegForElectronicHealthCard')
      window.location.href = `https://health.tengmed.com/open/getUserCode?apiVersion=3&type=register&isvAppId=${isvAppId}&redirect_uri=${redirectUri}`
      break;
    case -1:
    case '-1':
      router.go(-1)
      break;
    default:
      linkHealthCard(val).then(res => {
        if (res.healthCardId) {
          resultCode.value = 0
          getPatientIdByOpenid().then((cards) => {
            store.dispatch({
              type: 'storePatientCards',
              cards
            })
          })
        }
      }).catch(e => {
        resultCode.value = -1
        resultMessage.value = e
      })
      break;
  }
}

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

const goLastPage = () => {
  router.go(-1)
}

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] === 'healthCode') {
        healthCodeAction(paramKeyVal[1])
      }
    })
  }
})
</script>