<template>
	<div class="knowledge-index-container layout-padding">
		<el-card shadow="never" class="h100">
			<splitpanes class="h100" :horizontal="horizontal">
				<pane min-size="16" max-size="25" size="16">
					<el-tabs v-model="state.activeName" stretch @tab-change="resetNode">
						<el-tab-pane label="部门" name="0">
							<el-input v-model="filterOrg" placeholder="请输入部门名称" class="input-with-select mb10" clearable @input="onQueryChanged"> </el-input>
						</el-tab-pane>
						<el-tab-pane label="知识分类" name="1">
							<el-input v-model="filterType" placeholder="请输入知识分类名称" class="input-with-select mb10" clearable> </el-input>
						</el-tab-pane>
						<el-tab-pane label="热点" name="2">
							<el-input v-model="filterHot" placeholder="请输入热点名称" class="input-with-select mb10" clearable> </el-input>
						</el-tab-pane>
					</el-tabs>
					<el-scrollbar style="height: calc(100% - 100px);'" ref="scrollBarRef" v-loading="state.loading">
						<el-tree-v2
							v-show="state.activeName === '0'"
							:data="state.orgData"
							highlight-current
							:expand-on-click-node="false"
							:props="{ children: 'children', label: 'name' }"
							@node-click="handleNodeClick"
							ref="orgRef"
							:filter-method="filterNode"
							:item-size="40"
							:height="treeHeight"
							empty-text="暂无组织数据"
						>
							<template #default="{ node }">
								<span :title="node.label">{{ node.label }}</span>
							</template>
						</el-tree-v2>
						<el-tree
							:data="state.knowledgeOptions"
							highlight-current
							:expand-on-click-node="false"
							:props="{ children: 'children', label: 'name' }"
							@node-click="handleNodeClick"
							ref="typeRef"
							:filter-node-method="filterNodeType"
							node-key="id"
							:style="state.activeName === '1' ? 'min-width: 100%; display: inline-block' : 'display:none'"
						>
						</el-tree>

						<el-tree
							node-key="id"
							:load="loadNode"
							lazy
							v-if="lazyShow"
							:props="{
								label: 'hotSpotFullName',
								children: 'children',
								isLeaf: 'hasChild',
							}"
							:filter-node-method="filterNodeHot"
							@node-click="handleNodeClick"
							v-loading="loading"
							highlight-current
							check-strictly
							:expand-on-click-node="false"
							ref="hotRef"
							:style="state.activeName === '2' ? 'min-width: 100%; display: inline-block' : 'display:none'"
						/>
						<el-tree
							ref="hotRef"
							:data="state.hotSpotData"
							node-key="id"
							v-else
							default-expand-all
							highlight-current
							:props="{
								label: 'hotSpotFullName',
								children: 'children',
							}"
							v-loading="loading"
							:filter-node-method="filterNodeHot"
							@node-click="handleNodeClick"
							:expand-on-click-node="false"
							check-strictly
							:style="state.activeName === '2' ? 'min-width: 100%; display: inline-block' : 'display:none'"
						/>
					</el-scrollbar>
				</pane>
				<pane>
					<el-scrollbar class="pr10 scrollbar__view">
						<el-tabs v-model="state.queryParams.Status" @tab-change="handleClick">
							<el-tab-pane label="全部" name=" "></el-tab-pane>
							<el-tab-pane :label="v.value" :name="v.key" v-for="(v, i) in state.statusOptions" :key="i"></el-tab-pane>
						</el-tabs>
						<!-- 搜索条件 -->
						<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 label="是否公开" prop="IsPublic">
								<el-select v-model="state.queryParams.IsPublic" placeholder="请选择是否公开">
									<el-option label="公开" :value="true" />
									<el-option label="不公开" :value="false" />
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="handleQuery" :loading="state.tableLoading">
									<SvgIcon name="ele-Search" class="mr5" />查询
								</el-button>
								<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.tableLoading">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
							</el-form-item>
						</el-form>
						<ProTable
							ref="proTableRef"
							:columns="columns"
							:data="state.tableData"
							@updateTable="queryList"
							:loading="state.tableLoading"
							:total="state.total"
							v-model:page-index="state.queryParams.PageIndex"
							v-model:page-size="state.queryParams.PageSize"
						>
							<template #tableHeader="scope">
								<el-button type="primary" @click="onOpenAddUser" v-auth="'knowledge:index:add'">
									<SvgIcon name="ele-Plus" class="mr5" />创建知识
								</el-button>
							</template>
							<template #title="{ row }">
								<el-button link type="primary" @click="onPreview(row)">{{ row.title }}</el-button>
							</template>
							<template #knowledgeType="{ row }">
								<span>{{ row.knowledgeType?.map((item) => item.value).join(',') }}</span>
							</template>
							<template #isPublic="{ row }">
								<span>{{ row.isPublic ? '公开' : '不公开' }}</span>
							</template>
							<template #operation="{ row }">
								<el-button
									link
									type="primary"
									@click="onEdit(row)"
									title="编辑"
									v-if="[0, 4, 5, 6].includes(row.newStatus) && row.status != 1"
									v-auth="'knowledge:index:edit'"
								>
									编辑
								</el-button>
								<el-button
									link
									type="danger"
									@click="onRowDel(row)"
									title="删除"
									v-if="[0, 2, 4, 5, 6].includes(row.newStatus) && row.status != 1"
									v-auth="'knowledge:index:delete'"
								>
									删除
								</el-button>
								<el-button
									link
									type="primary"
									@click="offShelfFn(row)"
									title="下架"
									v-if="[3].includes(row.newStatus)"
									v-auth="'knowledge:index:undercarriage'"
								>
									下架
								</el-button>
								<el-button
									link
									type="primary"
									@click="groundingFn(row)"
									title="上架"
									v-if="[4].includes(row.newStatus)"
									v-auth="'knowledge:index:grounding'"
								>
									上架
								</el-button>
								<!--									<el-button
                  link
                  type="primary"
                  @click="onAudit(row)"
                  title="审批"
                  v-if="[1, 2].includes(row.status) && row.isCanHandle"
                  v-auth="'business:order:handle'"
                >
                  审批
                </el-button>-->
								<el-button link type="primary" @click="onPreview(row)" title="查看"> 查看 </el-button>
							</template>
						</ProTable>
						<el-backtop target=".scrollbar__view > div" />
					</el-scrollbar>
				</pane>
			</splitpanes>
		</el-card>
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="queryList" />
	</div>
