<template>
	<div class="knowledge-type-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<div class="flex-center-between mb20">
				<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
					<el-form-item label="关键字" prop="keyword" class="mb0">
						<el-input v-model="state.queryParams.keyword" placeholder="类型名称" clearable @keyup.enter="handleQuery" style="width: 250px" />
					</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>
				<div>
					<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>
				</div>
			</div>
			<!-- 表格 -->
			<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"
					>
						<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="ts" setup name="knowledgeType">
import { defineAsyncComponent, ref, h, reactive, onMounted, watch } from 'vue';
import { ElMessageBox, ElMessage, ElTag, ElButton } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { formatDate } from '/@/utils/formatTime';
import { treeList, delType, changeAble, changeStateAndOffShelf } from '/@/api/knowledge/type';
import { throttle } from '/@/utils/tools';
import other from '/@/utils/other';
import type { FormInstance } from 'element-plus';
// 引入组件
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({
	tableData: <EmptyArrayType>[], // 获取所有菜单
	staticArr: <EmptyArrayType>[], // 获取所有菜单
	loading: false, // 加载状态
	isExpand: false,  // 是否展开
	queryParams: {  // 查询参数
		keyword: '',
	},
	expandedRowKeys: <EmptyArrayType>[],  // 展开的行
	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) => h('span', {}, { default: () => formatDate(new Date(data.rowData.lastModificationTime), 'YYYY-mm-dd HH:MM:SS') }),
		},
		{
			key: 'isEnable',
			dataKey: 'isEnable',
			title: '状态',
			width: 100,
			cellRenderer: (data: any) => {
				return h(ElTag, { type: data.rowData.isEnable ? 'success' : 'info' }, { default: () => (data.rowData.isEnable ? '启用' : '禁用') });
			},
		},
		{
			key: 'handle',
			title: '操作',
			width: 200,
			fixed: 'right',
			align: 'center',
			cellRenderer: (data: any) => {
				return h('p', {}, [
					auth('knowledge:type:edit')
						? h(
								ElButton,
								{
									onClick: () => onOpenEdit(data.rowData),
									type: 'primary',
									link: true,
									title: '修改菜单',
								},
								{ default: () => '修改' }
						  )
						: '',

					data.rowData.isEnable
						? h('span', {}, [
								auth('knowledge:type:disable&enable')
									? h(
											ElButton,
											{
												onClick: () => onDisabled(data.rowData),
												type: 'danger',
												link: true,
												title: '停用分类',
											},
											{ default: () => '停用' }
									  )
									: '',
								auth('knowledge:type:disable&undercarriage')
									? h(
											ElButton,
											{
												onClick: () => undercarriage(data.rowData),
												type: 'info',
												link: true,
												title: '停用并下架关联知识',
												style: { marginLeft: 0 },
											},
											{ default: () => '停用并下架' }
									  )
									: '',
						  ])
						: auth('knowledge:type:disable&enable')
						? h(
								ElButton,
								{
									onClick: () => onEnable(data.rowData),
									type: 'success',
									link: true,
									title: '启用分类',
								},
								{ default: () => '启用' }
						  )
						: '',
					auth('knowledge:type:delete')
						? h(
								ElButton,
								{
									onClick: () => onDelete(data.rowData),
									type: 'danger',
									link: true,
									title: '删除分类',
								},
								{ default: () => '删除' }
						  )
						: '',
				]);
			},
		},
	],
});
// 表格过滤
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.loading = false;
	} else {
		queryList();
	}
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
	state.expandedRowKeys = [];
	emptyArr = [];
}, 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 onDisabled = (row: any) => {
	ElMessageBox.confirm(`是否要停用该类型？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			changeAble(row.id).then(() => {
				ElMessage.success('停用成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 启用
const onEnable = (row: any) => {
	ElMessageBox.confirm(`是否要启用该类型？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			changeAble(row.id).then(() => {
				ElMessage.success('启用成功');
				queryList();
			});
		})
		.catch(() => {});
};

// 删除当前行
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确认删除该类型？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delType(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
const undercarriage = (row: any) => {
	ElMessageBox.confirm(`确定要停用并下架相关知识？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			changeStateAndOffShelf(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 获取知识库类型
const queryList = () => {
	if (!auth('knowledge:type:query')) ElMessage.error('抱歉，您没有权限查询知识库类型');
	else {
		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();
});
</script>
<style lang="scss" scoped>
.knowledge-type-container {
	.table {
		flex: 1;
	}
}
</style>
