<template>
	<el-table :data="state.tableData" style="width: 100%"  align="center">
		<el-table-column prop="id" label="ID"   show-overflow-tooltip align="center" />
		<el-table-column prop="hex" label="身份信息哈希值"  width="180"  show-overflow-tooltip align="center" />
		<el-table-column prop="name" label="颁发者"  show-overflow-tooltip align="center" />
		<el-table-column prop="issueDate" label="证书生效时间" width="120" align="center" />
		<el-table-column prop="expireDate" label="证书过期时间" width="120" align="center"/>

		<el-table-column prop="status" label="证书状态">
			<template #default="{row}">
				<el-tag
					:type="{
              '0': 'warning',
              '1': 'success',
              '2': 'primary'
            }[row.auditStatus]"
					effect="light"
				>
					{{
						{
							'0': '待验证',
							'1': '已通过',
							'2': '已更新'
						}[row.auditStatus]
					}}
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column label="操作项" min-width="180" align="center">
			<template #default="scope">
				<el-button
					link
					type="primary"
					size="small"
					@click.prevent="info(scope.row)"
				>
					生成密钥信息
				</el-button>

				<el-button
					link
					type="primary"
					size="small"
					@click="downloadCertificate(scope.row)"
				>
					下载证书
				</el-button>
			</template>
		</el-table-column>
	</el-table>


	<!-- 详情对话框 -->
	<el-dialog
		v-model="state.detailDialogVisible"
		title="生成密钥信息"
		width="700px"
	>
		<el-descriptions :column="2" border>
			<el-descriptions-item label="证书ID">{{ state.currentCertificate.id }}</el-descriptions-item>
			<el-descriptions-item label="状态">
				<el-tag
					:type="{
            '0': 'warning',
            '1': 'success',
            '2': 'primary'
          }[state.currentCertificate.auditStatus]"
					effect="light"
				>
					{{
						{
							'0': '待验证',
							'1': '已通过',
							'2': '已更新'
						}[state.currentCertificate.auditStatus]
					}}
				</el-tag>
			</el-descriptions-item>
<!--			<el-descriptions-item label="身份信息哈希值">{{ state.currentCertificate.hex }}</el-descriptions-item>-->
			<el-descriptions-item label="颁发者">{{ state.currentCertificate.name }}</el-descriptions-item>
			<el-descriptions-item label="证书生效时间">{{ formatDate(state.currentCertificate.issueDate) }}</el-descriptions-item>
			<el-descriptions-item label="证书过期时间">{{ formatDate(state.currentCertificate.expireDate) }}</el-descriptions-item>

			<el-descriptions-item label="更新时间">{{ formatDateTime(state.currentCertificate.updateTime) }}</el-descriptions-item>
			<el-descriptions-item label="区块链交易哈希" :span="2" v-if="state.currentCertificate.txHash">
				{{ state.currentCertificate.txHash }}
				<el-button
					type="primary"
					link

					v-if="state.currentCertificate.txHash"
				>
					查看交易
				</el-button>
			</el-descriptions-item>
			<el-descriptions-item label="备注" :span="2" v-if="state.currentCertificate.remarks">
				{{ state.currentCertificate.remarks }}
			</el-descriptions-item>
		</el-descriptions>

		<!-- 证书图片预览 -->
		<div class="certificate-preview" v-if="state.currentCertificate.img">
			<h4>证书预览</h4>
			<el-image
				:src="state.currentCertificate.img"
				:preview-src-list="[state.currentCertificate.img]"
				fit="contain"
				style="max-height: 300px;"
			/>
		</div>

		<template #footer>
			<el-button @click="state.detailDialogVisible = false">关闭</el-button>
		</template>
	</el-dialog>


</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted } from 'vue'

const state = reactive({
	tableData:[],
	query:{
		total:0,

	},
	// 详情对话框相关状态
	detailDialogVisible: false,
	currentCertificate: {} as any
})
const loadCertificates = async () => {
	try {
		const res = await frontRequest.get('/api/certificate/page', {
			params: {
				...state.query
			}
		})
		state.tableData = res.data.list || []
		state.query.total = res.data.total
	} catch (e) {
		ElMessage.error('数据加载失败')
	}
}

// 查看详情
const info = (row: any) => {
	state.currentCertificate = { ...row }
	state.detailDialogVisible = true
}

// 格式化日期 (yyyy-MM-dd)
const formatDate = (dateString: string) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	return date.toLocaleDateString()
}

// 格式化日期时间 (yyyy-MM-dd HH:mm:ss)
const formatDateTime = (dateString: string) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	return date.toLocaleString()
}

onMounted(()=>{
	loadCertificates()
})

// 下载证书方法
const downloadCertificate = (row: any) => {


	if (!row.img) {
		ElMessage.warning('没有可下载的证书图片')
		return
	}

	// 创建一个隐藏的<a>标签用于下载
	const link = document.createElement('a')
	link.href = row.img
	link.target = '_blank'
	// 从URL中提取文件名，如果没有则使用默认名
	const fileName = row.img.split('/').pop() || `certificate_${row.id}`
	link.download = fileName
	// 触发点击事件
	document.body.appendChild(link)
	link.click()
	document.body.removeChild(link)

	// 如果是跨域图片，需要使用fetch API
	if (isCrossOrigin(row.img)) {
		downloadCrossOriginImage(row.img, fileName)
	}
}
// 检查是否是跨域图片
const isCrossOrigin = (url: string) => {
	try {
		return new URL(url).origin !== window.location.origin
	} catch {
		return false
	}
}
// 处理跨域图片下载
const downloadCrossOriginImage = async (url: string, filename: string) => {
	try {
		const response = await fetch(url, {
			mode: 'cors',
			credentials: 'same-origin' // 根据你的后端配置可能需要调整
		})

		if (!response.ok) throw new Error('下载失败')
		const blob = await response.blob()
		const blobUrl = window.URL.createObjectURL(blob)
		const link = document.createElement('a')
		link.href = blobUrl
		link.download = filename
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)

		// 释放内存
		window.URL.revokeObjectURL(blobUrl)
	} catch (error) {

	}
}

</script>

<style scoped lang="scss">

</style>

<route lang="json">
{
"meta": {
"layout": "front"
}
}
</route>
