<template>
    <el-dialog v-model="dialogVisible" :before-close="handleClose" :title="title" style="width: 700px; padding-bottom: 20px">
        <div class="global_dialog_content">
            <el-form ref="FormDataRef" :model="form.data" :rules="form.rules" label-width="100">
                <el-form-item label="岗位名称" prop="name">
                    <el-input v-model="form.data.name" placeholder="请输入岗位名称" style="width: 320px" />
                </el-form-item>
                <el-form-item label="岗位描述" prop="description">
                    <el-input maxlength="100" v-model="form.data.description" placeholder="请输入岗位描述" style="width: 320px" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button :loading="submitting" type="primary" @click="onClickSave">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { sysPositionSave } from '~/api/sys.js';

const dialogVisible = ref(false);
const FormDataRef = ref(null);
const submitting = ref(false);
const title = ref('');
const userId = ref('');

const emits = defineEmits();
const form = reactive({
    data: {
        name: '',
        description: '',
        type: '',
    },
    rules: {
        name: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '岗位描述不能为空', trigger: 'blur' }],
    },
});

const onShowDialog = (val, page) => {
    title.value = !val ? '新增岗位' : '编辑岗位';
    dialogVisible.value = true;
    if (val) {
        userId.value = val.id;
        form.data = val;
    }
};

const onClickSave = () => {
    FormDataRef.value.validate((valid) => {
        if (valid) {
            submitting.value = true;
            const params = { ...form.data };
            if (!userId.value) {
                params.id = userId.value;
            }
            sysPositionSave(params)
                .then(() => {
                    ElMessage.success('操作成功');
                    handleClose();
                    emits('success');
                    submitting.value = false;
                })
                .catch(() => {
                    submitting.value = false;
                });
        }
    });
};

const handleClose = () => {
    form.data = {};
    dialogVisible.value = false;
    if (FormDataRef.value) {
        FormDataRef.value.clearValidate();
    }
};
defineExpose({
    onShowDialog,
});
</script>
<style lang="scss" scoped></style>
