<template>
	<div class="system-edit-menu-container">
		<el-dialog title="修改部门" v-model="state.isShowDialog" width="769px" draggable>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="部门名称" prop="orgName" :rules="[{ required: true, message: '请输入部门名称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.orgName" placeholder="请输入部门名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="上级部门" prop="parentId" :rules="[{ required: true, message: '请选择上级部门', trigger: 'change' }]">
							<el-cascader
								:options="state.orgData"
								filterable
								:props="{ checkStrictly: true, value: 'id', label: 'orgName', emitPath: false }"
								placeholder="请选择上级部门"
								clearable
								class="w100"
								v-model="state.ruleForm.parentId"
								ref="cascaderRef"
								@change="getselKnowledgeList"
							>
								<template #default="{ node, data }">
									<span>{{ data.orgName }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="是否启用" prop="name" :rules="[{ required: false, message: '请输入角色状态', trigger: 'blur' }]">
							<el-switch v-model="state.ruleForm.isEnable" inline-prompt active-text="启" inactive-text="禁"></el-switch>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" v-waves="'light'" :loading="state.loading">修 改 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemEditOrg">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { updateOrg, getOrgById } from '/@/api/system/organize';

// 定义接口来定义对象的类型
interface OrgFormState {
	isShowDialog: boolean;
	ruleForm: {
		orgName: string;
		orgCode: string;
		parentId: string;
		parentName: string;
		isEnable: boolean;
		children: Array<any>;
	};
	orgData: Array<any>;
	loading: boolean;
}

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

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<OrgFormState>({
	isShowDialog: false,
	ruleForm: {
		orgName: '',
		orgCode: '',
		parentId: '',
		parentName: '',
		isEnable: true,
		children: [],
	},
	orgData: [], // 上级部门数据
	loading: false,
});
// 格式化数据  排除自己
const formatData = (arr: Array<any>, id: string) => {
	if (!arr) return [];
	arr.forEach((v: any, i: number) => {
		if (v.id === id) arr.splice(i, 1);
		if (v.children && v.children.length) {
			formatData(v.children, id);
		}
	});
	return arr;
};
// 打开弹窗
const openDialog = async (row: any, orgData: any) => {
	if (!auth('100503')) ElMessage.warning('抱歉，您没有获取部门详情的权限！');
	else {
		ruleFormRef.value?.resetFields();
		try {
			state.orgData = JSON.parse(JSON.stringify(orgData));
			state.orgData = formatData(state.orgData, row.id);
			const res: any = await getOrgById(row.id);
			state.ruleForm = res.result;
			state.isShowDialog = true;
		} catch (error) {
			console.log(error);
		}
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
const cascaderRef = ref();
// 获取选择name值
const getselKnowledgeList = () => {
	let currentNode = cascaderRef.value.getCheckedNodes();
	state.ruleForm.parentName = currentNode[0]?.label ?? '';
};
// 修改
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			updateOrg(state.ruleForm).then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('修改成功');
			});
		} else {
			console.log('error submit!', fields);
		}
	});
	// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