</template>

<script lang="tsx" setup name="knowledgeManage">
import { ref, reactive, onMounted, watch, defineAsyncComponent, nextTick, onActivated } from 'vue';
import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { throttle } from '@/utils/tools';
import { KnowledgePaged, KnowledgeOffShelf, KnowledgeOnTheShelf, baseData, KnowledgeDel } from '@/api/knowledge';
import { getOrgList } from '@/api/system/organize';
import { treeList } from '@/api/knowledge/type';
import { hotSpotSearch, hotSpotType } from '@/api/business/order';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 引入组件
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批

const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ prop: 'title', label: '标题', width: 300 },
	{ prop: 'knowledgeType', label: '知识分类', width: 200 },
	{ prop: 'statusName', label: '知识状态' },
	{ prop: 'attribution', label: '知识归属', width: 120 },
	{ prop: 'sourceOrganize.name', label: '来源部门', width: 120 },
	{ prop: 'hotspotName', label: '热点', minWidth: 200 },
	{ prop: 'isPublic', label: '是否公开' },
	{ prop: 'pageView', label: '阅读次数' },
	{
		prop: 'onShelfTime',
		label: '上架时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.onShelfTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'offShelfTime',
		label: '下架时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.offShelfTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'creatorName', label: '创建人', width: 120 },
	{ prop: 'creatorOrgName', label: '创建部门', width: 150 },
	{
		prop: 'creationTime',
		label: '创建时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'lastModificationTime',
		label: '更新时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 250, align: 'center' },
]);
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 10, //每页条数
		Keyword: null, //关键字
		Status: ' ', //状态
		OrgId: null, //组织机构
		HotSpotTypeId: null, //热点分类
		KnowledgeTypeId: null, //知识类型
		Title: null, //标题
		Summary: null, //摘要
	},
	activeName: '0', //tab切换
	tableData: [], //表格数据
	total: 0, //总条数
	loading: false, //表格loading
	tableLoading: false, //表格loading
	orgData: [], //组织机构数据
	knowledgeOptions: [], //知识库类型数据
	statusOptions: [], //状态数据
	hotSpotData: [], //热点数据
});
const router = useRouter(); //路由
const ruleFormRef = ref<FormInstance>(); //表单ref
const horizontal = ref(false);

