<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"> <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"> <SvgIcon name="ele-Plus" class="mr5" /> 新增 </el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table
				class="table"
				:data="state.tableData"
				row-key="id"
				default-expand-all
				v-loading="state.loading"
				:tree-props="{ children: 'child' }"
				ref="tableRef"
			>
				<el-table-column prop="name" label="类型名称" />
				<el-table-column prop="sort" label="排序" width="150" />
				<el-table-column prop="creationTime" label="创建时间" width="170" align="center">
					<template #default="{ row }">
						<span>{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="isEnable" label="状态" width="150" align="center">
					<template #default="{ row }">
						<el-tag v-if="row.isEnable" type="success"> 启用 </el-tag>
						<el-tag v-else type="info"> 停用 </el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="250" fixed="right" align="center">
					<template #default="{ row }">
						<el-button link type="primary" @click="onOpenEdit(row)" title="修改"> 修改 </el-button>
						<el-button link type="info" @click="onDisabled(row)" v-if="row.isEnable" title="停用"> 停用 </el-button>
						<el-button link type="warning" @click="onEnable(row)" v-else title="启用"> 启用 </el-button>
						<el-button link type="info" @click="undercarriage(row)" v-if="row.isEnable" title="停用并下架关联知识"> 停用并下架 </el-button>
						<el-button link type="danger" @click="onDelete(row)" title="删除"> 删除 </el-button>
					</template>
				</el-table-column>
				<template #empty>
					<Empty />
				</template>
			</el-table>
		</div>
		<KnowledgeTypeAdd ref="knowledgeTypeAddRef" @updateList="getList" />
		<KnowledgeTypeEdit ref="knowledgeTypeEditRef" @updateList="getList" />
	</div>
</template>
<script lang="ts" setup name="knowledgeType">
import { defineAsyncComponent, ref, h, reactive, onMounted, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { treelist, delType, changeAble, changestateandoffshelf } from '/@/api/knowledge/type';
import { throttle } from '/@/utils/tools';
import type { FormInstance } from 'element-plus';
// 引入组件
const KnowledgeTypeAdd = defineAsyncComponent(() => import('/@/views/knowledge/config/type/component/knowledgeTypeAdd.vue'));
const KnowledgeTypeEdit = defineAsyncComponent(() => import('/@/views/knowledge/config/type/component/knowledgeTypeEdit.vue'));

// 定义变量内容
const knowledgeTypeAddRef = ref();
const knowledgeTypeEditRef = ref();
const ruleFormRef = ref();
const state = reactive({
	tableData: <any>[], // 获取所有菜单
	staticArr: <any>[], // 获取所有菜单
	loading: false,
	isExpand: true,
	queryParams: {
		keyword: '',
	},
	expandedRowKeys: <any>[],
});
// 过滤表格
const formatTable = (list: any[], keyword: string) => {
	let emptyArr: any[] = [];
	console.log(list)
	list.map((item) => {
		if (item.name.includes(keyword)) {
			if (item.child && Array.isArray(item.child) && item.child.length > 0) {
				item.child = formatTable(item.child, keyword);
			}
			emptyArr.push(item);
		} else if (item.child && Array.isArray(item.child) && item.child.length > 0) {
			item.child = formatTable(item.child, keyword);
			if (item.child.length) {
				emptyArr.push(item);
			}
		}
	});
	return emptyArr;
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	if (state.queryParams.keyword) {
		state.loading = true;
		state.tableData = formatTable(JSON.parse(JSON.stringify(state.staticArr)), state.queryParams.keyword);
		state.loading = false;
	} else {
		getList();
	}
}, 1000);
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getList();
};

const expand = () => {
	state.isExpand = !state.isExpand;
	toggleRowExpansionAll(state.tableData, state.isExpand);
};
const tableRef = ref();
const toggleRowExpansionAll = (data: any[], isExpansion: boolean) => {
	data.forEach((item) => {
		tableRef.value.toggleRowExpansion(item, isExpansion);
		if (item.child !== undefined && item.child !== null) {
			toggleRowExpansionAll(item.child, isExpansion);
		}
	});
};
// 打开新增菜单弹窗
const onOpenAdd = () => {
	knowledgeTypeAddRef.value.openDialog(state.tableData);
};
// 打开编辑菜单弹窗
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('停用成功');
				getList();
			});
		})
		.catch(() => {});
};
// 启用
const onEnable = (row: any) => {
	ElMessageBox.confirm(`是否要启用该类型？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			changeAble(row.id).then(() => {
				ElMessage.success('启用成功');
				getList();
			});
		})
		.catch(() => {});
};

// 删除当前行
const onDelete = (row: any) => {
	ElMessageBox.confirm(`是否确认删除该类型？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delType(row.id).then(() => {
				ElMessage.success('删除成功');
				getList();
			});
		})
		.catch(() => {});
};
const undercarriage = (row: any) => {
	ElMessageBox.confirm(`确定要停用并下架相关知识？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			changestateandoffshelf(row.id).then(() => {
				ElMessage.success('操作成功');
				getList();
			});
		})
		.catch(() => {});
};
// 获取所有部门结构
const getList = () => {
	state.loading = true;
	treelist()
		.then((res: any) => {
			state.tableData = res?.result ?? [];
			state.staticArr = res?.result ?? [];
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 页面加载时
onMounted(() => {
	getList();
});
</script>
<style lang="scss" scoped>
.knowledge-type-container {
	.table {
		flex: 1;
	}
}
</style>
