<template>
	<el-drawer v-model="isShowDrawer" title="文档分段管理" size="70%" :close-on-click-modal="true">
		<div class="chunks-container" v-loading="loading">
			<div class="chunks-header">
				<div class="doc-info">
					<span class="doc-name">{{ documentInfo.name }}</span>
					<el-tag size="small" type="info">共 {{ tableData.total }} 个分段</el-tag>
				</div>
				<div class="actions">
					<el-input v-model="searchKeyword" placeholder="搜索分段内容" clearable style="width: 200px" @keyup.enter="onSearch">
						<template #append>
							<el-button @click="onSearch">
								<el-icon><ele-Search /></el-icon>
							</el-button>
						</template>
					</el-input>
				</div>
			</div>

			<div class="chunks-list">
				<div class="chunk-item" v-for="chunk in tableData.data" :key="chunk.id">
					<div class="chunk-header">
						<div class="chunk-index">
							<el-tag size="small"># {{ chunk.chunkIndex + 1 }}</el-tag>
							<span class="char-count">{{ chunk.charCount }} 字符</span>
							<span class="token-count" v-if="chunk.tokenCount">{{ chunk.tokenCount }} tokens</span>
						</div>
						<div class="chunk-actions">
							<el-button size="small" text type="primary" @click="onEditChunk(chunk)" v-auth="'api/v1/knowledge/document/chunk/update'">
								<el-icon><ele-Edit /></el-icon>
								编辑
							</el-button>
							<el-button size="small" text type="danger" @click="onDeleteChunk(chunk)" v-auth="'api/v1/knowledge/document/chunk/delete'">
								<el-icon><ele-Delete /></el-icon>
								删除
							</el-button>
						</div>
					</div>
					<div class="chunk-content" v-if="!chunk.isEditing">
						{{ chunk.content }}
					</div>
					<div class="chunk-edit" v-else>
						<el-input v-model="chunk.editContent" type="textarea" :rows="6" placeholder="请输入分段内容" />
						<div class="edit-actions">
							<el-button size="small" @click="onCancelEdit(chunk)">取消</el-button>
							<el-button size="small" type="primary" @click="onSaveChunk(chunk)" :loading="chunk.saving">保存</el-button>
						</div>
					</div>
				</div>

				<el-empty v-if="tableData.data.length === 0" description="暂无分段数据" />
			</div>

			<!-- 分页 -->
			<div class="chunks-pagination" v-if="tableData.total > 0">
				<el-pagination
					v-model:current-page="tableData.param.pageNum"
					v-model:page-size="tableData.param.pageSize"
					:page-sizes="[10, 20, 50]"
					:total="tableData.total"
					layout="total, sizes, prev, pager, next"
					@size-change="onSizeChange"
					@current-change="onCurrentChange"
				/>
			</div>
		</div>
	</el-drawer>
</template>

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

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listDocumentChunks, updateDocumentChunk, deleteDocumentChunk } from '/@/api/knowledge/document';

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

// 文档信息
const documentInfo = reactive({
	id: '',
	name: '',
});

// 表格数据
const tableData = reactive({
	data: [] as any[],
	total: 0,
	param: {
		documentId: '',
		pageNum: 1,
		pageSize: 10,
	},
});

// 获取分段列表
const getChunkList = async () => {
	loading.value = true;
	try {
		const res: any = await listDocumentChunks(tableData.param);
		tableData.data = (res.data?.list || []).map((item: any) => ({
			...item,
			isEditing: false,
			editContent: '',
			saving: false,
		}));
		tableData.total = res.data?.total || 0;
	} catch (_error) {
		tableData.data = [];
		tableData.total = 0;
		ElMessage.error('获取分段列表失败');
	} finally {
		loading.value = false;
	}
};

// 搜索
const onSearch = () => {
	tableData.param.pageNum = 1;
	getChunkList();
};

// 编辑分段
const onEditChunk = (chunk: any) => {
	chunk.isEditing = true;
	chunk.editContent = chunk.content;
};

// 取消编辑
const onCancelEdit = (chunk: any) => {
	chunk.isEditing = false;
	chunk.editContent = '';
};

// 保存分段
const onSaveChunk = async (chunk: any) => {
	if (!chunk.editContent.trim()) {
		ElMessage.warning('分段内容不能为空');
		return;
	}

	chunk.saving = true;
	try {
		await updateDocumentChunk({ id: chunk.id, content: chunk.editContent });
		chunk.content = chunk.editContent;
		chunk.charCount = chunk.editContent.length;
		chunk.isEditing = false;
		ElMessage.success('保存成功');
	} catch (_error) {
		ElMessage.error('保存失败');
	} finally {
		chunk.saving = false;
	}
};

// 删除分段
const onDeleteChunk = (chunk: any) => {
	ElMessageBox.confirm('确定要删除该分段吗？删除后将影响检索结果。', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await deleteDocumentChunk(chunk.id);
				ElMessage.success('删除成功');
				getChunkList();
			} catch (_error) {
				ElMessage.error('删除失败');
			}
		})
		.catch(() => {});
};

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

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

// 打开弹窗
const openDialog = (row: any) => {
	documentInfo.id = row.id;
	documentInfo.name = row.name;
	tableData.param.documentId = row.id;
	tableData.param.pageNum = 1;
	searchKeyword.value = '';
	isShowDrawer.value = true;
	getChunkList();
};

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

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

	.chunks-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;

		.doc-info {
			display: flex;
			align-items: center;
			gap: 12px;

			.doc-name {
				font-size: 16px;
				font-weight: 500;
			}
		}
	}

	.chunks-list {
		flex: 1;
		overflow: auto;

		.chunk-item {
			border: 1px solid #ebeef5;
			border-radius: 4px;
			margin-bottom: 12px;
			padding: 12px 16px;
			background: #fff;

			&:hover {
				border-color: #409eff;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
			}

			.chunk-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 8px;

				.chunk-index {
					display: flex;
					align-items: center;
					gap: 12px;

					.char-count,
					.token-count {
						font-size: 12px;
						color: #909399;
					}
				}
			}

			.chunk-content {
				color: #606266;
				line-height: 1.6;
				font-size: 14px;
				word-break: break-all;
			}

			.chunk-edit {
				.edit-actions {
					margin-top: 10px;
					text-align: right;
				}
			}
		}
	}

	.chunks-pagination {
		padding-top: 16px;
		border-top: 1px solid #ebeef5;
		display: flex;
		justify-content: flex-end;
	}
}
</style>
