<template>
	<div class="system-edit-role-container">
		<el-dialog title="配置权限" v-model="state.isShowDialog" draggable>
			<div class="custom-tree-node-container">
				<el-table :data="state.menuTableData" style="width: 100%; margin-bottom: 20px" row-key="id" border
					default-expand-all>
					<el-table-column width="180">
						<template #header>
							<el-checkbox v-model="checkAllMenu" :indeterminate="isIndeterminateMenu"
								@change="handleCheckAllChangeMenu">菜单</el-checkbox>
						</template>
						<template #default="scope">
							<el-checkbox-group v-model="state.systemMenuArr" @change="handleCheckedMenuChange">
								<el-checkbox :label="scope.row.permissionCode">{{ scope.row.pageName }}</el-checkbox>
							</el-checkbox-group>
						</template>
					</el-table-column>
					<el-table-column prop="children">
						<template #header>
							<el-checkbox v-model="checkAllBtn" :indeterminate="isIndeterminateBtn"
								@change="handleCheckAllChangeBtn">按钮</el-checkbox>
						</template>
						<template #default="scope">
							<el-checkbox-group v-model="state.systemButtonArr" @change="handleCheckedBtnChange">
								<el-checkbox v-for="(item) in scope.row.buttonArr" :key="item.id"
									:label="item.permissionCode"><span v-if="showSetting">{{ item.permissionCode }}-{{
											item.btnName
									}}</span>
									<span v-else>{{ item.btnName }}</span>
								</el-checkbox>
							</el-checkbox-group>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemEditRole">
import { reactive, onMounted, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { getMenuList } from "/@/api/system/menu";
import { getRolePower, setRolePower } from "/@/api/system/roles"

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	isShowDialog: false,
	menuTableData: <any>[],
	systemMenuArr: <any>[],
	systemButtonArr: <any>[],
	currentRow: {},
	allMenuArr: <any>[],
	allButtonArr: <any>[],
});
const checkAllMenu = ref(false)
const checkAllBtn = ref(false)
const isIndeterminateMenu = ref(false)
const isIndeterminateBtn = ref(false);
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
// 打开弹窗
const openDialog = (row: any) => {
	state.currentRow = row;
	state.systemMenuArr = <any>[];
	state.systemButtonArr = <any>[];
	if (userInfos.value.authBtnList.includes('100205')) {
		getRolePower({ roleid: row.id }).then((res: any) => {
			state.systemMenuArr = res.result?.systemMenuArr ?? [];
			state.systemButtonArr = res.result?.systemButtonArr ?? [];
			// 设置全选状态
			if (state.allButtonArr.length === state.systemButtonArr.length) {
				checkAllBtn.value = true;
				isIndeterminateBtn.value = false;
			} else if (state.systemButtonArr.length !== 0) {
				checkAllBtn.value = false;
				isIndeterminateBtn.value = true;
			} else {
				checkAllBtn.value = false;
				isIndeterminateBtn.value = false;
			}
			if (state.allMenuArr.length === state.systemMenuArr.length) {
				checkAllMenu.value = true;
				isIndeterminateMenu.value = false;
			} else if (state.systemMenuArr.length !== 0) {
				checkAllMenu.value = false;
				isIndeterminateMenu.value = true;
			} else {
				checkAllMenu.value = false;
				isIndeterminateMenu.value = false;
			}
			state.isShowDialog = true;
		});
	} else {
		ElMessage.warning('您没有获取角色权限的权限');
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 保存
const onSubmit = () => {
	let req = {
		roleId: state.currentRow.id,
		roleCode: state.currentRow.name,
		systemMenuArr: state.systemMenuArr,
		systemButtonArr: state.systemButtonArr
	}
	setRolePower(req).then(() => {
		ElMessage({
			message: '操作成功',
			type: 'success',
		})
		closeDialog();
		emit("updateList")
	}).catch(() => { // 新增失败
		closeDialog();
	})
};
// 获取所有菜单
const getMenuListApi = () => {
	getMenuList().then((res: any) => {
		state.menuTableData = res?.result ?? [];
		state.allMenuArr = getAllMenuCode(state.menuTableData);
		state.allButtonArr = getAllButtonCode(state.menuTableData);
	})
}
// 获取所有的菜单code集合
const getAllMenuCode = (arr: any[]) => {
	const newArr = <any>[];
	arr.forEach(v => {
		newArr.push(v.permissionCode);
		if (v.children?.length) {
			newArr.push(...getAllMenuCode(v.children));
		}
	});
	return newArr;
}
// 获取所有按钮的code集合
let newArr1 = <any>[];
const getAllButtonCode = (arr: any) => {
	if (!arr.length) return;

	// 定义一个帮助函数，用于处理每一项数据
	const processItem = (item: any) => {
		for (let i of item.buttonArr) {
			newArr1.push(i.permissionCode)
		}
		if (item.children?.length) {
			getAllButtonCode(item.children)
		}
	}

	arr.forEach(processItem);
	return newArr1;
}
// 全选菜单
const handleCheckAllChangeMenu = (val: boolean) => {
	state.systemMenuArr = val ? state.allMenuArr : []
	isIndeterminateMenu.value = false
}
const handleCheckedMenuChange = (value: string[]) => {
	const checkedCount = value.length;
	checkAllMenu.value = checkedCount === state.allMenuArr.length
	isIndeterminateMenu.value = checkedCount > 0 && checkedCount < state.allMenuArr.length;
}
// 全选按钮
const handleCheckAllChangeBtn = (val: boolean) => {
	state.systemButtonArr = val ? state.allButtonArr : []
	isIndeterminateBtn.value = false
}
const handleCheckedBtnChange = (value: string[]) => {
	const checkedCount = value.length;
	checkAllBtn.value = checkedCount === state.allButtonArr.length;
	isIndeterminateBtn.value = checkedCount > 0 && checkedCount < state.allButtonArr.length;
}
// 开发环境不显示设置
const showSetting = computed(() => {
	return import.meta.env.VITE_MODE_NAME === 'development'
})
onMounted(() => {
	getMenuListApi()
})
// 暴露变量
defineExpose({
	openDialog,
	closeDialog
});
</script>

<style scoped lang="scss">
:deep(.el-table td.el-table__cell div.cell) {
	display: flex;
	box-sizing: border-box;
	align-items: center;
}
</style>
