<template>
	<div class="knowledge-collect-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<splitpanes class="h100" :horizontal="horizontal">
				<pane min-size="16" max-size="25" size="16">
					<el-input v-model="filterGroup" placeholder="请填写分组名称" class="input-with-select mb10" clearable> </el-input>
					<el-scrollbar style="height: calc(100% - 20px);'" ref="scrollBarRef">
						<el-skeleton :loading="state.groupLoading" animated :rows="10">
							<template #default>
								<el-auto-resizer>
									<template #default="{ height, width }">
										<el-tree
											:data="collectGroupOptions"
											node-key="id"
											default-expand-all
											:expand-on-click-node="false"
											:render-content="renderContent"
											empty-text="暂无分组数据"
											:props="{
												label: 'name',
												children: 'children',
											}"
											highlight-current
											@node-click="handleNodeClick"
											ref="treeRef"
											:filter-node-method="filterNode"
										>
										</el-tree>
									</template>
								</el-auto-resizer>
							</template>
						</el-skeleton>
					</el-scrollbar>
				</pane>
				<pane class="h100" style="display: flex; flex-direction: column; flex: 1">
					<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
						<el-form-item label="关键词" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" placeholder="关键词" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
							<el-button @click="resetQuery(ruleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
						</el-form-item>
					</el-form>
					<vxe-toolbar
						ref="toolbarRef"
						:loading="state.tableLoading"
						custom
						:refresh="{
							queryMethod: handleQuery,
						}"
					>
					</vxe-toolbar>
					<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
						<vxe-table
							border
							:loading="state.tableLoading"
							:data="state.tableData"
							:column-config="{ resizable: true }"
							:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
							ref="tableRef"
							height="auto"
							auto-resize
							show-overflow
							:scrollY="{ enabled: true, gt: 100 }"
							id="knowledgeCollect"
							:custom-config="{ storage: true }"
							showHeaderOverflow
						>
							<vxe-column field="knowledge.title" title="标题" min-width="200">
								<template #default="{ row }">
									<el-button link type="primary" @click="onPreview(row)">{{ row.knowledge?.title }}</el-button>
								</template>
							</vxe-column>
							<vxe-column field="knowledgeType" title="知识分类" width="150"></vxe-column>
							<vxe-column field="knowledge.statusText" title="知识状态" width="100"></vxe-column>
							<vxe-column field="score" title="知识评分" width="120"></vxe-column>
							<vxe-column field="creatorName" title="收藏人" width="120"></vxe-column>
							<vxe-column field="creationTime" title="收藏时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column title="操作" fixed="right" width="100" align="center" :show-overflow="false">
								<template #default="{ row }">
									<el-button link type="primary" @click="onPreview(row)" title="知识详情"> 知识详情 </el-button>
								</template>
							</vxe-column>
						</vxe-table>
					</div>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.tableLoading"
					/>
				</pane>
			</splitpanes>
		</div>
		<collect-group-add ref="collectGroupAddRef" @update="getCollectGroupOptions" />
	</div>
</template>

<script lang="tsx" setup name="knowledgeCollect">
import { defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { useRouter } from 'vue-router';
import { collectList, delCollectGroup, getCollectList } from '@/api/knowledge/collect';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

const TextTooltip = defineAsyncComponent(() => import('@/components/TextTooltip/index.vue'));
const CollectGroupAdd = defineAsyncComponent(() => import('@/views/knowledge/collect/components/Collect-group-add.vue')); // 收藏分组新增
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 知识分类
		KnowledgeCollectGroupId: null, // 分组ID
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
	typeData: [], // 知识分类
	groupLoading: false,
});
const horizontal = ref(false);
const ruleFormRef = ref<RefType>(null); // 表单ref
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	collectList(state.queryParams)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
		})
		.finally(() => {
			state.loading = false;
		});
};
// 重置表单
const treeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	treeRef.value?.setCurrentKey(null);
	queryList();
};
// 知识详情
const router = useRouter();
const onPreview = (row: any) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.knowledgeId,
			tagsViewName: '知识详情',
		},
	});
};
// 搜索
const filterGroup = ref('');
watch(filterGroup, (val) => {
	treeRef.value!.filter(val);
});
const filterNode = (value: string, data: any) => {
	if (!value) return true;
	return data.name.includes(value);
};
// 获取收藏分组列表
const collectGroupOptions = ref<Array<any>>([]);
const getCollectGroupOptions = () => {
	state.groupLoading = true;
	getCollectList({ PageSize: 999, PageIndex: 1 })
		.then((res: any) => {
			collectGroupOptions.value = [
				{
					name: '全部',
					id: '',
					children: res.result?.items,
				},
			];
			state.groupLoading = false;
		})
		.catch(() => {
			state.groupLoading = false;
		});
};
// 自定义 render-content 函数
const renderContent = (h, { node, data }) => {
	return (
		<span class="custom-tree-node">
			<TextTooltip content={node.label} effect="dark" placement="top"></TextTooltip>
			{node.label === '全部' ? (
				<span>
					<el-button link type="primary" onClick={(event: MouseEvent) => appendGroup(event)}>
						新增
					</el-button>
				</span>
			) : (
				<el-button link type="danger" onClick={(event: MouseEvent) => deleteGroup(event, node)}>
					删除
				</el-button>
			)}
		</span>
	);
};
// 新增节点
const collectGroupAddRef = ref<RefType>();
const appendGroup = (event: MouseEvent) => {
	// 阻止事件冒泡
	event.stopPropagation();
	collectGroupAddRef.value.openDialog();
};
// 删除节点
const deleteGroup = (event: MouseEvent, node: any) => {
	// 阻止事件冒泡
	event.stopPropagation();
	ElMessageBox.confirm(`删除分组将同步取消该分组下已收藏的知识，是否确认删除?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.groupLoading = true;
			delCollectGroup(node.data.id)
				.then(() => {
					state.groupLoading = false;
					getCollectGroupOptions();
					queryList();
					ElMessage.success('删除成功');
				})
				.catch(() => {
					state.groupLoading = false;
				});
		})
		.catch(() => {});
};
// 点击节点
const handleNodeClick = (data: any) => {
	state.queryParams.KnowledgeCollectGroupId = data.id;
	queryList();
};
// 页面加载时
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getCollectGroupOptions();
});
</script>
<style lang="scss" scoped>
.knowledge-collect-container {
	:deep(.el-tree-node__content) {
		height: 36px;
	}
	:deep(.el-card__body) {
		height: 100%;
	}
}
</style>
<style>
.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
	max-width: 100%;
	overflow: hidden;
}
</style>
