<template>
		<div class="knowledge-knowledge-page">
			<div class="knowledge-knowledge-container">
				<el-card shadow="hover">
					<div class="knowledge-knowledge-search mb15">
						<el-form :inline="true">
							<el-form-item label="数据集名称">
								<el-input size="default" v-model="tableData.param.keyword" placeholder="请输入数据集名称" clearable style="width: 200px" />
							</el-form-item>
							<el-form-item label="数据集类型">
								<el-select size="default" v-model="tableData.param.datasetType" placeholder="请选择类型" clearable style="width: 150px">
									<el-option label="文本" :value="1" />
									<el-option label="视频" :value="2" />
								</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="enable" />
									<el-option label="禁用" value="disable" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button size="default" type="primary" @click="getknowledgeList">
									<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="onOpenAdd" v-auth="'api/v1/knowledge/knowledge/create'">
									<el-icon><ele-Plus /></el-icon>
									新增
								</el-button>
							</el-form-item>
						</el-form>
					</div>
					<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading" border>
						<el-table-column type="index" label="序号" width="60" align="center" />
						<el-table-column prop="name" label="数据集名称" min-width="180" show-overflow-tooltip>
							<template #default="scope">
								<el-link type="primary" @click="onViewDetail(scope.row)">{{ scope.row.name }}</el-link>
							</template>
						</el-table-column>
						<el-table-column prop="datasetType" label="类型" width="100" align="center">
							<template #default="scope">
								<el-tag :type="getTypeTagType(scope.row.datasetType)">{{ getTypeText(scope.row.datasetType) }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="documentCount" label="文档数" width="100" align="center" />
						<el-table-column prop="charCount" label="字符数" width="120" align="center">
							<template #default="scope">
								{{ formatCharCount(scope.row.charCount) }}
							</template>
						</el-table-column>
						<el-table-column prop="embeddingModel" label="向量模型" width="150" show-overflow-tooltip />
						<el-table-column prop="status" label="状态" width="80" align="center">
							<template #default="scope">
								<el-switch
									v-model="scope.row.statusEnabled"
									inline-prompt
									active-text="启"
									inactive-text="停"
									@change="onStatusChange(scope.row)"
									v-auth="'api/v1/knowledge/knowledge/updateStatus'"
								/>
							</template>
						</el-table-column>
						<el-table-column prop="createdAt" label="创建时间" width="170" show-overflow-tooltip />
						<el-table-column prop="updatedAt" 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="onEdit(scope.row)" v-auth="'api/v1/knowledge/knowledge/update'">编辑</el-button>
								<el-button size="small" text type="success" @click="onManageDocuments(scope.row)">文档</el-button>
								<el-button size="small" text type="danger" @click="onRowDel(scope.row)" v-auth="'api/v1/knowledge/knowledge/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>
			<Editknowledge ref="editknowledgeRef" @getknowledgeList="getknowledgeList" />
		</div>
	</template>

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

	<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listknowledges, deleteknowledge, updateknowledgeStatus } from '/@/api/knowledge/dataset';
import Editknowledge from './component/editDataset.vue';

const router = useRouter();

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

// 编辑弹窗ref
const editknowledgeRef = ref();

// 获取数据集列表
const getknowledgeList = async () => {
	tableData.loading = true;
	try {
		const res: any = await listknowledges(tableData.param);
		const list = res.data?.list || [];
		tableData.data = list.map((item: any) => ({
			...item,
			statusEnabled: item.status === 'enable',
		}));
		tableData.total = res.data?.total || 0;
	} catch (_error) {
		tableData.data = [];
		tableData.total = 0;
		ElMessage.error('获取数据集列表失败');
	} finally {
		tableData.loading = false;
	}
};

// 获取类型标签类型
const getTypeTagType = (datasetType: number) => {
	switch (datasetType) {
		case 1:
			return 'primary';
		case 2:
			return 'success';
		default:
			return 'info';
	}
};

// 获取类型文本
const getTypeText = (datasetType: number) => {
	switch (datasetType) {
		case 1:
			return '文本';
		case 2:
			return '视频';
		default:
			return String(datasetType);
	}
};

// 格式化字符数
const formatCharCount = (count: number) => {
	if (!count) return '0';
	if (count >= 10000) {
		return (count / 10000).toFixed(1) + '万';
	}
	return count.toString();
};

// 重置查询
const onResetQuery = () => {
	tableData.param.keyword = '';
	tableData.param.datasetType = undefined;
	tableData.param.status = undefined;
	tableData.param.pageNum = 1;
	getknowledgeList();
};

// 打开新增弹窗
const onOpenAdd = () => {
	editknowledgeRef.value.openDialog();
};

// 打开编辑弹窗
const onEdit = (row: any) => {
	editknowledgeRef.value.openDialog(row);
};

// 查看详情
const onViewDetail = (row: any) => {
	router.push({ path: '/knowledge/document', query: { knowledgeId: row.id, knowledgeName: row.name } });
};

// 管理文档
const onManageDocuments = (row: any) => {
	router.push({ path: '/knowledge/document', query: { knowledgeId: row.id, knowledgeName: row.name } });
};

// 状态切换
const onStatusChange = async (row: any) => {
	const newStatus = row.statusEnabled ? 'enable' : 'disable';
	const statusText = row.statusEnabled ? '启用' : '禁用';
	try {
		await updateknowledgeStatus({ id: row.id, status: newStatus });
		ElMessage.success(`${statusText}成功`);
	} catch (_error) {
		row.statusEnabled = !row.statusEnabled;
		ElMessage.error(`${statusText}失败`);
	}
};

// 删除数据集
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`确定要删除数据集【${row.name}】吗？删除后相关文档也将被删除！`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await deleteknowledge(row.id);
				ElMessage.success('删除成功');
				getknowledgeList();
			} catch (_error) {
				ElMessage.error('删除失败');
			}
		})
		.catch(() => {});
};

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

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

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

	<style scoped lang="scss">
.knowledge-knowledge-page {
	padding: 15px;
	.knowledge-knowledge-container {
		.knowledge-knowledge-search {
			.el-form-item {
				margin-bottom: 0;
			}
		}
	}
}
	</style>
