<template>
	<div class="table-box">
		<el-card>
			<el-select v-model="style" class="m-2" placeholder="请选择" @change="onChangeStyle(style)" size="large">
				<el-option v-for="item in optionStyle" :key="item.value" :label="item.label" :value="item.value"
			/></el-select>
			<el-select v-model="type" class="m-2" @change="onChangeType(type)" placeholder="请选择" size="large">
				<el-option v-for="item in optionType" :key="item.value" :label="item.label" :value="item.value"
			/></el-select>
			<el-button type="primary" @click="handleAddItem()">新增</el-button>
		</el-card>
		<ProTable
			ref="proTable"
			title="用户列表"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
			:tool-button="false"
			:pagination="true"
			background
			:isShowSearch="false"
		>
			<template #moduleType="{ row }">
				{{
					row.moduleType == 1
						? "jxjadmin模块"
						: row.moduleType == 2
						? "政务模块"
						: row.moduleType == 3
						? "企业模块"
						: row.moduleType == 4
						? "项目模块"
						: ""
				}}
			</template>
			<template #appShow="{ row }">
				<!-- <el-button type="primary" @click="handleAddItem()">新增</el-button> -->
				{{ row.appShow == 1 ? "是" : "否" }}
			</template>
			<template #operation="{ row }">
				<el-button type="primary" link :icon="Menu" @click="onmenuManage(row)">菜单管理</el-button>
				<el-button type="primary" link :icon="EditPen" @click="handleEditItem('edit', row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(row)">删除</el-button>
			</template>
		</ProTable>

		<el-dialog v-model="dialogMenuVisible" title="菜单管理" append-to-body ref="DialogTable" width="800px" height="800px">
			<el-button type="primary" style="margin-top: -24px" @click="DiaAddItem(toTag)">新增</el-button>
			<el-table :data="gridData">
				<el-table-column property="menuName" label="菜单名称" width="150" />
				<el-table-column property="path" label="菜单路径" width="200" />
				<el-table-column property="status" label="状态">
					<template #default="{ row }">
						{{ row.status == 1 ? "启用" : "禁用" }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="300" align="center">
					<template #default="scope">
						<el-button type="primary" link :icon="Menu" @click="onBtnManage(scope.row)">按钮管理</el-button>
						<el-button type="primary" link :icon="EditPen" @click="onEditItem(scope.row)">编辑</el-button>
						<el-button type="primary" link :icon="Delete" @click="deleteMenu(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<!-- 按钮管理 -->
		<el-dialog v-model="dialogbtnVisible" title="按钮管理" ref="DialogTable" width="40%" height="800px">
			<el-button type="primary" style="margin-top: -24px" @click="onDiabtnAdd(1, buttonData)">新增</el-button>
			<el-table :data="buttonData">
				<el-table-column property="actionName" label="按钮名称" />
				<el-table-column property="actionCode" label="按钮标识" />
				<el-table-column property="status" width="100" label="状态">
					<template #default="{ row }">
						{{ row.status === 1 ? "启用" : "禁用" }}
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template #default="scope">
						<el-button type="primary" link :icon="EditPen" @click="onDiabtnAdd(2, scope.row)">编辑</el-button>
						<el-button type="primary" link :icon="Delete" @click="onBtnDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<DialogForm
			:title="title"
			:formConfig="formConfig"
			:formData="formData"
			v-model:visible="visible"
			append-to-body
			width="700px"
			@confirm="saveItem"
		>
		</DialogForm>
		<!-- 新增\编辑菜单 -->
		<el-dialog v-model="addOrEditDialogVisibleMenu" :title="title" width="30%">
			<!-- <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <div class="dialogTopTitle" :id="titleId" :class="titleClass">
              <img src="@/assets/images/dialogIcon/dialogAddIcon.png" alt="" width="15" height="18" class="configureIcon" />
              <span>{{ dialogMenuTitle }}菜单</span>
            </div>
          </div>
        </template> -->
			<div>
				<el-form :model="formMenu" label-width="155px">
					<el-form-item label="所属模块：">
						<!-- <el-input v-model="formMenu.moduleName" placeholder="请输入" /> -->
						<el-select v-model="formMenu.moduleId" class="m-2" placeholder="请选择">
							<el-option v-for="item in toTag" :key="item.moduleId" :label="item.moduleName" :value="item.moduleId">{{
								item.moduleName
							}}</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="父级菜单：">
						<el-select v-model="formMenu.parentId" class="m-2" placeholder="请选择">
							<el-option v-for="item in fatherNameTo" :key="item.menuId" :label="item.menuName" :value="item.menuId" />
						</el-select>
					</el-form-item>
					<el-form-item label="菜单名称：">
						<el-input v-model="formMenu.menuName" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="菜单图标：">
						<el-input v-model="formMenu.icon" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="菜单路径：">
						<el-input v-model="formMenu.path" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="APP端菜单路径：">
						<el-input v-model="formMenu.appPath" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="状态：">
						<el-select v-model="formMenu.status" class="m-2" placeholder="请选择">
							<el-option v-for="item in menuStatusSel" :key="item.status" :label="item.label" :value="item.status" />
						</el-select>
					</el-form-item>
					<el-form-item label="打开方式：">
						<el-select v-model="formMenu.target" class="m-2" placeholder="请选择">
							<el-option v-for="item in menuTargetSel" :key="item.target" :label="item.label" :value="item.target" />
						</el-select>
					</el-form-item>
					<el-form-item label="优先级：">
						<el-input v-model="formMenu.priority" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字" />
					</el-form-item>
					<el-form-item label="描述：">
						<el-input v-model="formMenu.menuDesc" placeholder="请输入" />
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrEditDialogVisibleMenu = false">取消</el-button>
					<el-button type="primary" @click="onSubmitMenu(formMenu)">保存</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 按钮管理的新增与编辑 -->
		<DialogForm
			:title="title"
			:formConfig="formbtnConfig"
			:formData="formbtnData"
			v-model:visible="btnvisible"
			append-to-body
			width="34%"
			@confirm="onbtnSave"
		>
		</DialogForm>
	</div>
</template>

<script setup lang="tsx" name="jxjSystem">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { User } from "@/api/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import DialogForm from "@/components/DialogForm/index.vue";
import { CirclePlus, Delete, EditPen, Menu, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import {
	getMenuList,
	deleteMunu,
	editMenu,
	addMenu,
	menuList,
	addMenubase,
	editMenubase,
	deletesysMenu,
	btnList,
	addAction,
	editAction,
	deleteAction,
	getDicList
} from "@/api/modules/jxjview";

const router = useRouter();
const type = ref("");
const style = ref("");
// 页面新增和编辑
const visible = ref(false);
const dialogMenuVisible = ref(false);
const addOrEditDialogVisibleMenu = ref(false);
const dialogbtnVisible = ref(false);
// 按钮管理的新增编辑弹窗
const btnvisible = ref(false);
// const moduleName = ref("");
const fatherNameTo = ref([]);
const toTag = ref([{ moduleName: "", moduleId: "" }]);
const title = ref("");
const formData = ref({});
// 获取字典风格
const diaTableData = reactive({
	dictType: "module_style_type"
});
// 获取字典类型
const diaTableType = reactive({
	dictType: "module_type"
});
const formbtnData = ref({
	actionName: "",
	actionCode: "",
	status: "",
	menuId: ""
});
const formMenu = ref({
	moduleId: "",
	parentId: "",
	menuName: "",
	icon: "",
	path: "",
	appPath: "",
	status: "",
	target: "",
	priority: "",
	menuDesc: ""
});

// 获取字典风格
const optionStyle = ref([]);
// 获取字典类型
const optionType = ref([]);
const menuStatusSel = reactive([
	{ status: 0, label: "禁用" },
	{ status: 1, label: "启用" }
]);
const menuTargetSel = reactive([
	{ target: "0", label: "窗口内" },
	{ target: "1", label: "新窗口" }
]);
const mode = ref("");
const gridData = ref([]);
const buttonData = ref([]);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
const DialogTable = ref();
const btnmenuId = ref("");
// 添加数据按钮
const handleAddItem = () => {
	mode.value = "add";
	visible.value = true;
	title.value = "新增模块";
	formData.value = reactive({});
};

// 修改数据按钮
function handleEditItem(index: string, row: any) {
	mode.value = "edit";
	visible.value = true;
	title.value = "编辑模块";

	formData.value = reactive(row);
	// if (row.styleType === 1) {
	// 	formData.value.styleType == "政务后台";
	// }
	// row.styleType == 1
	// 	? formData.value.styleType == "政务后台"
	// 	: row.styleType == 2
	// 	? formData.value.styleType == "企业后台"
	// 	: "项目后台";
}

// 按钮管理的新增
const onDiabtnAdd = (index, row) => {
	if (index === 1) {
		formbtnData.value = reactive({ actionName: "", actionCode: "", status: "", menuId: "" });
		btnvisible.value = true;
		title.value = "新增按钮";
		formbtnData.value.menuId = btnmenuId.value;
	} else {
		btnvisible.value = true;
		title.value = "编辑按钮";
		formbtnData.value = reactive({ ...row });
	}
};

const DiaAddItem = async (val: any) => {
	formMenu.value = reactive({});
	addOrEditDialogVisibleMenu.value = true;
	title.value = "新增菜单";
};
const onEditItem = async (row: any) => {
	addOrEditDialogVisibleMenu.value = true;
	title.value = "编辑菜单";
	formMenu.value = reactive({ ...row });
};

// 菜单管理的点击
const onmenuManage = async (row: any) => {
	title.value = "菜单管理";
	dialogMenuVisible.value = true;
	toTag.value = [{ moduleName: row.moduleName, moduleId: row.moduleId }];
	const res = await getMenuTabList({ moduleId: row.moduleId });
	gridData.value = res.result;
	fatherNameTo.value = res.result.filter(i => {
		return {
			menuName: i.menuName
		};
	});

	fatherNameTo.value.push({ menuId: 0, menuName: "不选" });
};

// 菜单管理的表格
const getMenuTabList = async (params: any) => {
	const res = await menuList(params);
	gridData.value = res.result;
	return menuList(params);
};

// 表格配置项
const columns: ColumnProps[] = [
	{
		prop: "labelName",
		label: "标签名称"
	},
	{
		prop: "moduleName",
		label: "模块名称"
		// search: { el: "input" }
	},
	// 多级 prop
	{ prop: "appName", label: "APP端模块名称" },
	{ prop: "appPlugin", label: "APP端组件名" },
	{ prop: "modulePath", label: "模块路径" },
	{ prop: "moduleIconChecked", label: "解锁模块图标" },
	{ prop: "moduleIconNormal", label: "未解锁模块图标" },
	{
		prop: "moduleType",
		label: "模块类型"
	},
	{ prop: "appShow", label: "是否在APP端显示" },
	{ prop: "operation", label: "操作", fixed: "right", width: 330 }
];

// 弹窗中的配置
const formConfig = reactive({
	formItemConfig: [
		{
			label: "标签名称",
			prop: "labelName",
			type: "input"
		},
		{
			label: "标签排序",
			prop: "labelSortNum",
			type: "input"
		},
		{
			label: "模块名称",
			prop: "moduleName",
			type: "input"
		},
		{
			label: "模块类型",
			prop: "moduleType",
			type: "select",
			data: []
		},
		{
			label: "模块风格",
			prop: "styleType",
			type: "select",
			data: []
		},
		{
			label: "解锁模块图标",
			prop: "moduleIconChecked",
			type: "input"
		},
		{
			label: "未解锁模块图标",
			prop: "moduleIconNormal",
			type: "input"
		},
		{
			label: "模块路径",
			prop: "modulePath",
			type: "input"
		},
		{
			label: "APP端组件名",
			prop: "appPlugin",
			type: "input"
		},
		{
			label: "是否在APP展示",
			prop: "appShow",
			type: "radio",
			data: [
				{ label: "是", value: 1 },
				{ label: "否", value: 0 }
			]
		},
		{
			label: "模块描述",
			prop: "moduleDesc",
			type: "input"
		},
		{
			label: "是否是重要模块",
			prop: "isImportantModule",
			type: "radio",
			data: [
				{ label: "是", value: "1" },
				{ label: "否", value: "0" }
			]
		}
	],
	rules: {
		moduleName: [
			{
				required: true,
				message: "请输入模块名称",
				trigger: "blur"
			}
		]
	}
});

// 按钮管理的新增与编辑
const formbtnConfig = {
	formItemConfig: [
		{
			label: "按钮名称",
			prop: "actionName",
			type: "input"
		},
		{
			label: "按钮标识",
			prop: "actionCode",
			type: "input"
		},
		{
			label: "状态",
			prop: "status",
			type: "select",
			data: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 }
			]
		}
	],
	rules: {
		actionName: [
			{
				required: true,
				message: "请输入按钮名称",
				trigger: "blur"
			}
		],
		actionCode: [
			{
				required: true,
				message: "请输入按钮标识",
				trigger: "blur"
			}
		]
	}
};

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	moduleType: "",
	styleType: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	// console.log(data);
	return {
		list: data.records,
		total: Number(data.total),
		pageNo: Number(data.current),
		pageSize: Number(data.size)
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getMenuList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));

	return getMenuList(newParams);
};

