<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 v-if="scope.row.auditStatus ==0" link type="primary" @click="update(scope.row,1)">确认</el-button>
					<el-button v-if="scope.row.auditStatus !=0" link type="primary" @click="showDetail(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>

		<!-- 添加/编辑弹窗 -->
		<el-dialog
			v-model="state.dialogVisible"
			:title="state.dialogTitle"
			width="600px"
			:append-to-body="false"
		>
			<el-form :model="state.form" :rules="rules" ref="formRef" label-position="top">
				<el-form-item label="证书" prop="certificateNumber">
					<image-upload @update:imageUrl="handleImageUrl" :image-url="state.form.img" />
				</el-form-item>
				<el-form-item label="用户" prop="userId">
					<el-select v-model="state.form.userId" placeholder="请选择">
						<el-option
							v-for="item in state.userList"
							:key="item.id"
							:label="`${item.nickName} (${item.username})`"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="签发日期" prop="issueDate">
					<el-date-picker
						v-model="state.form.issueDate"
						type="datetime"
						format="YYYY-MM-DD HH:mm:ss"
						value-format="YYYY-MM-DD HH:mm:ss"
					/>
				</el-form-item>
				<el-form-item label="过期日期" prop="expireDate">
					<el-date-picker
						v-model="state.form.expireDate"
						type="datetime"
						format="YYYY-MM-DD HH:mm:ss"
						value-format="YYYY-MM-DD HH:mm:ss"
					/>
				</el-form-item>
				<el-form-item label="证书详情" prop="certificateData">
					<el-input type="textarea" v-model="state.form.certificateData" />
				</el-form-item>
				<el-form-item label="证书状态" prop="status">
					<el-select v-model="state.form.status">
						<el-option label="有效" :value="1" />
						<el-option label="撤销" :value="0" />
						<el-option label="过期" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item label="审核状态" prop="auditStatus">
					<el-select v-model="state.form.auditStatus">
						<el-option label="待审核" :value="0" />
						<el-option label="审核通过" :value="1" />
						<el-option label="审核拒绝" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item label="审核备注" prop="auditComments">
					<el-input type="textarea" v-model="state.form.auditComments" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="submitForm">提交</el-button>
			</template>
		</el-dialog>

		<!-- 详情弹窗 -->
		<el-dialog
			v-model="state.detailDialogVisible"
			title="证书详情"
			width="700px"
			:append-to-body="false"
		>
			<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.user?.password }}</el-descriptions-item>-->
				<el-descriptions-item label="证书生效时间">{{ formatDateSimple(state.currentCertificate.issueDate) }}</el-descriptions-item>
				<el-descriptions-item label="证书过期时间">{{ formatDateSimple(state.currentCertificate.expireDate) }}</el-descriptions-item>
				<el-descriptions-item label="区块链交易哈希" :span="2" v-if="state.currentCertificate.txHash">
					{{ state.currentCertificate.txHash }}
					<el-button type="primary" link @click="viewOnBlockchain(state.currentCertificate.txHash)">查看交易</el-button>
				</el-descriptions-item>
				<el-descriptions-item label="审核备注" :span="2" v-if="state.currentCertificate.auditComments">
					{{ state.currentCertificate.auditComments }}
				</el-descriptions-item>
			</el-descriptions>

			<!-- 证书图片预览 -->
			<div class="certificate-image-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>
	</div>
</template>

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

const formRef = ref<FormInstance>()
const loading = ref(true)

const state = reactive({
	activeTab: 'all',
	dialogVisible: false,
	detailDialogVisible: false,
	chainDialogVisible: false,
	dialogTitle: '',
	certificateList: [] as any[],
	currentCertificate: {} as any,
	form: {},
	query: {
		page: 1,
		limit: 10,
		total: 1,
		auditStatus: null
	},
	userList: []
})

const rules = {
	certificateNumber: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
	userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
	issueDate: [{ required: true, message: '请选择签发日期', trigger: 'change' }],
	expireDate: [{ required: true, message: '请选择过期日期', trigger: 'change' }],
	certificateData: [{ required: true, message: '请输入证书详情', trigger: 'blur' }],
	status: [{ required: true, message: '请选择状态', trigger: 'change' }],
	auditStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }]
}

function update(data: any, status: number) {
	data.auditStatus = status
	adminRequest.put("/sys/certificate", data).then(() => {
		loadCertificates()
		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}`
}

function handleImageUrl(path: string) {
	state.form.img = path
}

const handlePageChange = (page: number) => {
	state.query.page = page
	loadCertificates()
}

const submitForm = () => {
	if (!formRef.value) return
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const method = state.form.id ? 'put' : 'post'
			await adminRequest[method]('/sys/certificate', state.form)
			ElMessage.success(state.form.id ? '修改成功' : '添加成功')
			state.dialogVisible = false
			loadCertificates()
		}
	})
}

const showDetail = (row: any) => {
	state.currentCertificate = { ...row }
	state.detailDialogVisible = true
}

const viewOnBlockchain = (txHash: string) => {
	const explorerUrl = `https://blockchain-explorer.example.com/tx/${txHash}`
	window.open(explorerUrl, '_blank')
}

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 {
	margin-top: 20px;
	text-align: center;
}

.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>
