<template>
    <el-dialog
        v-model="dialogFormVisible"
        align-center
        :title="title"
        width="500px"
        @close="close"
    >
        <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
            <el-form-item label="标题" prop="title">
                <el-input v-model.trim="form.title" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
                <el-input v-model.trim="form.author" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
        </template>
    </el-dialog>
</template>

<script>
    import { doEdit } from '@/api/table'

    export default defineComponent({
        name: 'TableEdit',
        emits: ['fetch-data'],
        setup(props, { emit }) {
            const $baseMessage = inject('$baseMessage')

            const state = reactive({
                formRef: null,
                form: {
                    title: '',
                    author: '',
                },
                rules: {
                    title: [
                        {
                            required: true,
                            trigger: 'blur',
                            message: '请输入标题',
                        },
                    ],
                    author: [
                        {
                            required: true,
                            trigger: 'blur',
                            message: '请输入作者',
                        },
                    ],
                },
                title: '',
                dialogFormVisible: false,
            })

            const showEdit = (row) => {
                if (!row) {
                    state.title = '添加'
                } else {
                    state.title = '编辑'
                    state.form = JSON.parse(JSON.stringify(row))
                }
                state.dialogFormVisible = true
            }
            const close = () => {
                state['formRef'].resetFields()
                state.form = {
                    title: '',
                    author: '',
                }
                state.dialogFormVisible = false
            }
            const save = () => {
                state['formRef'].validate(async (valid) => {
                    if (valid) {
                        const { msg } = await doEdit(state.form)
                        $baseMessage(msg, 'success', 'vab-hey-message-success')
                        emit('fetch-data')
                        close()
                    }
                })
            }

            return {
                ...toRefs(state),
                showEdit,
                close,
                save,
            }
        },
    })
</script>
