<template>
	<el-row>
<!--		<el-col :span="12">-->
<!--			<el-button type="primary" @click="openForm(true)">添加证书</el-button>-->
<!--		</el-col>-->
		<el-col :span="12" class="text-right">
			<el-button type="info" @click="openChainInstructions">上链须知</el-button>
		</el-col>
	</el-row>

	<!-- 新增Tabs标签 -->
	<el-tabs v-model="state.activeTab"  @tab-click="handleClick">
		<el-tab-pane label="全部" name="all"></el-tab-pane>
		<el-tab-pane label="待审核" name="0"></el-tab-pane>
		<el-tab-pane label="已通过" name="1"></el-tab-pane>
		<el-tab-pane label="已拒绝" name="2"></el-tab-pane>
	</el-tabs>

	<el-table :data="state.certificateList" v-loading="loading" class="el-table">
		<el-table-column prop="id" label="编号" />
		<el-table-column prop="certificateNumber" label="证书编号" />
		<el-table-column prop="path" label="证书" align="center">
			<template #default="scope">
				<el-image
					style="width: 50px; height: 50px"
					:src="scope.row.img"
					:preview-src-list="scope.row.img.toString().split(',')"
					fit="cover"
					:preview-teleported="true"
				/>
			</template>
		</el-table-column>
		<el-table-column prop="user.nickName" label="用户" />
		<el-table-column prop="issueDate" label="签发日期" />
		<el-table-column prop="expireDate" label="过期日期" />
		<el-table-column prop="status" label="证书状态" :formatter="statusText" />
		<!-- 新增审核状态列 -->
		<el-table-column prop="auditStatus" label="审核状态">
			<template #default="scope">
				<el-tag :type="auditTagType(scope.row.auditStatus)">
					{{ auditStatusText(scope.row.auditStatus) }}
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column prop="auditComments" label="审核备注" />
		<el-table-column prop="createdAt" label="创建时间" />
		<el-table-column label="操作" fixed="right" align="center">
			<template #default="scope">
				<el-button link type="primary" @click="openForm(false, scope.row)">编辑/审核</el-button>
				<el-button
					v-if="scope.row.auditStatus == 1"
					link
					type="primary"
					@click="onChain(scope.row)"
					:disabled="scope.row.auditStatus !== 1"
				>
					上链
				</el-button>
				<el-button link type="danger" @click="del(scope.row.id)">删除</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">
				<el-input v-model="state.form.certificateNumber" />
			</el-form-item>
			<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.chainDialogVisible"
		title="上链须知与注意事项"
		width="500px"
		:append-to-body="false"
	>
		<div class="tip-dialog">
			<h4>上链须知</h4>
			<p>1. 一旦证书信息上链后，将不可修改。</p>
			<p>2. 请务必确保所填写的证书信息准确无误。</p>
			<p>3. 上链信息具有公正性和透明性，请谨慎操作。</p>
			<p>4. 如果发现错误，请联系管理员进行后续处理。</p>
		</div>
		<template #footer>
			<el-button type="primary" @click="state.chainDialogVisible = false">我已知晓</el-button>
		</template>
	</el-dialog>
</template>

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

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

const state = reactive(<any>{
	activeTab: 'all', // 当前激活的Tab
	dialogVisible: false,
	chainDialogVisible: false,
	dialogTitle: "",
	certificateList: [] as any[],
	form: {
		id: null,
		certificateNumber: '',
		userId: '',
		issueDate: '',
		expireDate: '',
		certificateData: '',
		blockchainTxId: '',
		img: '',
		status: 1,
		auditStatus: 0,    // 新增审核状态
		auditComments: ''  // 新增审核备注
	},
	query: {
		page: 1,
		limit: 10,
		total: 1,
		isBlock: 0,
		auditStatus: null // 新增审核状态查询参数
	},
	userList: []
})

// 接收子组件传递的路径
function handleImageUrl(path: string) {
	state.form.img = path
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
	state.query.page = 1
	state.query.auditStatus = tab.props.name

	console.log(event)
	loadCertificates()
}


// 审核状态显示
const auditStatusText = (status: number) => {
	const map = { 0: '待审核', 1: '已通过', 2: '已拒绝' }
	return map[status] ?? '未知状态'
}
// 审核状态标签样式
const auditTagType = (status: number) => {
	const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
	return typeMap[status] || ''
}
const onChain = async (row: any) => {
	ElMessageBox.confirm(
		'上链后证书数据将不可更改，是否继续？',
		'提示',
		{
			confirmButtonText: '确认上链',
			cancelButtonText: '取消',
			type: 'warning',
		}
	).then(async () => {
		await adminRequest.put('/sys/certificate/block', row)
		ElMessage.success('上链成功')
		loadCertificates()
	}).catch(() => {})
}
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' }]
}
const openForm = (isAdd: boolean, data?: any) => {
	state.dialogVisible = true
	state.dialogTitle = isAdd ? '添加证书' : '编辑证书'
	nextTick(() => {
		state.form = isAdd ? {
			...state.form,
			id: null,
			auditStatus: 0,
			auditComments: ''
		} : { ...data }
	})
}

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 del = async (id: number) => {
	await adminRequest.delete(`/sys/certificate/delete/${id}`)
	ElMessage.success('删除成功')
	loadCertificates()
}

const statusText = (row: any) => {
	const map = { 0: '撤销', 1: '有效', 2: '过期' }
	return map[row.status] ?? '未知'
}

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

const openChainInstructions = () => {
	state.chainDialogVisible = true
}

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

<style scoped>
/* 新增Tabs样式 */
.el-tabs {
	margin-top: 20px;
	background: #fff;
	padding: 0 20px;
	border-radius: 4px;
}

/* 调整审核状态标签样式 */
.el-tag {
	padding: 0 8px;
	height: 24px;
	line-height: 24px;
}

/* 其他原有样式保持不变 */
.pagination-container {
	margin-top: 20px;
	display: flex;
	justify-content: center;
}

.el-table {
	margin-top: 20px;
}
.pagination-container {
	margin-top: 20px;
	display: flex;
	justify-content: center;
}
.el-table {
	margin-top: 20px;
}
.el-button {
	margin-bottom: 20px;
}
.text-right {
	text-align: right;
}

/* 弹出框样式 */
.el-dialog__header {
	background-color: #409EFF;
	color: #fff;
	text-align: center;
}
.el-dialog {
	border-radius: 8px;
}
.el-dialog__body {
	padding: 20px;
}

/* 表单样式 */
.el-form-item {
	margin-bottom: 15px;
}
.el-input,
.el-date-picker,
.el-select {
	width: 100%;
}

/* 上链须知弹框样式 */
.tip-dialog {
	border: 1px solid #f0ad4e;
	background-color: #fcf8e3;
	border-radius: 5px;
	padding: 20px;
	margin-bottom: 20px;
}
.tip-dialog h4 {
	margin: 0 0 10px 0;
	color: #f0ad4e;
}
.tip-dialog p {
	margin: 0;
	font-size: 14px;
	line-height: 1.5;
}

/* Tabs 样式 */
.filter-tabs {
	margin-top: 20px;
}
</style>
