<template>
	<div class="system-menu-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" v-waves>
							<SvgIcon name="ele-Search" class="mr5" />查询
						</el-button>
						<el-button @click="resetQuery(ruleFormRef)" v-waves 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="onOpenAddMenu" v-auth="'system:menu: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.menuTableData"
						expand-column-key="pageName"
						fixed
						:width="width"
						:height="height"
					>
						<template #empty>
							<Empty />
						</template>
					</el-table-v2>
				</template>
			</el-auto-resizer>
		</div>
		<menu-add ref="menuAddRef" @updateList="getMenuListApi" />
		<menu-edit ref="menuEditRef" @updateList="getMenuListApi" />
	</div>
</template>

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

// 定义变量内容
const state = reactive({
	menuTableData: <EmptyArrayType>[], // 获取所有菜单
	staticArr: <EmptyArrayType>[],  // 静态路由
	loading: false, // 加载状态
	queryParams: {
		keyword: '',  // 关键字
	},
	expandedRowKeys: <EmptyArrayType>[],  // 展开的行
	columns: [
		{
			key: 'pageName',
			dataKey: 'pageName',
			title: '菜单名称',
			width: 300,
			cellRenderer: (data: any) => {
				return h('p', { style: { justifyContent: 'flex-end' } }, [
					h(MenuSvgIcon, { name: data.rowData.icon }, ''),
					h('span', { class: 'pl5' }, { default: () => data.rowData.pageName }),
				]);
			},
		},
		{
			key: 'menuType',
			dataKey: 'menuType',
			title: '菜单类型',
			width: 100,
			cellRenderer: ({ rowData }: any) => {
				switch (rowData.menuType) {
					case 1:
						return h(ElTag, { type: 'success' }, { default: () => '目录' });
					case 2:
						return h(ElTag, { type: 'success' }, { default: () => '菜单' });
					case 3:
						return h(ElTag, { type: 'info' }, { default: () => '按钮' });
					default:
						return h(ElTag, { type: 'success' }, { default: () => '按钮' });
				}
			},
		},
		{
			key: 'permissionCode',
			dataKey: 'permissionCode',
			title: '权限编码',
			width: 100,
		},
		{
			key: 'forePermissionCode',
			dataKey: 'forePermissionCode',
			title: '权限标志',
			width: 300,
		},
		{
			key: 'displayOrder',
			dataKey: 'displayOrder',
			title: '排序',
			width: 80,
		},
		{
			key: 'component',
			dataKey: 'component',
			title: '组件路径',
			width: 400,
		},
		{
			key: 'isFast',
			dataKey: 'isFast',
			title: '快捷入口',
			width: 100,
			cellRenderer: ({ rowData }) => {
				if ([1, 2].includes(rowData.menuType)) {
					return h(ElTag, { type: rowData.isFast ? 'success' : 'info' }, { default: () => (rowData.isFast ? '是' : '否') });
				}
			},
		},
		{
			key: 'isHide',
			dataKey: 'isHide',
			title: '是否隐藏',
			width: 100,
			cellRenderer: ({ rowData }) => {
				if ([1, 2].includes(rowData.menuType)) {
					return h(ElTag, { type: rowData.isHide ? 'success' : 'info' }, { default: () => (rowData.isHide ? '是' : '否') });
				}
			},
		},
		{
			key: 'isKeepAlive',
			dataKey: 'isKeepAlive',
			title: '是否缓存',
			width: 100,
			cellRenderer: ({ rowData }) => {
				if ([1, 2].includes(rowData.menuType)) {
					return h(ElTag, { type: rowData.isKeepAlive ? 'success' : 'info' }, { default: () => (rowData.isKeepAlive ? '是' : '否') });
				}
			},
		},
		{
			key: 'isAffix',
			dataKey: 'isAffix',
			title: '是否固定',
			width: 100,
			cellRenderer: ({ rowData }) => {
				if ([1, 2].includes(rowData.menuType)) {
					return h(ElTag, { type: rowData.isAffix ? 'success' : 'info' }, { default: () => (rowData.isAffix ? '是' : '否') });
				}
			},
		},
		{
			key: 'isLink',
			dataKey: 'isLink',
			title: '是否外链',
			width: 100,
			cellRenderer: ({ rowData }) => {
				if ([1, 2].includes(rowData.menuType)) {
					return h(ElTag, { type: rowData.isLink ? 'success' : 'info' }, { default: () => (rowData.isLink ? '是' : '否') });
				}
			},
		},
		{
			key: 'handle',
			title: '操作',
			width: 100,
			fixed: 'right',
			align: 'center',
			cellRenderer: (data: any) => {
				// 权限判断
				return h('span', { class: 'flex' }, [
					auth('system:menu:edit')
						? h(
								ElButton,
								{
									onClick: () => onOpenEditMenu(data.rowData),
									type: 'primary',
									link: true,
									title: '修改菜单',
								},
								{ default: () => '修改' })
						: '',
					auth('system:menu:delete')
						? h(
								ElButton,
								{
									onClick: () => onTableRowDel(data.rowData),
									type: 'danger',
									link: true,
									title: '删除菜单',
								},
								{ default: () => '删除' })
						: '',
				]);
			},
		},
	],
	isExpand: false,  // 是否展开
});
const ruleFormRef = ref<RefType>(); // 表单ref
const formatTable = (list: any[], keyword: string) => {
	if (!list.length || !Array.isArray(list)) return [];
	let emptyArr: any[] = [];
	list.map((item) => {
		if (item.pageName.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.menuTableData = formatTable(other.deepClone(state.staticArr), state.queryParams.keyword);
		state.expandedRowKeys = getExpand(state.menuTableData);
		state.loading = false;
	} else {
		getMenuListApi();
	}
}, 300);
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getMenuListApi();
	state.expandedRowKeys = [];
	emptyArr = [];
};
// 打开新增菜单弹窗
const menuAddRef = ref<RefType>();  // 新增菜单弹窗
const onOpenAddMenu = () => {
	menuAddRef.value.openDialog();
};
// 打开编辑菜单弹窗
const menuEditRef = ref<RefType>(); // 修改菜单弹窗
const onOpenEditMenu = (row: RouteRecordRaw) => {
	menuEditRef.value.openDialog(row);
};
const expand = () => {
	state.isExpand = !state.isExpand;
};
watch(
	() => state.isExpand,
	(old: Boolean) => {
		if (old) getAllIds(state.menuTableData);
		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 onTableRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除菜单：${row.pageName}, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			removeMenu(row.id).then(() => {
				ElMessage.success('删除成功');
				getMenuListApi();
			});
		})
		.catch(() => {});
};
// 获取所有菜单
const getMenuListApi = () => {
	if (!auth('system:menu:query')) ElMessage.error('抱歉，您没有权限获取菜单管理列表！');
	else {
		state.loading = true;
		getMenuList()
			.then((res: any) => {
				state.menuTableData = res?.result ?? [];
				state.staticArr = res?.result ?? [];
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};

// 页面加载时
onMounted(() => {
	getMenuListApi();
});
</script>
<style lang="scss" scoped>
.system-menu-container {
	.table {
		flex: 1;
	}
}
</style>
