<template>
	<el-drawer v-model="isShowDrawer" title="文档预览" size="60%" :close-on-click-modal="true">
		<div class="preview-container" v-loading="loading">
			<div class="preview-header">
				<div class="file-info">
					<el-icon class="file-icon" :style="{ color: getFileIconColor(documentInfo.fileType) }">
						<ele-Document />
					</el-icon>
					<div class="file-detail">
						<h3>{{ documentInfo.name }}</h3>
						<div class="meta">
							<span>类型: {{ documentInfo.fileType?.toUpperCase() }}</span>
							<span>大小: {{ formatFileSize(documentInfo.fileSize) }}</span>
							<span>字符数: {{ documentInfo.charCount }}</span>
							<span>分段数: {{ documentInfo.chunkCount }}</span>
						</div>
					</div>
				</div>
				<div class="actions">
					<el-button type="primary" size="small" @click="onDownload">
						<el-icon><ele-Download /></el-icon>
						下载
					</el-button>
				</div>
			</div>
			<el-divider />
			<div class="preview-content">
				<el-tabs v-model="activeTab">
					<el-tab-pane label="原文内容" name="content">
						<div class="content-area" v-html="formattedContent"></div>
					</el-tab-pane>
					<el-tab-pane label="文档信息" name="info">
						<el-descriptions :column="2" border>
							<el-descriptions-item label="文档名称">{{ documentInfo.name }}</el-descriptions-item>
							<el-descriptions-item label="所属数据集">{{ documentInfo.knowledgeName }}</el-descriptions-item>
							<el-descriptions-item label="文件类型">{{ documentInfo.fileType?.toUpperCase() }}</el-descriptions-item>
							<el-descriptions-item label="文件大小">{{ formatFileSize(documentInfo.fileSize) }}</el-descriptions-item>
							<el-descriptions-item label="字符数">{{ documentInfo.charCount }}</el-descriptions-item>
							<el-descriptions-item label="分段数">{{ documentInfo.chunkCount }}</el-descriptions-item>
							<el-descriptions-item label="处理状态">
								<el-tag :type="getStatusTagType(documentInfo.status)">{{ getStatusText(documentInfo.status) }}</el-tag>
							</el-descriptions-item>
							<el-descriptions-item label="索引状态">
								<el-tag :type="getIndexStatusTagType(documentInfo.indexStatus)">{{ getIndexStatusText(documentInfo.indexStatus) }}</el-tag>
							</el-descriptions-item>
							<el-descriptions-item label="上传时间" :span="2">{{ documentInfo.createdAt }}</el-descriptions-item>
							<el-descriptions-item label="更新时间" :span="2">{{ documentInfo.updatedAt }}</el-descriptions-item>
							<el-descriptions-item label="错误信息" :span="2" v-if="documentInfo.errorMessage">
								<span style="color: #f56c6c">{{ documentInfo.errorMessage }}</span>
							</el-descriptions-item>
						</el-descriptions>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
	</el-drawer>
</template>

<script lang="ts">
export default {
	name: 'previewDocument',
};
</script>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { previewDocument, getDocument } from '/@/api/knowledge/document';

// 抽屉状态
const isShowDrawer = ref(false);
const loading = ref(false);
const activeTab = ref('content');

// 文档信息
const documentInfo = reactive({
	id: '',
	name: '',
	knowledgeId: '',
	knowledgeName: '',
	fileType: '',
	fileSize: 0,
	filePath: '',
	charCount: 0,
	chunkCount: 0,
	status: '',
	indexStatus: '',
	errorMessage: '',
	createdAt: '',
	updatedAt: '',
});

// 文档内容
const documentContent = ref('');

// 格式化内容
const formattedContent = computed(() => {
	if (!documentContent.value) return '<p style="color: #909399">暂无内容</p>';
	// 将换行符转换为HTML换行
	return documentContent.value
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/\n/g, '<br>')
		.replace(/ {2}/g, '&nbsp;&nbsp;');
});

// 获取文件图标颜色
const getFileIconColor = (fileType: string) => {
	switch (fileType) {
		case 'pdf':
			return '#f56c6c';
		case 'docx':
			return '#409eff';
		case 'txt':
			return '#909399';
		case 'md':
			return '#67c23a';
		case 'html':
			return '#e6a23c';
		default:
			return '#909399';
	}
};

// 格式化文件大小
const formatFileSize = (size: number) => {
	if (!size) return '0 B';
	if (size < 1024) return size + ' B';
	if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
	return (size / 1024 / 1024).toFixed(1) + ' MB';
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
	switch (status) {
		case 'pending':
			return 'info';
		case 'processing':
			return 'warning';
		case 'completed':
			return 'success';
		case 'failed':
			return 'danger';
		default:
			return 'info';
	}
};

// 获取状态文本
const getStatusText = (status: string) => {
	switch (status) {
		case 'pending':
			return '待处理';
		case 'processing':
			return '处理中';
		case 'completed':
			return '已完成';
		case 'failed':
			return '失败';
		default:
			return status;
	}
};

// 获取索引状态标签类型
const getIndexStatusTagType = (status: string) => {
	switch (status) {
		case 'not_indexed':
			return 'info';
		case 'indexing':
			return 'warning';
		case 'indexed':
			return 'success';
		case 'failed':
			return 'danger';
		default:
			return 'info';
	}
};

// 获取索引状态文本
const getIndexStatusText = (status: string) => {
	switch (status) {
		case 'not_indexed':
			return '未索引';
		case 'indexing':
			return '索引中';
		case 'indexed':
			return '已索引';
		case 'failed':
			return '索引失败';
		default:
			return status;
	}
};

// 打开弹窗
const openDialog = async (row: any) => {
	// 先设置基本信息
	Object.assign(documentInfo, row);
	documentContent.value = '';
	activeTab.value = 'content';
	isShowDrawer.value = true;

	// 获取文档详情和内容
	loading.value = true;
	try {
		const [detailRes, contentRes] = await Promise.all([getDocument(row.id), previewDocument(row.id)]);

		if (detailRes.data) {
			Object.assign(documentInfo, detailRes.data);
		}
		if (contentRes.data) {
			documentContent.value = contentRes.data.content || '';
		}
	} catch (_error) {
		documentContent.value = '';
		ElMessage.error('获取文档详情失败');
	} finally {
		loading.value = false;
	}
};

// 下载文档
const onDownload = () => {
	if (documentInfo.filePath) {
		window.open(documentInfo.filePath, '_blank');
	} else {
		ElMessage.warning('文档路径不存在');
	}
};

// 暴露方法
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.preview-container {
	height: 100%;
	display: flex;
	flex-direction: column;

	.preview-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.file-info {
			display: flex;
			align-items: center;

			.file-icon {
				font-size: 48px;
				margin-right: 16px;
			}

			.file-detail {
				h3 {
					margin: 0 0 8px 0;
					font-size: 18px;
				}

				.meta {
					color: #909399;
					font-size: 13px;

					span {
						margin-right: 16px;
					}
				}
			}
		}
	}

	.preview-content {
		flex: 1;
		overflow: auto;

		.content-area {
			padding: 16px;
			background: #f5f7fa;
			border-radius: 4px;
			min-height: 400px;
			line-height: 1.8;
			font-size: 14px;
			white-space: pre-wrap;
			word-break: break-all;
		}
	}
}
</style>
