<template>
	<a-modal v-model:visible="openOtherModel_1" title="分配权限,(请使用Ctrl+F查找关键字)" ok-text="提交" cancel-text="取消"
		@ok="sumbitForm" @cancel="cancelModal" width="100%">
		<a-divider orientation="left">{{detailTitle}}</a-divider>
		<a-spin :spinning="spinning">
			<div v-for="(item, index) in permissionList" style="width: 100%;">
				<a-row :gutter="20" class="a-row" align="middle">
					<a-col span="6" class="a-col">
						<a-checkbox @change="one($event, index, item)"
							:checked="item.checked" :value="item.id">{{item.name}}</a-checkbox>
					</a-col>
					<a-col span="18" class="a-col">
						<div v-for="(childItem, childIndex) in item.childs">
							<a-row align="middle">
								<a-col span="6" class="a-col">
									<a-checkbox @change="two($event, index, childItem)"
										:checked="childItem.checked" :value="childItem.id">{{childItem.name}}
									</a-checkbox>
								</a-col>
								<a-col span="18" class="a-col">
									<a-row :gutter="20" align="middle">
										<a-col span="8" class="a-col"
											v-for="(thirdItem, thirdIndex) in childItem.childs"><a-checkbox
												@change="three($event, index, childItem)"
												:checked="thirdItem.checked" :value="thirdItem.id">{{thirdItem.name}}</a-checkbox></a-col>
									</a-row>
								</a-col>
							</a-row>
						</div>
					</a-col>
				</a-row>
			</div>
		</a-spin>
	</a-modal>
</template>

