<template>
	<div class="knowledge-type-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="关键字" prop="keyword" class="mb0">
					<el-input v-model="state.queryParams.keyword" placeholder="类型名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item class="mb0">
					<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" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onOpenAdd" v-auth="'knowledge:type:add'"> <SvgIcon name="ele-Plus" class="mr5" /> 新增类型 </el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					:loading="state.loading"
					:data="list"
					:column-config="{ resizable: true, useKey: true }"
					:row-config="{ isCurrent: true, isHover: true, useKey: true, height: 36 }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 0 }"
					id="knowledgeType"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform: true,
						rowField: 'id',
						parentField: 'parentId',
					}"
				>
					<vxe-column field="name" title="类型名称" min-width="400" treeNode>
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<span class="pl5" v-html="row.name"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="sort" title="排序" width="80"></vxe-column>
					<vxe-column field="lastModificationTime" title="更新时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.lastModificationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="isEnable" title="状态" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isEnable ? 'success' : 'info'">{{ row.isEnable ? '启用' : '禁用' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="180" align="center" :show-overflow="false">
						<template #default="{ row }">
							<el-button link type="primary" @click="onConnect(row)" title="关联组织" v-auth="'knowledge:type:connect'"> 关联组织 </el-button>
							<el-button link type="primary" @click="onOpenEdit(row)" title="修改" v-auth="'knowledge:type:edit'"> 修改 </el-button>
							<el-button link type="danger" @click="onDelete(row)" title="删除" v-auth="'knowledge:type:delete'"> 删除 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<knowledge-type-add ref="knowledgeTypeAddRef" @updateList="queryList" />
		<knowledge-type-edit ref="knowledgeTypeEditRef" @updateList="queryList" />
		<knowledge-type-connect ref="knowledgeTypeConnectRef" @updateList="queryList" />
	</div>
</template>
<script lang="tsx" setup name="knowledgeType">
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { delType, treeList } from '@/api/knowledge/type';
import { throttle } from '@/utils/tools';
import XEUtils from 'xe-utils';
// 引入组件
const KnowledgeTypeAdd = defineAsyncComponent(() => import('@/views/knowledge/config/type/components/Knowledge-type-add.vue')); // 新增组件
const KnowledgeTypeEdit = defineAsyncComponent(() => import('@/views/knowledge/config/type/components/Knowledge-type-edit.vue')); // 修改组件
const KnowledgeTypeConnect = defineAsyncComponent(() => import('@/views/knowledge/config/type/components/knowledge-type-connect.vue')); // 连接组件
const TextTooltip = defineAsyncComponent(() => import('@/components/TextTooltip/index.vue'));

// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		keyword: null,
	},
});
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	queryList();
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 300);
// 打开新增分类弹窗
const knowledgeTypeAddRef = ref<RefType>(); // 新增ref
const onOpenAdd = () => {
	knowledgeTypeAddRef.value.openDialog(tableData.value);
};
// 打开编辑分类弹窗
const knowledgeTypeEditRef = ref<RefType>(); // 修改ref
const onOpenEdit = (row: any) => {
	knowledgeTypeEditRef.value.openDialog(row, tableData.value);
};

// 删除当前行
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确认删除该类型？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delType(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 关联组织
const knowledgeTypeConnectRef = ref<RefType>();
const onConnect = (row: any) => {
	knowledgeTypeConnectRef.value.openDialog(row);
};
// 获取知识库类型
const tableRef = ref<RefType>();
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = () => {
	state.loading = true;
	treeList()
		.then((res: any) => {
			tableData.value = res?.result ?? [];
			const filterVal = XEUtils.toValueString(state.queryParams.keyword)?.trim().toLowerCase();
			if (filterVal) {
				const filterRE = new RegExp(filterVal, 'gi');
				const options = { children: 'children' };
				const searchProps = ['name'];
				// 搜索为克隆数据，不会污染源数据
				const rest = XEUtils.searchTree(
					tableData.value,
					(item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
					options
				);
				XEUtils.eachTree(
					rest,
					(item) => {
						searchProps.forEach((key) => {
							item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-highlight">${match}</span>`);
						});
					},
					options
				);
				list.value = rest;
				list.value = XEUtils.toTreeArray(list.value);
				nextTick(() => {
					// 搜索之后默认展开所有子节点
					if (tableRef.value) {
						tableRef.value.setAllTreeExpand(true);
					}
				});
			} else {
				list.value = tableData.value;
				list.value = XEUtils.toTreeArray(list.value);
			}

			state.loading = false;
		})
		.catch((err) => {
			console.log(err);
			state.loading = false;
		});
};
// 页面加载时
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
