<template>
	<div class="system-menu-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">
					<el-input v-model="state.queryParams.keyword" placeholder="菜单名称/权限编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item>
					<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="onOpenAddMenu" v-auth="'system:menu: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="systemMenu"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform:true,
						rowField:'id',
						parentField:'parentId',
					}"
				>
					<vxe-column field="pageName" title="菜单名称" min-width="400" treeNode>
						<template #default="{ row }">
							<p style="display: flex; align-items: center">
								<MenuSvgIcon :name="row.icon" />
								<span class="pl5" v-html="row.pageName"></span>
							</p>
						</template>
					</vxe-column>
					<vxe-column field="menuType" title="菜单类型" width="100" align="center">
						<template #default="{ row }">
							<el-tag v-if="row.menuType === 1" type="success">目录</el-tag>
							<el-tag v-if="row.menuType === 2" type="warning">菜单</el-tag>
							<el-tag v-if="row.menuType === 3" type="success">按钮</el-tag>
						</template>
					</vxe-column>
					<vxe-column field="permissionCode" title="权限编码" width="100">
						<template #default="{ row }">
							<span class="pl5" v-html="row.permissionCode"></span>
						</template>
					</vxe-column>
					<vxe-column field="displayOrder" title="排序" width="80"></vxe-column>
					<vxe-column field="component" title="组件路径" width="200"></vxe-column>
					<vxe-column field="isFast" title="是否快捷入口" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isFast ? 'success' : 'info'">{{ row.isFast ? '是' : '否' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column field="isHide" title="是否隐藏" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isHide ? 'success' : 'info'">{{ row.isHide ? '是' : '否' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column field="isKeepAlive" title="是否缓存" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isKeepAlive ? 'success' : 'info'">{{ row.isKeepAlive ? '是' : '否' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column field="isAffix" title="是否固定" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isAffix ? 'success' : 'info'">{{ row.isAffix ? '是' : '否' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column field="isLink" title="是否外链" width="120" align="center">
						<template #default="{ row }">
							<el-tag :type="row.isLink ? 'success' : 'info'">{{ row.isLink ? '是' : '否' }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="110" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onOpenEditMenu(row)" title="修改" v-auth="'system:menu:edit'"> 修改 </el-button>
							<el-button link type="danger" @click="onTableRowDel(row)" title="删除" v-auth="'system:menu:delete'"> 删除 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<menu-add ref="menuAddRef" @updateList="queryList" :menuData="getMenuDataWithOutBtn(tableData)" />
		<menu-edit ref="menuEditRef" @updateList="queryList" :menuData="getMenuDataWithOutBtn(tableData)" />
	</div>
</template>

<script lang="tsx" setup name="systemMenu">
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import { RouteRecordRaw } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getMenuList, removeMenu } from '@/api/system/menu';
import MenuSvgIcon from '@/views/system/menu/components/Menu-svgIcon.vue';
import { throttle } from '@/utils/tools';
import XEUtils from 'xe-utils';
// 引入组件
const MenuAdd = defineAsyncComponent(() => import('@/views/system/menu/components/Menu-add.vue')); // 新增菜单组件
const MenuEdit = defineAsyncComponent(() => import('@/views/system/menu/components/Menu-edit.vue')); // 编辑菜单组件

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 关键字
	},
	expandedRowKeys: [], // 展开的行
	isExpand: false, // 是否展开
});
const ruleFormRef = ref<RefType>(); // 表单ref
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	queryList();
}, 300);
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 打开新增菜单弹窗
const menuAddRef = ref<RefType>(); // 新增菜单弹窗
const onOpenAddMenu = () => {
	menuAddRef.value.openDialog();
};
// 打开编辑菜单弹窗
const menuEditRef = ref<RefType>(); // 修改菜单弹窗
const onOpenEditMenu = (row: RouteRecordRaw) => {
	menuEditRef.value.openDialog(row);
};
// 删除当前行
const onTableRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除菜单：${row.pageName}, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			removeMenu(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 获取所有菜单
const tableRef = ref<RefType>();
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = () => {
	state.loading = true;
	getMenuList()
		.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 = ['pageName', 'permissionCode'];
				// 搜索为克隆数据，不会污染源数据
				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: any) => {
			console.log(err);
			state.loading = false;
		});
};
// 格式化菜单数据并排除按钮
const getMenuDataWithOutBtn = (routes: any) => {
	if (!routes) return [];
	return routes.map((route: any) => {
		const { pageName: title, children, ...rest } = route;
		let filteredChildren = children ? children.filter((child: any) => child.menuType !== 3) : [];
		return {
			...rest,
			title,
			children: getMenuDataWithOutBtn(filteredChildren),
		};
	});
};
// 页面加载时
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