// 热点分类懒加载
const lazyShow = ref(true);
const loading = ref(false);
const loadNode = async (node: any, resolve: any) => {
	try {
		loading.value = true;
		if (node.isLeaf) return resolve([]);
		const res: any = await hotSpotType({ id: node.data.id ? node.data.id : null });
		resolve(res.result);
		loading.value = false;
	} catch (error) {
		resolve([]);
		loading.value = true;
	}
};
// 三个类型的搜索
const filterOrg = ref('');
const orgRef = ref<RefType>();
const onQueryChanged = (query: string) => {
	if (query) {
		orgRef.value!.filter(query);
	} else {
		orgRef.value!.filter(query);
		orgRef.value?.setExpandedKeys([]);
	}
};
const filterNode = (value: string, data: any) => {
	if (!value) return true;
	return data.name.includes(value);
};
const filterType = ref('');
const typeRef = ref<RefType>();
watch(filterType, (val) => {
	typeRef.value!.filter(val);
});
const filterNodeType = (value: string, data: any) => {
	if (!value) return true;
	return data.name.includes(value);
};
const filterHot = ref('');
const hotRef = ref<RefType>();
watch(filterHot, (val) => {
	if (val) {
		lazyShow.value = false; //当输入框有值时关闭懒加载
		loading.value = true;
		hotSpotSearch(val)
			.then((res) => {
				//获取后端搜索的数据 	//selectMacTree是我自己的后端接口，你们换成自己的
				state.hotSpotData.length = 0;
				state.hotSpotData = res.result ?? [];
				hotRef.value!.filter(val);
				loading.value = false;
			})
			.catch((e) => {
				loading.value = false;
			});
	} else if (val == '' || val == ' ' || val == null) {
		lazyShow.value = true; // 懒加载树显示
	}
});
const filterNodeHot = (value: string, data: any) => {
	if (!value) return true;
	return data.hotSpotName.includes(value);
};

