<template>
		<el-dialog title="新增区域" v-model="state.dialogVisible" width="769px" draggable @close="close">
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="区域名称" prop="areaName" :rules="[{ required: true, message: '请填写区域名称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.areaName" 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="areaNameAbbreviation" :rules="[{ required: true, message: '请填写区域简称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.areaNameAbbreviation" placeholder="请填写区域简称" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="上级区域" prop="parentId" :rules="[{ required: false, message: '请选择上级区域', trigger: 'change' }]">
							<el-cascader
								:options="state.areaData"
								filterable
								:props="{ checkStrictly: true, value: 'id', label: 'areaName', emitPath: false }"
								placeholder="请选择上级区域"
								clearable
								class="w100"
								v-model="state.ruleForm.parentId"
							>
							</el-cascader>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
				</span>
			</template>
		</el-dialog>
</template>

<script setup lang="ts" name="systemAddArea">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import {treeAreaAdd} from '@/api/auxiliary/area';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
    areaName: '', // 部门名称
    areaNameAbbreviation: '', // 部门编码
		parentId: '', // 上级区域id
	},
	loading: false, // 确定按钮loading
  areaData:[]
});
// 打开弹窗
const openDialog = async (areaData: any) => {
	state.areaData = areaData ?? [];
	state.dialogVisible = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
  ruleFormRef.value?.clearValidate();
  ruleFormRef.value?.resetFields();
};
// 新增
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
    treeAreaAdd(state.ruleForm)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
        emit('updateList');
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
