Files
zyt/admin/src/components/EsignDoctorDialog.vue
T
2026-11-20 10:30:04 +08:00

407 lines
16 KiB
Vue

<template>
<el-dialog
:model-value="true"
:title="reviewer ? '审核签署身份' : '医生电子签署身份'"
:width="frameUrl ? 'min(760px, 94vw)' : 'min(520px, 94vw)'"
top="5vh"
append-to-body
:close-on-click-modal="false"
:before-close="dismiss"
>
<p class="doctor-esign__message" role="status">{{ guidance }}</p>
<dl v-if="state?.enabled && state.status === 'ready'" class="doctor-esign__expiry">
<template v-if="state.cert_expires_at">
<dt>签署证书有效期至</dt>
<dd>{{ formatExpiry(state.cert_expires_at) }}</dd>
</template>
<template v-if="grantActive">
<dt>快捷签授权有效期至</dt>
<dd>{{ formatExpiry(state.quicksign_expires_at) }}</dd>
<dt>快捷签剩余次数</dt>
<dd>{{ state.quicksign_remaining_times }}</dd>
</template>
</dl>
<p v-if="error" class="doctor-esign__error" role="alert">{{ error }}</p>
<label v-if="needsMobile" class="doctor-esign__field">
本人手机号码
<el-input
v-model="mobile"
:disabled="!!pending"
type="tel"
inputmode="numeric"
maxlength="11"
autocomplete="off"
placeholder="请输入 11 位大陆手机号码"
/>
</label>
<label v-if="needsIdentityNumber" class="doctor-esign__field">
本次认证使用的身份证号码
<el-input
v-model="identityNumber"
:disabled="!!pending"
type="password"
maxlength="18"
autocomplete="off"
:spellcheck="false"
placeholder="请输入 15 或 18 位大陆居民身份证号码"
/>
</label>
<iframe
v-if="frameUrl"
:src="frameUrl"
class="doctor-esign__frame"
title="e签宝本人身份核验"
sandbox="allow-forms allow-scripts allow-same-origin"
referrerpolicy="no-referrer"
@error="authenticationUnavailable"
/>
<template #footer>
<div class="doctor-esign__actions">
<el-button v-if="needsMobile || canAuthorizeQuick" type="primary" :disabled="!!pending" @click="start">
{{ startLabel }}
</el-button>
<el-button v-if="canResume" type="primary" :disabled="!!pending" @click="openAuthentication">
{{ state?.quicksign_authorizing ? '继续快捷签授权' : '继续人脸认证' }}
</el-button>
<el-button v-if="canComplete" type="primary" :disabled="!!pending" @click="complete">
{{ state?.quicksign_authorizing ? '确认快捷签授权' : '确认绑定签署身份' }}
</el-button>
<el-button
v-if="canResume && !state?.quicksign_authorizing"
:disabled="!!pending"
@click="enterMobile"
>重新输入手机号</el-button>
<el-button :disabled="!!pending" @click="refresh">检查状态</el-button>
<el-button v-if="frameUrl" link @click="authenticationUnavailable">验证页面不可用</el-button>
<el-button @click="dismiss">关闭</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import {
prescriptionEsignDoctorComplete,
prescriptionEsignDoctorStart,
prescriptionEsignDoctorStatus,
type PrescriptionEsignDoctorStatus
} from '@/api/tcm'
import { safeEsignAuthUrl } from '@/utils/prescription-esign'
const props = defineProps<{ serverTimeOffsetMs: number; reviewer?: boolean }>()
const emit = defineEmits<{ (event: 'close'): void }>()
type DoctorRequest = 'status' | 'start' | 'complete'
const enrollmentStatuses = ['unbound', 'needs_mobile', 'renewal_required']
const statuses = [...enrollmentStatuses, 'authenticating', 'binding_required', 'ready']
const pollInterval = 5000
const authenticationTimeout = 10 * 60 * 1000
const expiryFormatter = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23'
})
const state = ref<ReturnType<typeof validateStatus> | null>(null)
const pending = ref<DoctorRequest | null>(null)
const frameUrl = ref('')
const mobile = ref('')
const identityNumber = ref('')
const editingMobile = ref(false)
const error = ref('')
const now = ref(Date.now() + props.serverTimeOffsetMs)
const authUrl = computed(() => state.value?.auth_url ?? '')
const authenticating = computed(() => state.value?.enabled === true && state.value.status === 'authenticating')
const canResume = computed(() => authenticating.value && !!authUrl.value && !frameUrl.value && !editingMobile.value)
const canComplete = computed(() => state.value?.enabled === true && state.value.status === 'binding_required')
const needsIdentityNumber = computed(() => canComplete.value && !state.value?.quicksign_authorizing
&& state.value?.identity_details_required === true)
const needsMobile = computed(() => state.value?.enabled === true
&& (enrollmentStatuses.includes(state.value.status) || editingMobile.value))
const quickReady = computed(() => state.value?.enabled === true && state.value.status === 'ready'
&& state.value.quicksign_enabled === true)
const grantActive = computed(() => quickReady.value && !!state.value && !state.value.quicksign_unavailable_reason
&& (state.value.quicksign_remaining_times ?? 0) > 0 && state.value.quicksign_expires_at * 1000 > now.value)
const canAuthorizeQuick = computed(() => quickReady.value && !grantActive.value)
const startLabel = computed(() => {
if (canAuthorizeQuick.value) return '授权快捷签'
if (state.value?.status === 'renewal_required') return '开始续期认证'
return '开始人脸认证'
})
const guidance = computed(() => {
const current = state.value
if (!current) return pending.value === 'status' ? '正在查询医生签署身份…' : ''
if (!current.enabled) return '当前环境未启用医生电子签署身份。'
switch (current.status) {
case 'unbound':
return '首次电子签署前,请验证本人身份并绑定签署证书。'
case 'needs_mobile':
return '请使用本人手机号码完成签署身份验证。'
case 'renewal_required':
return '签署证书需要续期,请使用本人手机号码完成人脸认证。'
case 'authenticating':
if (editingMobile.value) return '请使用本人手机号码完成人脸认证。'
if (current.authUrlUnavailable) return '验证链接不可用,请检查状态后重试。'
if (!authUrl.value) return '认证请求处理中,请稍后检查状态。'
if (!frameUrl.value) return current.quicksign_authorizing ? '请继续完成快捷签授权。' : '请继续完成本人人脸认证。'
return current.quicksign_authorizing
? '请使用手机支付宝扫码刷脸,并按 e签宝页面提示确认授权。'
: '请使用手机支付宝扫描 e签宝页面中的二维码并完成人脸识别。'
case 'binding_required':
if (current.quicksign_authorizing) return '人脸认证已通过,请确认启用本人的快捷签。'
if (needsIdentityNumber.value) return '人脸认证已通过。首次绑定证书需要补充与本次认证一致的身份证号码。'
return '人脸认证已通过,请确认完成本人的签署身份认证。'
case 'ready': {
if (!quickReady.value) return '医生签署身份已就绪。'
if (grantActive.value) return props.reviewer ? '快捷签授权有效。每张处方由审核人本人确认签名。'
: '快捷签授权有效。每张处方仍需开方医生本人确认签名。'
const reason = current.quicksign_unavailable_reason
if (reason === 'expired' || (current.quicksign_expires_at > 0 && current.quicksign_expires_at * 1000 <= now.value)) {
return '快捷签授权已过期,请重新授权。'
}
if (reason === 'exhausted') return '快捷签授权次数已用完,请重新授权。'
if (reason === 'invalid') return '快捷签授权已失效,请重新授权。'
return '签署身份已就绪。请授权使用本人的快捷签,每张处方仍需本人确认签名。'
}
}
})
let closed = false
let generation = 0
let statusRequest: AbortController | undefined
let pollTimer: ReturnType<typeof setTimeout> | undefined
let deadlineTimer: ReturnType<typeof setTimeout> | undefined
let grantExpiryTimer: ReturnType<typeof setTimeout> | undefined
function formatExpiry(timestamp: number) {
return `${expiryFormatter.format(timestamp * 1000)}(北京时间)`
}
function validTime(value: number) {
return Number.isSafeInteger(value) && value >= 0 && value <= 253402300799
}
function validateStatus(result: PrescriptionEsignDoctorStatus) {
const {
enabled, status, cert_expires_at,
identity_details_required = false, quicksign_enabled = false, quicksign_authorizing = false,
quicksign_expires_at = 0, quicksign_remaining_times = 0, quicksign_unavailable_reason = ''
} = result
if (!statuses.includes(status) || typeof enabled !== 'boolean'
|| typeof quicksign_enabled !== 'boolean' || typeof quicksign_authorizing !== 'boolean'
|| !validTime(cert_expires_at) || !validTime(quicksign_expires_at)
|| typeof identity_details_required !== 'boolean'
|| (identity_details_required && (!enabled || status !== 'binding_required' || quicksign_authorizing))
|| (quicksign_authorizing && (!enabled || !quicksign_enabled || !['authenticating', 'binding_required'].includes(status)))
|| !Number.isSafeInteger(quicksign_remaining_times) || quicksign_remaining_times < 0
|| !['', 'missing', 'expired', 'exhausted', 'invalid'].includes(quicksign_unavailable_reason)) {
throw new Error('医生签署状态无效')
}
const providerUrl = enabled && status === 'authenticating' ? result.auth_url : undefined
const auth_url = safeEsignAuthUrl(providerUrl)
return {
enabled, status, cert_expires_at, identity_details_required, quicksign_enabled, quicksign_authorizing,
quicksign_expires_at, quicksign_remaining_times, quicksign_unavailable_reason, auth_url,
authUrlUnavailable: Boolean(providerUrl && !auth_url)
}
}
function clearInputs() {
mobile.value = ''
identityNumber.value = ''
}
function stopAuthentication() {
clearTimeout(pollTimer)
clearTimeout(deadlineTimer)
frameUrl.value = ''
}
function cancelWork() {
generation++
statusRequest?.abort()
statusRequest = undefined
pending.value = null
clearInputs()
stopAuthentication()
}
function clearStatus() {
cancelWork()
clearTimeout(grantExpiryTimer)
state.value = null
editingMobile.value = false
error.value = ''
}
function dismiss() {
closed = true
clearStatus()
emit('close')
}
function canAct() {
return !closed && document.visibilityState === 'visible'
}
function accept(result: ReturnType<typeof validateStatus>) {
clearTimeout(grantExpiryTimer)
now.value = Date.now() + props.serverTimeOffsetMs
editingMobile.value = false
state.value = result
if (!authenticating.value || (frameUrl.value && frameUrl.value !== authUrl.value)) stopAuthentication()
if (grantActive.value) {
const expiresIn = result.quicksign_expires_at * 1000 - now.value
if (expiresIn <= 2147483647) {
grantExpiryTimer = setTimeout(() => { now.value = Date.now() + props.serverTimeOffsetMs }, expiresIn)
}
}
}
function schedulePoll() {
if (frameUrl.value) pollTimer = setTimeout(() => void refresh(), pollInterval)
}
function openAuthentication() {
if (!canAct() || pending.value || !canResume.value) return
frameUrl.value = authUrl.value
error.value = ''
deadlineTimer = setTimeout(() => {
cancelWork()
error.value = '自动检查已结束,请检查状态后继续。'
}, authenticationTimeout)
schedulePoll()
}
function authenticationUnavailable() {
if (!frameUrl.value) return
cancelWork()
error.value = '无法加载 e签宝认证页面,请检查状态后重试。'
}
function enterMobile() {
if (!canAct() || pending.value || !canResume.value || state.value?.quicksign_authorizing) return
editingMobile.value = true
error.value = ''
}
async function submit(
kind: DoctorRequest,
request: () => Promise<PrescriptionEsignDoctorStatus>
) {
if (!canAct() || pending.value) return
const current = generation
clearInputs()
clearTimeout(pollTimer)
error.value = ''
pending.value = kind
try {
const result = validateStatus(await request())
if (current !== generation || !canAct()) return
accept(result)
} catch {
if (current !== generation || !canAct()) return
clearStatus()
error.value = '医生签署身份状态待确认,请检查状态后继续。'
return
} finally {
if (current === generation) pending.value = null
}
if (kind === 'start') openAuthentication()
else schedulePoll()
}
async function refresh() {
if (!canAct() || pending.value) return
const controller = new AbortController()
statusRequest = controller
try {
await submit('status', () => prescriptionEsignDoctorStatus(controller.signal))
} finally {
if (statusRequest === controller) statusRequest = undefined
}
}
async function start() {
if (!canAct() || pending.value) return
if (canAuthorizeQuick.value) {
await submit('start', () => prescriptionEsignDoctorStart({}))
} else if (needsMobile.value) {
const number = mobile.value.trim()
clearInputs()
if (!/^1[3-9]\d{9}$/.test(number)) {
error.value = '请输入有效的大陆手机号码。'
return
}
await submit('start', () => prescriptionEsignDoctorStart({ mobile: number }))
}
}
async function complete() {
if (!canAct() || pending.value || !canComplete.value) return
if (needsIdentityNumber.value) {
const number = identityNumber.value.trim().toUpperCase()
clearInputs()
if (!/^(?:\d{15}|\d{17}[\dX])$/.test(number)) {
error.value = '请输入本次认证使用的 15 或 18 位大陆居民身份证号码。'
return
}
await submit('complete', () => prescriptionEsignDoctorComplete({ identity_number: number }))
} else {
await submit('complete', () => prescriptionEsignDoctorComplete({}))
}
}
function onVisibilityChange() {
if (document.visibilityState === 'visible') void refresh()
else clearStatus()
}
onMounted(() => {
document.addEventListener('visibilitychange', onVisibilityChange)
void refresh()
})
onBeforeUnmount(() => {
closed = true
clearStatus()
document.removeEventListener('visibilitychange', onVisibilityChange)
})
</script>
<style scoped>
.doctor-esign__message, .doctor-esign__error {
margin: 0 0 12px;
line-height: 1.6;
}
.doctor-esign__message:empty { display: none; }
.doctor-esign__error { color: var(--el-color-danger); }
.doctor-esign__expiry {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 8px 16px;
margin: 0 0 12px;
padding-top: 12px;
border-top: 1px solid var(--el-border-color-light);
}
.doctor-esign__expiry dt { color: var(--el-text-color-secondary); }
.doctor-esign__expiry dd { margin: 0; }
.doctor-esign__field { display: grid; gap: 6px; max-width: 350px; }
.doctor-esign__frame {
display: block;
width: 100%;
height: min(60vh, 620px);
border: 1px solid var(--el-border-color-light);
border-radius: 4px;
background: white;
}
.doctor-esign__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
.doctor-esign__actions .el-button + .el-button { margin-left: 0; }
</style>