<template>
  <window-size>
    <div style="margin-top: 12px">
      <div id="qrcode" :style="qrMargin"></div>
    </div>
    <div class="expire-wrapper">
      <div style="color: #999">
        <span v-if="timer > -1">{{timer}}秒后过期</span>
        <span v-else>已过期</span>
      </div>
      <div v-if="timer < 0" style="color: #409EFF; margin-left: 8px" @click="drawQrcode">
        <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M512 166.4c-70.4 0-134.4 19.2-192 57.6L294.4 185.6C281.6 166.4 256 172.8 249.6 192L204.8 332.8C204.8 345.6 217.6 364.8 230.4 364.8l147.2-6.4c19.2 0 32-25.6 19.2-38.4L364.8 281.6l0 0 0-6.4C403.2 243.2 460.8 230.4 512 230.4c153.6 0 281.6 128 281.6 281.6s-128 281.6-281.6 281.6-281.6-128-281.6-281.6c0-19.2-12.8-32-32-32S166.4 492.8 166.4 512c0 192 153.6 345.6 345.6 345.6S857.6 704 857.6 512 704 166.4 512 166.4z" fill="#409EFF"></path></svg>
        刷新
      </div>
    </div>
    <div style="height: 10px"></div>
    <van-cell title="姓名" icon="user-o" :value="currentCard.name" />
    <van-cell title="就诊卡号" icon="credit-pay" :value="currentCard.patientId" />
    <van-cell title="手机号" icon="phone-o" :value="currentCard.phone" />
    <van-cell title="身份证号" icon="idcard" :value="currentCard.socialNo" />
    <div style="height: 10px"></div>
    <van-button type="primary" plain block @click="setThisDefaultCard" :disabled="currentCard.isDefault === 1" icon="star-o">
      设置默认就诊人
    </van-button>
    <div style="height: 10px"></div>
    <van-button type="primary" plain block @click="showEditDialog = true" icon="edit">编辑个人信息</van-button>
    <div style="height: 10px"></div>
    <van-button type="primary" plain block @click="unbindCard" icon="revoke">解除绑定</van-button>

    <van-dialog v-model:show="showEditDialog" title="编辑个人信息" show-cancel-button :before-close="modifyInfo">
      <div class="modify-note">提示：如需修改姓名或身份证号，请本人持身份证到医院窗口办理。</div>
      <van-field v-model="currentCard.name" label="姓名" disabled></van-field>
      <van-field v-model="currentCard.socialNo" label="身份证" disabled></van-field>
      <van-field v-model="currentCard.phone" type="tel" label="手机号" placeholder="请输入手机号"></van-field>
    </van-dialog>
  </window-size>
</template>

<script setup>
import store from '@/store'
import {onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {showConfirmDialog, showToast} from 'vant'
import {
  getPatientIdByOpenid,
  relieveBindCard,
  relieveBindCardButCanceled,
  setDefaultCard,
  updateBindInfo,
} from '@/api/patient-id-cards'
import {isValidIdcard, isValidPhone} from '@/utils/validate'
import {qrcanvas} from 'qrcanvas'

const timer = ref(0)

const screenSize = store.state.screenSize
const qrMargin = {
  marginLeft: (screenSize.w - 164) / 2 + 'px',
}

const router = useRouter()
const currentCard = store.getters.getCertainCard(router.currentRoute.value.params.patientId)

const setThisDefaultCard = () => {
  setDefaultCard(currentCard.patientId).then(() => {
    showToast({
      message: '设置成功',
      position: 'top'
    })
    getPatientIdByOpenid().then((cards) => {
      store.dispatch({
        type: 'storePatientCards',
        cards
      })
    })
  })
}

const showEditDialog = ref(false)
const modifyInfo = (action) => {
  if (action === 'cancel') {
    showEditDialog.value = false
  } else {
    if (!currentCard.name) {
      showToast({
        message: '请输入姓名',
        position: 'top',
      })
      return
    }
    if (!isValidIdcard(currentCard.socialNo)) {
      showToast({
        message: '请输入正确的身份证号码',
        position: 'top',
      })
      return
    }
    if (!isValidPhone(currentCard.phone)) {
      showToast({
        message: '请输入正确的手机号码',
        position: 'top',
      })
      return
    }
    updateBindInfo(currentCard).then(() => {
      showToast({
        message: '修改个人信息成功！',
        position: 'top'
      })
    })
  }
}

const unbindCard = () => {
  showConfirmDialog({
    title: '提示',
    message: '是否确定解除绑定？',
  }).then(() => {
    relieveBindCard(currentCard).then((cards) => {
      showToast({
        message: '解除绑定成功！',
        position: 'top'
      })
      store.dispatch({
        type: 'storePatientCards',
        cards
      }).then(() => {
        router.go(-1)
      })
    })
  }).catch(() => {
    relieveBindCardButCanceled(currentCard)
  })
}

let expireInterval = null

const startExpireInterval = () => {
  timer.value = 60
  expireInterval = setInterval(() => {
    timer.value -= 1
    if (timer.value < 0) {
      clearInterval(expireInterval)
      expireQrcode()
    }
  }, 1000)
}

function expireQrcode() {
  const canvas = qrcanvas({
    data: 'expired',
    size: 164,
  })
  let oldChild = document.getElementById('qrcode').childNodes[0]
  document.getElementById('qrcode').replaceChild(canvas, oldChild)
}

const drawQrcode = () => {
  const canvas = qrcanvas({
    id: 'new',
    data: currentCard.patientId + '@' + currentCard.cardType,
    size: 164,
  })
  document.getElementById('qrcode').innerHTML = ''
  document.getElementById('qrcode').appendChild(canvas)
  startExpireInterval()
}

onMounted(() => {
  drawQrcode()
})
</script>

<style scoped>
.expire-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}
.modify-note {
  padding: 4px 12px;
  font-size: 12px;
  color: red;
}
</style>