<template>
    <ele-modal
        :width="500"
        v-model="visible"
        title="我要留言"
        :body-style="{ padding: '20px 30px' }"
    >
        <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item prop="content">
                <el-input
                    v-model="form.content"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入留言内容，限200字以内"
                    maxlength="200"
                    show-word-limit
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="flex justify-end gap-3">
                <el-button @click="visible = false">取消</el-button>
                <el-button
                    type="primary"
                    :loading="loading"
                    @click="handleSubmit"
                    >确认提交</el-button
                >
            </div>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import request from '@/utils/request';

    const visible = ref(false);
    const loading = ref(false);
    const formRef = ref(null);

    const form = reactive({
        refundOrderId: '',
        content: ''
    });

    const rules = {
        content: [
            { required: true, message: '请输入留言内容', trigger: 'blur' },
            { max: 200, message: '长度不能超过200个字符', trigger: 'blur' }
        ]
    };

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

    const open = (refundOrderId) => {
        form.refundOrderId = refundOrderId;
        form.content = '';
        visible.value = true;
        // 清除上次的校验状态
        if (formRef.value) {
            formRef.value.clearValidate();
        }
    };

    const handleSubmit = async () => {
        if (!formRef.value) return;

        await formRef.value.validate((valid) => {
            if (valid) {
                loading.value = true;
                request
                    .post('/shop/shopOrder/refundAddDisposeContent', {
                        refundOrderId: form.refundOrderId,
                        content: form.content
                    })
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('留言成功');
                            visible.value = false;
                            emit('success');
                        } else {
                            EleMessage.error(res.data.msg || '留言失败');
                        }
                    })
                    .catch((e) => {
                        console.error(e);
                        EleMessage.error('网络错误');
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            }
        });
    };

    defineExpose({
        open
    });
</script>