// 切换tab 查询列表
const handleClick = () => {
	queryList();
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	queryList();
}, 500);
// 获取所有组织结构 和基础数据
const getOrgListApi = async () => {
	state.loading = true;
	try {
		const res: any = await Promise.all([getOrgList(), treeList({ IsEnable: true }), baseData()]);
		state.orgData = res[0].result ?? []; //部门
		state.knowledgeOptions = res[1].result ?? []; // 知识类型
		state.statusOptions = res[2].result ?? []; // 列表状态
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
/** 获取知识列表 */
const queryList = () => {
	state.tableLoading = true;
	KnowledgePaged(state.queryParams)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 点击节点
const handleNodeClick = (data: any) => {
	switch (state.activeName) {
		case '0':
			state.queryParams.CreateOrgId = data.id;
			break;
		case '1':
			state.queryParams.KnowledgeTypeId = data.id;
			break;
		case '2':
			state.queryParams.HotspotId = data.id;
			break;
		default:
			break;
	}
	queryList();
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreateOrgId = null;
	state.queryParams.KnowledgeTypeId = null;
	state.queryParams.HotspotId = null;
	filterOrg.value = '';
	filterType.value = '';
	filterHot.value = '';
	typeRef.value?.setCurrentKey(null);
	orgRef.value?.setCurrentKey(null);
	hotRef.value?.setCurrentKey(null);
	handleQuery();
}, 500);
// 重置选中的节点
const resetNode = () => {
	state.queryParams.CreateOrgId = null;
	state.queryParams.KnowledgeTypeId = null;
	state.queryParams.HotspotId = null;
	filterOrg.value = '';
	filterType.value = '';
	filterHot.value = '';
	typeRef.value?.setCurrentKey(null);
	orgRef.value?.setCurrentKey(null);
	hotRef.value?.setCurrentKey(null);
	handleQuery();
};
// 新增知识
const onOpenAddUser = () => {
	if (!router.hasRoute('knowledgeEdit')) {
		ElMessage.warning('当前用户未配置新增知识页面');
		return;
	}
	router.push({
		name: 'knowledgeEdit',
		params: {
			tagsViewName: '新增知识',
		},
	});
};
// 修改知识
const onEdit = (row: any) => {
	if (!router.hasRoute('knowledgeEdit')) {
		ElMessage.warning('当前用户未配置知识编辑页面');
		return;
	}
	router.push({
		name: 'knowledgeEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑知识',
		},
	});
};
// 预览
const onPreview = (row: any) => {
	if (!router.hasRoute('knowledgePreview')) {
		ElMessage.warning('当前用户未配置知识查看页面');
		return;
	}
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.id,
			tagsViewName: '知识查看',
		},
	});
};
// 审批
const processAuditRef = ref<RefType>(); //审核记录ref
const onAudit = (row: any) => {
	const params = {
		id: row.workflowId,
		processType: '工单办理',
		orderDetail: {},
		extra: {
			dialogTitle: '知识审批',
			inputPlaceholder: '办理意见',
			annexName: '知识附件',
		},
	};
	processAuditRef.value.openDialog(params);
};
// 下架
const offShelfFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要下架【${row.title}】？知识下架后，将不会被检索到！`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOffShelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 上架
const groundingFn = (row: any) => {
	ElMessageBox.confirm(`是否确定要上架【${row.title}】？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			KnowledgeOnTheShelf(row.id).then(() => {
				ElMessage.success('操作成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 删除知识
const onRowDel = (row: any) => {
	if (row.workflowId) {
		// 如果有流程id，说明是审批中的知识
		const params = {
			id: row.workflowId,
			processType: '删除知识',
			extra: {
				dialogTitle: '删除知识',
				inputPlaceholder: '办理意见',
				annexName: '知识附件',
			},
			orderDetail: row,
		};
		processAuditRef.value.openDialog(params);
	} else {
		// 否则直接删除
		ElMessageBox.confirm(`是否确定要删除【${row.title}】？`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
		})
			.then(() => {
				KnowledgeDel({ data: row }).then(() => {
					ElMessage.success('操作成功');
					handleQuery();
				});
			})
			.catch(() => {});
	}
};
onMounted(() => {
	queryList();
	getOrgListApi();
});
const scrollBarRef = ref<RefType>(); // 滚动条ref
const treeHeight = ref(0);
onMounted(async () => {
	await nextTick();
	treeHeight.value = scrollBarRef.value.wrapRef.clientHeight;
	window.addEventListener('resize', () => {
		treeHeight.value = scrollBarRef.value.wrapRef.clientHeight;
	});
});
onActivated(() => {
	orgRef.value.setData(state.orgData);
});
</script>
<style lang="scss" scoped>
.knowledge-index-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}
	.rightContent {
		height: 100%;
	}
	:deep(.el-tree-node__content) {
		height: 40px;
	}
	:deep(.el-card__body) {
		height: 100%;
	}
}
</style>
