<template>
    <ElDialog
        v-model="show"
        :title="title"
        :class="{ '!w-10/12': !width, 'max-w-3xl': !width }"
        :close-on-click-modal="!saving"
        :close-on-press-escape="!saving"
        :width="width"
    >
        <ElForm :model="model" :rules="rules" ref="formEl" label-position="right" :label-width="labelWidth">
            <slot></slot>
        </ElForm>
        <div class="text-right">
            <ElButton @click="show = false" :disabled="saving">取消</ElButton>
            <ElButton type="primary" @click="onSave" :loading="saving">保存</ElButton>
        </div>
    </ElDialog>
</template>
<script setup>
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: '编辑'
    },
    model: {
        type: Object,
        default: () => ({})
    },
    rules: {
        type: Object,
        default: () => ({})
    },
    onSubmit: {
        type: Function,
        default: () => {}
    },
    labelWidth: {
        type: String,
        default: '80px'
    },
    width: {
        type: String
    }
})
const emit = defineEmits(['update:modelValue', 'success', 'error'])
const show = computed({
    get() {
        return props.modelValue
    },
    set(modelValue) {
        emit('update:modelValue', modelValue)
    }
})

const formEl = ref(null)
const saving = ref(false)
async function onSave() {
    try {
        try {
            await formEl.value.validate()
        } catch (e) {
            return
        }
        saving.value = true
        await props.onSubmit()
        saving.value = false
        show.value = false
        emit('success')
    } catch (e) {
        saving.value = false
        if (e.message) {
            if (typeof e.message === 'string') {
                ElMessage.error(e.message)
            } else {
                ElMessage.error(JSON.stringify(e.message))
            }
        } else {
            ElMessage.error('保存失败')
        }
        emit('error', e)
    }
}
watch(
    () => props.modelValue,
    (modelValue) => {
        if (modelValue && formEl.value) {
            formEl.value.clearValidate()
        }
    }
)
</script>
