<template>
	<xn-form-container
		title="授权资源"
		:width="drawerWidth"
		:visible="visible"
		:destroy-on-close="true"
		:show-pagination="false"
		@close="onClose"
	>
		<a-alert message="非超管角色不可被授权系统模块菜单资源" banner class="mb-2"/>
		<a-spin :spinning="spinningLoading">
			<a-tree
				:field-names="fieldNames"
				checkable
				defaultExpandAll
				:tree-data="loadDatas"
				v-model:checkedKeys="ownResource"
			>
				<template #title="{ title, id,icon }">
					<component :is="icon"/>
					<span>{{ title }}</span>
				</template>
			</a-tree>

		</a-spin>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="grantResourceForm">
import {nextTick} from "vue";
import tool from "@/utils/tool";
import roleApi from "@/api/sys/roleApi";
import resourceApi from "@/api/sys/resourceApi";
import userCenterApi from "@/api/sys/userCenterApi";

const spinningLoading = ref(false);
let firstShowMap = $ref({});
const emit = defineEmits({successful: null});
const submitLoading = ref(false);
// 抽屉的宽度
const drawerWidth = 1000;
// 自动获取宽度，默认获取浏览器的宽度的90%
//(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) * 0.9

const fieldNames = ref({
	children: "children",
	title: "title",
	key: "id"
});
const echoDatalist = ref([]);
const loadDatas = ref([]);
const ownResource = ref([]);

// 获取数据
const loadData = () => {

};
let visible = $ref(false);
// 返回的数据模型，最终需要转换成这样
let resultDataModel = {
	id: "",
	resourceIds: []
};
// 打开抽屉
const onOpen = (record) => {
	resultDataModel.id = record.id;
	visible = true;
	firstShowMap = {};
	// 获取回显数据
	roleApi.roleOwnResource({id: resultDataModel.id}).then(res => {
		ownResource.value = res.map(x => x.id)
	})
	// 获取表格数据
	spinningLoading.value = true;

	resourceApi.menuTree({excludeCategory: [4]}).then(res => {
		loadDatas.value = res;
	}).finally(() => spinningLoading.value = false)
};

// 关闭抽屉
const onClose = () => {
	// 将这些缓存的给清空
	echoDatalist.value = [];
	loadDatas.value = [];
	firstShowMap = {};
	visible = false;
};
// 验证并提交数据
const onSubmit = () => {
	submitLoading.value = true;
	resultDataModel.resourceIds = ownResource.value
	roleApi
		.roleGrantResource(resultDataModel)
		.then(() => {
			onClose();
			emit("successful");
			refreshCacheMenu();
		})
		.finally(() => {
			submitLoading.value = false;
		});
};
// 刷新缓存的菜单
const refreshCacheMenu = () => {
	nextTick(() => {
		userCenterApi.userLoginMenu().then((res) => {
			tool.data.set("MENU", res);
		});
	});
};
// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
});
</script>

<style scoped>
/* 重写复选框的样式 */
.ant-checkbox-wrapper {
	margin-left: 0px !important;
	padding-top: 2px !important;
	padding-bottom: 2px !important;
}
</style>