// 页面新增，编辑数据
const saveItem = async (form: any) => {
	if (form.moduleId) {
		const res = await editMenu(form);
		proTable.value.getTableList();
		ElMessage.success("编辑成功");
	} else {
		const res = await addMenu(form);
		ElMessage.success("新增成功");
		proTable.value.getTableList();
	}
	visible.value = false;
};
// 按钮管理的新增与编辑提交
const onbtnSave = async (form: any) => {
	if (form.actionId) {
		const res = await editAction(form);
		ElMessage.success("编辑成功");
	} else {
		const res = await addAction(formbtnData.value);
		ElMessage.success("新增成功");
	}
	btnvisible.value = false;
	getBtnTabList({ menuId: form.menuId });
};

// 菜单新增，编辑数据
const onSubmitMenu = async (form: any) => {
	if (form.menuId) {
		const res = await editMenubase(form);
		ElMessage.success("编辑成功");
	} else {
		const res = await addMenubase(form);
		ElMessage.success("新增成功");
	}
	addOrEditDialogVisibleMenu.value = false;
	getMenuTabList({ moduleId: form.moduleId });
};

const getBtnTabList = async (params: any) => {
	const res = await btnList(params);
	buttonData.value = res.result;
	return btnList(params);
};

// 按钮管理的点击
const onBtnManage = async (row: any) => {
	dialogbtnVisible.value = true;
	btnmenuId.value = row?.menuId;
	await getBtnTabList({ menuId: row.menuId });
};

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
	await useHandleData(deleteMunu, { id: params.moduleId }, `删除【${params.username}】用户`);
	proTable.value.getTableList();
};
// 删除系统菜单信息
const deleteMenu = async (params: User.ResUserList) => {
	await useHandleData(deletesysMenu, { menuId: params.menuId }, `删除【${params.username}】用户`);
	await menuList({ moduleId: params.moduleId });
};
// 删除按钮信息
const onBtnDelete = async (params: User.ResUserList) => {
	await useHandleData(deleteAction, { actionId: params.actionId }, `删除【${params.username}】用户`);
	getBtnTabList({ menuId: params.menuId });
};

const onChangeStyle = async (val: number) => {
	initParam.styleType = val;
	proTable.value.getTableList();
};
const onChangeType = async (val: number) => {
	initParam.moduleType = val;
	proTable.value.getTableList();
};

onMounted(async () => {
	const res = await getDicList(diaTableData);
	optionStyle.value = res.result.map(i => {
		return {
			label: i.dictValue,
			value: i.dictLabel
		};
	});
	formConfig.formItemConfig[3].data = optionStyle.value;
	const res1 = await getDicList(diaTableType);
	optionType.value = res1.result.map(i => {
		return {
			label: i.dictValue,
			value: i.dictLabel
		};
	});
	formConfig.formItemConfig[4].data = optionType.value;
});
</script>
