<template>
	<ServicePageScaffold title="资质证书" fallback-url="/pages/mall/delivery/profile/index">
		<ServicePanel title="证书列表" subtitle="基于当前服务人员档案展示资质状态和到期信息。">
			<view v-if="certificates.length == 0" class="empty-box"><text class="empty-text">暂无资质信息</text></view>
			<view v-for="item in certificates" :key="item.id" class="cert-card">
				<text class="row-title">{{ item.name }}</text>
				<text class="row-text">状态：{{ item.status }}</text>
				<text class="row-text">到期时间：{{ item.expireAt }}</text>
				<text class="row-text">发证机构：{{ item.issuer }}</text>
			</view>
		</ServicePanel>
	</ServicePageScaffold>
</template>

<script setup lang="uts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import ServicePageScaffold from '@/components/homeService/ServicePageScaffold.uvue'
import ServicePanel from '@/components/homeService/ServicePanel.uvue'
import type { DeliveryCertificateType, DeliveryInfoType } from '@/types/delivery.uts'
import { getDeliveryProfile } from '@/services/deliveryService.uts'
import { requireDeliveryAuth } from '@/utils/deliveryAuth.uts'

const certificates = ref([] as Array<DeliveryCertificateType>)

function buildProfileCertificates(profile: DeliveryInfoType): Array<DeliveryCertificateType> {
	if (profile.certificates.length > 0) {
		return profile.certificates
	}
	const result = [] as Array<DeliveryCertificateType>
	result.push({
		id: 'primary-certificate',
		name: '服务人员主资质',
		status: profile.certificateStatus,
		expireAt: profile.certificateExpireAt != '' ? profile.certificateExpireAt : '待完善',
		issuer: profile.organizationName != '' ? profile.organizationName : '机构待完善',
		imageUrl: ''
	} as DeliveryCertificateType)
	if (profile.skills.length > 0) {
		result.push({
			id: 'skills-certificate',
			name: '服务能力标签',
			status: 'valid',
			expireAt: '长期有效',
			issuer: profile.skills.join(' / '),
			imageUrl: ''
		} as DeliveryCertificateType)
	}
	return result
}

async function loadData() {
	const authResult = await requireDeliveryAuth({ redirectOnFail: true, toastOnFail: true })
	if (!authResult.ok) {
		return
	}
	const profile = await getDeliveryProfile()
	certificates.value = profile != null ? buildProfileCertificates(profile) : [] as Array<DeliveryCertificateType>
}

onShow(() => {
	loadData()
})
</script>

<style scoped>
.cert-card {
	padding: 24rpx;
	margin-bottom: 16rpx;
	border-radius: 20rpx;
	background: #f8fbfc;
}

.row-title {
	font-size: 30rpx;
	font-weight: 700;
	color: #16324f;
}

.row-text,
.empty-text {
	display: block;
	margin-top: 12rpx;
	font-size: 24rpx;
	line-height: 36rpx;
	color: #5e758c;
}

.empty-box {
	padding: 24rpx;
}
</style>