<template>
	<div class="knowledge-document-page">
		<div class="knowledge-document-container">
			<el-card shadow="hover">
				<!-- 面包屑导航 -->
				<div class="breadcrumb-nav mb15" v-if="currentknowledge.id">
					<el-breadcrumb separator="/">
						<el-breadcrumb-item :to="{ path: '/knowledge/knowledge' }">数据集管理</el-breadcrumb-item>
						<el-breadcrumb-item>{{ currentknowledge.name }}</el-breadcrumb-item>
					</el-breadcrumb>
				</div>

				<div class="knowledge-document-search mb15">
					<el-form :inline="true">
						<el-form-item label="所属数据集" v-if="!currentknowledge.id">
							<el-select size="default" v-model="tableData.param.knowledgeId" placeholder="请选择数据集" clearable style="width: 180px">
								<el-option v-for="item in knowledgeOptions" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
						<el-form-item label="文档名称">
							<el-input size="default" v-model="tableData.param.title" placeholder="请输入文档名称" clearable style="width: 200px" />
						</el-form-item>
						<el-form-item label="文件类型">
							<el-select size="default" v-model="tableData.param.fileType" placeholder="请选择类型" clearable style="width: 120px">
								<el-option label="PDF" value="pdf" />
								<el-option label="Word" value="docx" />
								<el-option label="TXT" value="txt" />
								<el-option label="Markdown" value="md" />
								<el-option label="HTML" value="html" />
							</el-select>
						</el-form-item>
						<el-form-item label="状态">
							<el-select size="default" v-model="tableData.param.status" placeholder="请选择状态" clearable style="width: 120px">
								<el-option label="待处理" value="pending" />
								<el-option label="处理中" value="processing" />
								<el-option label="已完成" value="completed" />
								<el-option label="失败" value="failed" />
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button size="default" type="primary" @click="getDocumentList">
								<el-icon><ele-Search /></el-icon>
								查询
							</el-button>
							<el-button size="default" @click="onResetQuery">
								<el-icon><ele-Refresh /></el-icon>
								重置
							</el-button>
							<el-button size="default" type="success" @click="onOpenUpload" v-auth="'api/v1/knowledge/document/upload'">
								<el-icon><ele-Upload /></el-icon>
								上传文档
							</el-button>
							<el-button
								size="default"
								type="danger"
								@click="onBatchDelete"
								:disabled="selectedIds.length === 0"
								v-auth="'api/v1/knowledge/document/batchDelete'"
							>
								<el-icon><ele-Delete /></el-icon>
								批量删除
							</el-button>
						</el-form-item>
					</el-form>
				</div>
				<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading" border @selection-change="onSelectionChange">
					<el-table-column type="selection" width="50" align="center" />
					<el-table-column type="index" label="序号" width="60" align="center" />
					<el-table-column prop="name" label="文档名称" min-width="200" show-overflow-tooltip>
						<template #default="scope">
							<div class="document-name">
								<el-icon class="file-icon" :style="{ color: getFileIconColor(scope.row.fileType) }">
									<ele-Document />
								</el-icon>
								<el-link type="primary" @click="onPreview(scope.row)">{{ scope.row.name }}</el-link>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="knowledgeName" label="所属数据集" width="150" show-overflow-tooltip v-if="!currentknowledge.id" />
					<el-table-column prop="fileType" label="文件类型" width="100" align="center">
						<template #default="scope">
							<el-tag size="small">{{ scope.row.fileType?.toUpperCase() }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="fileSize" label="文件大小" width="100" align="center">
						<template #default="scope">
							{{ formatFileSize(scope.row.fileSize) }}
						</template>
					</el-table-column>
					<el-table-column prop="charCount" label="字符数" width="100" align="center" />
					<el-table-column prop="chunkCount" label="分段数" width="80" align="center" />
					<el-table-column prop="status" label="处理状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="indexStatus" label="索引状态" width="100" align="center">
						<template #default="scope">
							<el-tag :type="getIndexStatusTagType(scope.row.indexStatus)">{{ getIndexStatusText(scope.row.indexStatus) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="createdAt" label="上传时间" width="170" show-overflow-tooltip />
					<el-table-column label="操作" width="200" fixed="right" align="center">
						<template #default="scope">
							<el-button size="small" text type="primary" @click="onPreview(scope.row)">预览</el-button>
							<el-button size="small" text type="success" @click="onViewChunks(scope.row)" v-auth="'api/v1/knowledge/document/chunks'"
								>分段</el-button
							>
							<el-button
								size="small"
								text
								type="warning"
								@click="onReprocess(scope.row)"
								v-if="scope.row.status === 'failed'"
								v-auth="'api/v1/knowledge/document/reprocess'"
								>重试</el-button
							>
							<el-button size="small" text type="danger" @click="onRowDel(scope.row)" v-auth="'api/v1/knowledge/document/delete'">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<div class="mt15" style="text-align: right">
					<el-pagination
						v-model:current-page="tableData.param.pageNum"
						v-model:page-size="tableData.param.pageSize"
						:page-sizes="[10, 20, 50, 100]"
						:total="tableData.total"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="onSizeChange"
						@current-change="onCurrentChange"
					/>
				</div>
			</el-card>
		</div>

		<!-- 上传文档弹窗 -->
		<UploadDocument
			ref="uploadDocumentRef"
			:knowledgeOptions="knowledgeOptions"
			:currentknowledgeId="currentknowledge.id"
			@getDocumentList="getDocumentList"
		/>

		<!-- 文档预览弹窗 -->
		<PreviewDocument ref="previewDocumentRef" />

		<!-- 文档分段弹窗 -->
		<DocumentChunks ref="documentChunksRef" />
	</div>
</template>

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

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listDocuments, deleteDocument, batchDeleteDocuments, reprocessDocument } from '/@/api/knowledge/document';
import { listknowledges } from '/@/api/knowledge/dataset';
import UploadDocument from './component/uploadDocument.vue';
import PreviewDocument from './component/previewDocument.vue';
import DocumentChunks from './component/documentChunks.vue';

const route = useRoute();

// 当前数据集
const currentknowledge = reactive({
	id: '',
	name: '',
});

// 数据集选项
const knowledgeOptions = ref<any[]>([]);

// 选中的文档ID
const selectedIds = ref<string[]>([]);

// 表格数据
const tableData = reactive({
	data: [] as any[],
	total: 0,
	loading: false,
	param: {
		title: '',
		knowledgeId: '',
		fileType: '',
		status: undefined as string | undefined,
		pageNum: 1,
		pageSize: 10,
	},
});

// 弹窗ref
const uploadDocumentRef = ref();
const previewDocumentRef = ref();
const documentChunksRef = ref();

// 获取数据集列表
const getknowledgeOptions = async () => {
	try {
		const res: any = await listknowledges({ pageNum: 1, pageSize: 1000 });
		knowledgeOptions.value = res.data?.list || [];
	} catch (_error) {
		knowledgeOptions.value = [];
		ElMessage.error('获取数据集列表失败');
	}
};

// 获取文档列表
const getDocumentList = async () => {
	tableData.loading = true;
	try {
		const params = { ...tableData.param };
		if (currentknowledge.id) {
			params.knowledgeId = currentknowledge.id;
		}
		const res: any = await listDocuments(params);
		tableData.data = res.data?.list || [];
		tableData.total = res.data?.total || 0;
	} catch (_error) {
		tableData.data = [];
		tableData.total = 0;
		ElMessage.error('获取文档列表失败');
	} finally {
		tableData.loading = false;
	}
};

// 获取文件图标颜色
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 onResetQuery = () => {
	tableData.param.title = '';
	if (!currentknowledge.id) {
		tableData.param.knowledgeId = '';
	}
	tableData.param.fileType = '';
	tableData.param.status = undefined;
	tableData.param.pageNum = 1;
	getDocumentList();
};

// 打开上传弹窗
const onOpenUpload = () => {
	uploadDocumentRef.value.openDialog();
};

// 预览文档
const onPreview = (row: any) => {
	previewDocumentRef.value.openDialog(row);
};

// 查看分段
const onViewChunks = (row: any) => {
	documentChunksRef.value.openDialog(row);
};

// 重新处理
const onReprocess = async (row: any) => {
	try {
		await reprocessDocument(row.id);
		ElMessage.success('已重新提交处理');
		getDocumentList();
	} catch (_error) {
		ElMessage.error('重新处理失败');
	}
};

// 选择变化
const onSelectionChange = (selection: any[]) => {
	selectedIds.value = selection.map((item) => item.id);
};

// 批量删除
const onBatchDelete = () => {
	ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个文档吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await batchDeleteDocuments(selectedIds.value);
				ElMessage.success('删除成功');
				getDocumentList();
			} catch (_error) {
				ElMessage.error('批量删除失败');
			}
		})
		.catch(() => {});
};

