<template>
	<div class="knowledge-type-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-row class="mb20" :gutter="10">
				<el-col :xs="24" :sm="12" :md="18" :lg="18" :xl="18">
					<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>
				</el-col>
				<el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" style="text-align: right">
					<el-button type="primary" @click="expand">
						<SvgIcon
							name="ele-ArrowDownBold"
							style="transition: transform var(--el-transition-duration)"
							:style="state.isExpand ? 'transform: none' : 'transform: rotateZ(180deg)'"
							class="mr5"
						/>
						{{ state.isExpand ? '收起' : '展开' }}</el-button
					>
					<el-button type="primary" @click="onOpenAdd" v-auth="'knowledge:type:add'"> <SvgIcon name="ele-Plus" class="mr5" /> 新增 </el-button>
				</el-col>
			</el-row>
			<!-- 表格 -->
			<el-auto-resizer class="table" v-loading="state.loading">
				<template #default="{ height, width }">
					<el-table-v2
						v-model:expanded-row-keys="state.expandedRowKeys"
						:columns="state.columns"
						:data="state.tableData"
						expand-column-key="name"
						fixed
						:width="width"
						:height="height"
						ref="virtuallyTableRef"
					>
						<template #empty>
							<Empty />
						</template>
					</el-table-v2>
				</template>
			</el-auto-resizer>
		</div>
		<knowledge-type-add ref="knowledgeTypeAddRef" @updateList="queryList" />
		<knowledge-type-edit ref="knowledgeTypeEditRef" @updateList="queryList" />
	</div>
</template>
<script lang="tsx" setup name="knowledgeType">
import { defineAsyncComponent, onActivated, onMounted, reactive, ref, watch } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { auth } from '@/utils/authFunction';
import { formatDate } from '@/utils/formatTime';
import { delType, treeList } from '@/api/knowledge/type';
import { throttle } from '@/utils/tools';
import other from '@/utils/other';
// 引入组件
const KnowledgeTypeAdd = defineAsyncComponent(() => import('@/views/knowledge/config/type/component/Knowledge-type-add.vue')); // 新增组件
const KnowledgeTypeEdit = defineAsyncComponent(() => import('@/views/knowledge/config/type/component/Knowledge-type-edit.vue')); // 修改组件

// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	tableData: [], // 获取所有菜单
	staticArr: [], // 获取所有菜单
	loading: false, // 加载状态
	isExpand: false, // 是否展开
	queryParams: {
		// 查询参数
		keyword: null,
	},
	expandedRowKeys: [], // 展开的行
	columns: [
		{
			key: 'name',
			dataKey: 'name',
			title: '类型名称',
			width: 600,
		},
		{
			key: 'sort',
			dataKey: 'sort',
			title: '排序',
			width: 150,
		},
		{
			key: 'lastModificationTime',
			dataKey: 'lastModificationTime',
			title: '更新时间',
			width: 200,
			cellRenderer: (data: any) => {
				return <span>{formatDate(new Date(data.rowData.lastModificationTime), 'YYYY-mm-dd HH:MM:SS')}</span>;
			},
		},
		{
			key: 'isEnable',
			dataKey: 'isEnable',
			title: '状态',
			width: 100,
			cellRenderer: (data: any) => {
				return <el-tag type={data.rowData.isEnable ? 'success' : 'info'}>{data.rowData.isEnable ? '启用' : '禁用'}</el-tag>;
			},
		},
		{
			key: 'handle',
			title: '操作',
			width: 120,
			fixed: 'right',
			align: 'center',
			cellRenderer: (data: any) => {
				return (
					<span>
						{auth('knowledge:type:edit') ? (
							<ElButton onClick={() => onOpenEdit(data.rowData)} type="primary" title="修改菜单" link>
								修改
							</ElButton>
						) : (
							''
						)}
						{auth('knowledge:type:delete') ? (
							<ElButton onClick={() => onDelete(data.rowData)} type="danger" title="删除分类" link>
								删除
							</ElButton>
						) : (
							''
						)}
					</span>
				);
			},
		},
	],
});
// 表格过滤
const formatTable = (list: any[], keyword: string) => {
	if (!list.length || !Array.isArray(list)) return [];
	let emptyArr: any[] = [];
	list.map((item) => {
		if (item.name.includes(keyword)) {
			if (item.children && Array.isArray(item.children) && item.children.length > 0) {
				item.children = formatTable(item.children, keyword);
			}
			emptyArr.push(item);
		} else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			item.children = formatTable(item.children, keyword);
			if (item.children.length) {
				emptyArr.push(item);
			}
		}
	});
	return emptyArr;
};
let emptyArr: any[] = [];
const getExpand = (list: any[]) => {
	if (!list.length || !Array.isArray(list)) return [];
	list.map((item) => {
		if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			getExpand(item.children);
		}
		emptyArr.push(item.id);
	});
	return emptyArr;
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	if (state.queryParams.keyword) {
		state.loading = true;
		state.expandedRowKeys = [];
		emptyArr = [];
		state.tableData = formatTable(other.deepClone(state.staticArr), state.queryParams.keyword);
		state.expandedRowKeys = getExpand(state.tableData);
		state.isExpand = true;
		state.loading = false;
	} else {
		queryList();
	}
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
	state.expandedRowKeys = [];
	emptyArr = [];
	state.isExpand = false;
}, 500);
// 展开收起
const expand = () => {
	state.isExpand = !state.isExpand;
};
watch(
	() => state.isExpand,
	(old: Boolean) => {
		if (old) getAllIds(state.tableData);
		else state.expandedRowKeys = [];
	}
);
const getAllIds = (arr: any) => {
	if (!arr) return [];
	arr.forEach((v: any) => {
		if (v.children?.length) {
			getAllIds(v.children);
			state.expandedRowKeys.push(v.id);
		}
	});
};
// 打开新增分类弹窗
const knowledgeTypeAddRef = ref<RefType>(); // 新增ref
const onOpenAdd = () => {
	knowledgeTypeAddRef.value.openDialog(state.tableData);
};
// 打开编辑分类弹窗
const knowledgeTypeEditRef = ref<RefType>(); // 修改ref
const onOpenEdit = (row: any) => {
	knowledgeTypeEditRef.value.openDialog(row, state.tableData);
};

// 删除当前行
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确认删除该类型？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delType(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 获取知识库类型
const queryList = () => {
	state.loading = true;
	treeList()
		.then((res: any) => {
			state.tableData = res?.result ?? [];
			state.staticArr = res?.result ?? [];
			state.expandedRowKeys = state.tableData.map((v: any) => {
				return v.children.map((i: any) => {
					return i.id;
				});
			});
			state.expandedRowKeys.push(state.tableData[0].id); //默认展开一级
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 页面加载时
onMounted(() => {
	queryList();
});
const virtuallyTableRef = ref<RefType>();
onActivated(() => {
	virtuallyTableRef.value.scrollToTop(0); // 回到顶部
});
</script>
<style lang="scss" scoped>
.knowledge-type-container {
	.table {
		flex: 1;
	}
}
</style>