<script setup lang="ts">
	import { ref, onMounted, defineProps, computed, watch, defineEmits } from 'vue';
	import { getPermissionListWithchilds, getRoleGetpermissions, PostRoleSavepermissions } from '@/apis/models';
	import { message } from 'ant-design-vue';
	import { useCommon } from '@/hooks/useCommon';
	let { store, commomParams, hideOtherModal1, openOtherModel_1 } = useCommon();
	const emit = defineEmits();
	let props = defineProps(['detail_record']);
	let detailTitle = ref<String>('')
	let permissionList = ref<object[]>([]);

	let choose_permission = ref<Number[]>([]);
	let spinning = ref<Boolean>(true); // 加载中

	openOtherModel_1 = computed(() => {
		return store.state.openOtherModel_1;
	})

	watch(() => props.detail_record, async (newVal) => {
		let res = await getPermissionListWithchilds({ page: 1, pagesize: 10, sort: 'id', sortby: "asc", keyword: "" });
		permissionList.value = res.data.permissions;
		spinning.value = false;
		let res1 = await getRoleGetpermissions({ ids: newVal.id.toString() });
		choose_permission.value = getAllIds(res1.data.permissions);
		detailTitle.value = `为角色"${newVal.name}"分配权限，当前拥有${choose_permission.value.length}个权限`;
		permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value);
	})


	const one = (e, idx, item) => {
		if (e.target.checked) {
			choose_permission.value.push(e.target.value);
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			if (item.childs) {
				item.childs.forEach(childItem => {
					choose_permission.value.push(childItem.id);
					console.log(choose_permission.value)
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
					if (childItem.childs) {
						childItem.childs.forEach(thirdItem => {
							choose_permission.value.push(thirdItem.id);
							permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
						})
					}
				})
			}
		} else {
			delValue(e.target.value);
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			if (item.childs) {
				item.childs.forEach(childItem => {
					delValue(childItem.id)
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
					if (childItem.childs) {
						childItem.childs.forEach(thirdItem => {
							delValue(thirdItem.id)
							permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
						})
					}
				})
			}
		}
	}

	const two = (e, idx, item) => {
		let isCheckBrother = false;
		if (e.target.checked) {
			choose_permission.value.push(e.target.value);
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			if (!findValue(permissionList.value[idx].id)) {
				choose_permission.value.push(permissionList.value[idx].id); // 添加一级
				permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				isCheckBrother = true;
			}
			if (item.childs) {
				item.childs.forEach(childItem => {
					choose_permission.value.push(childItem.id);
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				})
			}
		} else {
			delValue(e.target.value)
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			item.childs.forEach(childItem => {
				delValue(childItem.id)
				permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			})
			console.log(choose_permission.value)
			// 判断二级是否还有兄弟选中
			for (let i = 0; i < permissionList.value[idx].childs.length; i++) {
				if (findValue(permissionList.value[idx].childs[i].id)) {
					isCheckBrother = true;
				}
			}
			// 如没有就删除一级权限
			if (!isCheckBrother) {
				delValue(permissionList.value[idx].id);
				permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			}
		}
	}

	const three = (e, idx, item) => {
		if (e.target.checked) {
			choose_permission.value.push(e.target.value)
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			if (!findValue(permissionList.value[idx].id)) {
				choose_permission.value.push(permissionList.value[idx].id); // 添加一级
				permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			}
			if (permissionList.value[idx].childs) {
				if (!findValue(item.id)) {
					choose_permission.value.push(item.id); // 添加二级
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				}
			}
		} else {
			let isCheckBrother = false;
			delValue(e.target.value)
			permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
			// 判断操作是否还有兄弟选中
			if (permissionList.value[idx].childs) {
				for (let i = 0; i < item.childs.length; i++) {
					if (findValue(item.childs[i].id)) {
						isCheckBrother = true;
					}
				}
			
				// 如没有就删除二级权限
				if (!isCheckBrother) {
					delValue(item.id);
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				}

				// 判断二级是否还有兄弟选中
				for (let i = 0; i < permissionList.value[idx].childs.length; i++) {
					if (findValue(permissionList.value[idx].childs[i].id)) {
						isCheckBrother = true;
					}
				}
				// 如没有就删除一级权限
				if (!isCheckBrother) {
					delValue(permissionList.value[idx].id);
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				}
			} else {
				// 如没有就删除二级权限
				if (!isCheckBrother) {
					delValue(item.id);
					permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value)
				}
			}
		}
	}

	// 获取角色的权限
	const getOneRole = async () => {
		let res = await getPermissionListWithchilds({ page: 1, pagesize: 10, sort: 'id', sortby: "asc", keyword: "" });
		permissionList.value = res.data.permissions;
		spinning.value = false;
		let res1 = await getRoleGetpermissions({ ids: props.detail_record.id.toString() });
		choose_permission.value = getAllIds(res1.data.permissions);
		permissionList.value = setCheckedAndReturnNewArray(permissionList.value, choose_permission.value);
	}

	const sumbitForm = () => {
		PostRoleSavepermissions({ role_id: props.detail_record.id, permission_ids: choose_permission.value }).then(res => {
			message.success('提交菜单/权限成功');
			cancelModal();
			emit('successAdd');
		})
	}

	const cancelModal = () => {
		emit('closePermission');
		hideOtherModal1()
	}

	const getAllIds = (permissionArray) => {
		return permissionArray.flatMap(item => [item.id].concat(item.childs ? getAllIds(item.childs) : []));
	}

	const setCheckedAndReturnNewArray = (nodes, checkedIds) => {
		return nodes.map(node => {
			let newNode = { ...node };
			newNode.checked = checkedIds.includes(newNode.id);

			if (newNode.childs && Array.isArray(newNode.childs)) {
				newNode.childs = setCheckedAndReturnNewArray(newNode.childs, checkedIds);
			}

			return newNode;
		});
	}




	// 是否存在元素
	const findValue = (value) => {
		let isBrother = false;
		for (let i = 0; i < choose_permission.value.length; i++) {
			if (choose_permission.value[i] === value) {
				isBrother = true;
			}
		}
		return isBrother;
	}

	// 删除选择的元素
	const delValue = (value) => {
		for (let i = 0; i < choose_permission.value.length; i++) {
			if (choose_permission.value[i] == value) {
				choose_permission.value.splice(i, 1);
				break;
			}
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .ant-checkbox-group {
		display: block;
		border: none !important;
	}

	.a-row:first-child {
		border-bottom: none;
		// border-radius: 10px 10px 0 0;
	}

	.a-row:last-child {
		// border-radius: 0 0 10px 10px;
	}

	.a-row {
		padding: 6px;
		border: 1px #f0f0f0 solid;

		.a-col:first-child {}
	}

	.a-col {
		padding: 10px;
		// padding-top: 6px;
	}
</style>