// 删除文档
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`确定要删除文档【${row.name}】吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await deleteDocument(row.id);
				ElMessage.success('删除成功');
				getDocumentList();
			} catch (_error) {
				ElMessage.error('删除失败');
			}
		})
		.catch(() => {});
};

// 分页大小改变
const onSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	getDocumentList();
};

// 当前页改变
const onCurrentChange = (page: number) => {
	tableData.param.pageNum = page;
	getDocumentList();
};

// 监听路由参数
watch(
	() => route.query,
	(query) => {
		if (query.knowledgeId) {
			currentknowledge.id = query.knowledgeId as string;
			currentknowledge.name = (query.knowledgeName as string) || '';
			tableData.param.knowledgeId = currentknowledge.id;
		} else {
			currentknowledge.id = '';
			currentknowledge.name = '';
		}
		getDocumentList();
	},
	{ immediate: true }
);

// 页面加载时获取数据
onMounted(() => {
	getknowledgeOptions();
});
</script>

<style scoped lang="scss">
.knowledge-document-page {
	padding: 15px;
	.knowledge-document-container {
		.breadcrumb-nav {
			padding-bottom: 10px;
			border-bottom: 1px solid #ebeef5;
		}
		.knowledge-document-search {
			.el-form-item {
				margin-bottom: 10px;
				margin-right: 16px;
			}
		}
		.document-name {
			display: flex;
			align-items: center;
			.file-icon {
				margin-right: 8px;
				font-size: 18px;
			}
		}
	}
}
</style>
