<template>
	<div class="certificate-container">
		<!-- 查询表单 -->
		<el-row>
			<el-col :span="24">
				<el-form :inline="true" :model="state.query" class="demo-form-inline">
					<el-form-item label="证书编号">
						<el-input v-model="state.query.id" placeholder="请输入证书编号" clearable />
					</el-form-item>
					<el-form-item label="状态">
						<el-select
							style="width: 120px"
							v-model="state.query.auditStatus"
							placeholder="请选择状态"
							clearable
						>
							<el-option label="待审核" value="0" />
							<el-option label="已通过" value="1" />
							<el-option label="已拒绝" value="2" />
						</el-select>
					</el-form-item>

					<el-form-item label="过期时间">
						<el-date-picker
							v-model="state.query.expireDate"
							type="date"
							placeholder="请选择日期"
							clearable
						/>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="loadCertificates()">查询</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<!-- 证书列表 -->
		<el-table :data="state.certificateList" v-loading="loading" class="el-table">
			<el-table-column prop="id" label="ID" />
			<el-table-column prop="hex" label="身份信息哈希值" width="180" show-overflow-tooltip align="center" />
			<el-table-column prop="user.password" label="用户公钥" show-overflow-tooltip align="center" />
			<el-table-column
				prop="issueDate"
				label="证书生效时间"
				width="180"
				align="center"
			>
				<template #default="{ row }">
					{{ formatDateSimple(row.issueDate) }}
				</template>
			</el-table-column>

			<el-table-column
				prop="expireDate"
				label="证书过期时间"
				width="180"
				align="center"
			>
				<template #default="{ row }">
					{{ formatDateSimple(row.expireDate) }}
				</template>
			</el-table-column>
			<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="操作项"  align="center" width="230">
				<template #default="scope">
					<el-button link type="primary" @click="update(scope.row)">生成签名信息</el-button>
					<el-button link type="primary"  @click="downloadCertificate(scope.row)">下载证书</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页控件 -->
		<div class="pagination-container">
			<el-pagination
				v-if="state.query.total > 0"
				:current-page="state.query.page"
				:page-size="state.query.limit"
				:total="state.query.total"
				background
				layout="prev, pager, next"
				@current-change="handlePageChange"
			/>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
const loading = ref(true)
const state = reactive({
	certificateList: [] as any[],
	currentCertificate: {} as any,
	form: {},
	query: {
		page: 1,
		limit: 10,
		total: 1,
		auditStatus: null
	},
	userList: []
})

// 下载证书方法
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) {

		console.error('下载错误:', error)
	}
}

function update(data: any, status: number) {
	ElMessage.success("操作完成")
}

function formatDateSimple(val: string) {
	if (!val) return ''
	const d = new Date(val)
	const yyyy = d.getFullYear()
	const mm = String(d.getMonth() + 1).padStart(2, '0')
	const dd = String(d.getDate()).padStart(2, '0')
	return `${yyyy}-${mm}-${dd}`
}

const handlePageChange = (page: number) => {
	state.query.page = page
	loadCertificates()
}
const loadCertificates = async () => {
	loading.value = true
	try {
		const res = await adminRequest.get('/sys/certificate/page', {
			params: {
				...state.query,
				auditStatus: state.query.auditStatus === null ? undefined : state.query.auditStatus
			}
		})
		state.certificateList = res.data.list || []
		state.query.total = res.data.total
	} catch (e) {
		ElMessage.error('数据加载失败')
	} finally {
		loading.value = false
	}
}

onMounted(() => {
	loadCertificates()
	adminRequest.get(`sys/user-front/page`, { params: { limit: 9999 } })
		.then((res: any) => {
			state.userList = res.data.list
		})
})
</script>

<style scoped>
.certificate-container {
	padding: 20px;
}

.pagination-container {
	margin-top: 20px;
	display: flex;
	justify-content: center;
}

.el-table {
	margin-top: 20px;
}


.certificate-image-preview h4 {
	margin-bottom: 10px;
	color: #606266;
	font-weight: normal;
}

.tip-dialog h4 {
	margin: 0 0 10px 0;
	color: #f0ad4e;
}

.tip-dialog p {
	margin: 0;
	font-size: 14px;
	line-height: 1.5;
}
</style>
