<template>
	<el-dialog
		:title="type == 'ip' ? '添加IP分组' : '添加域名分组'"
		width="600"
		v-model="props.open"
		:close-on-click-modal="false"
		:destroy-on-close="true"
		@close="onCancel"
		draggable
	>
		<el-form ref="menuDialogFormRef" :rules="dataRules" :model="state.ruleForm" v-loading="loading">
			<el-form-item :label="t('marketingConfig.groupingName')" prop="groupName">
				<el-input v-model="state.ruleForm.groupName" type="text" :placeholder="t('marketingConfig.groupingNameTip')"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel">{{ t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup name="systemMenuDialog">
import { useI18n } from 'vue-i18n';
import { addGroup } from '/@/api/marketing/config';
import { useMessage } from '/@/hooks/message';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['update:open', 'onsuccess']);
const { t } = useI18n();

// 定义变量内容
const loading = ref(false);
const menuDialogFormRef = ref();

// 定义需要的数据
const state = reactive({
	ruleForm: {
		groupName: '',
	},
});

const props = defineProps({
	open: {
		type: Boolean,
		default: false,
	},
	type: {
		type: String,
		default: 'ip', // 'ip' or 'domain'
	},
});
// // 表单校验规则
const dataRules = reactive({
	groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
});
const onCancel = () => {
	emit('update:open', false);
};
// 保存数据
const onSubmit = async () => {
	try {
		await menuDialogFormRef.value.validateField('groupName');
	} catch {
		return;
	}
	try {
		loading.value = true;
		await addGroup({
			...state.ruleForm,
			groupType: props.type === 'ip' ? 1 : 2,
		});
		useMessage().success(t('common.addSuccessText'));
		emit('onsuccess');
		onCancel();
	} catch (err) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
watch(
	() => props.open,
	(val) => {
		if (val) {
			state.ruleForm = {
				groupName: '',
				groupType: '',
				groupDesc: '',
				groupStatus: '',
			};
		}
	}
);
</script>
<style>
.apps-loadmore.el-select-dropdown .el-scrollbar__wrap {
	height: 330px !important;
}
</style>