<script lang="ts" setup>
/**
 * @Name: CreateDialog.vue
 * @Description: 属性枚举-创建对话框
 * @Author: xinyan
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { Close, Finished } from '@element-plus/icons-vue';

const props = defineProps({
	rowData: Object,
});

const { rowData } = props;
const loading = ref(false);
const createDialog = <Ref>useTemplateRef('createDialog');
const createOpen = defineModel({ default: false });

const emit = defineEmits(['refresh']);

interface RuleForm {
	label: any;
	value: any;
	status: boolean;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
	label: '',
	value: '',
	status: true,
});

const rules = reactive<FormRules<RuleForm>>({
	label: [{ required: true, message: '请输入名称', trigger: 'blur' }],
	value: [{ required: true, message: '请输入数据值', trigger: 'blur' }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			const body = {
				attr:rowData.id,
				label: ruleForm.label,
				value: ruleForm.value,
				status: ruleForm.status,
			};
			const res = await useResponse(api.createEnum, body, loading);
			if (res.code === 2000) {
				ElMessage.success('创建成功');
				createOpen.value = false;
				emit('refresh');
			}
		} else {
			// createOpen.value = false;
			ElMessage.error('创建失败，请检查表单');
		}
	});
};

function cancelDialog() {
	resetForm(ruleFormRef.value);
	createDialog.value.visible = false;
}

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
};
</script>

<template>
	<el-dialog
		ref="createDialog"
		v-model="createOpen"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		:title="`属性枚举 - 创建 `"
		style="width: 30%"
	>
		<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="mx-2.5 mt-5" label-width="auto" status-icon>
			<el-form-item class="font-medium" label="名称" prop="label">
				<el-input v-model="ruleForm.label" placeholder="请输入名称" style="width: 328px" />
			</el-form-item>
			<el-form-item class="font-medium" label="数据值" prop="value">
				<el-input v-model="ruleForm.value" placeholder="请输入数据值" style="width: 328px" />
			</el-form-item>
			<el-form-item class="font-medium" label="状态" prop="value">
				<el-radio-group v-model="ruleForm.status">
					<el-radio :label="true">启用</el-radio>
					<el-radio :label="false">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button :icon="Close" @click="cancelDialog">取 消</el-button>
			<el-button :icon="Finished" :loading="loading" type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
		</template>
	</el-dialog>
</template>

<style scoped></style>
