<template>
    <el-dialog
        v-model="visible"
        :title="form.code ? '编辑文章' : '新建文章'"
        width="1000px"
        destroy-on-close
        @closed="handleClose"
        top="5vh"
        class="article-dialog"
    >
        <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>

            <div class="sub-article-section">
                <div class="sub-article-header">
                    <h3>副文章列表</h3>
                    <el-button
                        type="primary"
                        size="small"
                        @click="addSubArticle"
                        v-if="form.type == 2"
                        >添加副文章</el-button
                    >
                </div>

                <div
                    v-for="(subArticle, index) in form.subArticleList"
                    :key="index"
                    class="sub-article-item"
                >
                    <div class="sub-article-header">
                        <h4>副文章 #{{ index + 1 }}</h4>
                        <el-button
                            type="danger"
                            size="small"
                            circle
                            @click="removeSubArticle(index)"
                            :icon="Delete"
                            v-if="form.type == 2"
                        />
                    </div>

                    <el-form-item
                        :label="'副标题'"
                        :prop="'subArticleList.' + index + '.subTitle'"
                        :rules="{
                            required: true,
                            message: '请输入副标题',
                            trigger: 'blur'
                        }"
                    >
                        <el-input
                            v-model="subArticle.subTitle"
                            placeholder="请输入副标题"
                        />
                    </el-form-item>

                    <el-form-item
                        :label="'副内容'"
                        :prop="'subArticleList.' + index + '.subContent'"
                        :rules="{
                            required: true,
                            message: '请输入副内容',
                            trigger: 'blur'
                        }"
                    >
                        <TinymceEditor
                            v-model="subArticle.subContent"
                            :height="300"
                            placeholder="请输入副内容"
                        />
                    </el-form-item>
                </div>

                <div
                    v-if="form.subArticleList.length === 0"
                    class="empty-sub-articles"
                >
                    <el-empty description="暂无副文章，请点击添加按钮创建" />
                </div>
            </div>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref, reactive, defineEmits, watch } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import { Delete } from '@element-plus/icons-vue';
    import request from '@/utils/request';
    import TinymceEditor from '@/components/TinymceEditor/index.vue';

    // Remove the props for modelValue and articleData
    const emit = defineEmits(['success']);

    // 表单引用
    const formRef = ref(null);

    // 可见性
    const visible = ref(false);

    // 表单数据
    const form = reactive({
        type: '1',
        code: '',
        title: '',
        subArticleList: []
    });

    // 表单验证规则
    const rules = {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }]
    };

    // 添加副文章
    function addSubArticle() {
        form.subArticleList.push({
            subTitle: '',
            subContent: ''
        });
    }

    // 删除副文章
    function removeSubArticle(index) {
        form.subArticleList.splice(index, 1);
    }

    // 提交表单
    function submitForm() {
        formRef.value?.validate((valid) => {
            if (valid) {
                const method = form.code ? 'update' : 'add';
                let params = JSON.parse(JSON.stringify(form));
                delete params.type;
                request
                    .post(`/sys/articleInfo/${method}`, params)
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success(
                                method === 'update' ? '更新成功' : '添加成功'
                            );
                            visible.value = false;
                            emit('success');
                        } else {
                            EleMessage.error(res.data.msg || '操作失败');
                        }
                    });
            }
        });
    }

    // 关闭时重置表单
    function handleClose() {
        formRef.value?.resetFields();
        Object.assign(form, {
            code: '',
            title: '',
            subArticleList: []
        });
    }

    // 添加对外暴露的 handleOpen 方法
    function handleOpen(articleData = {}) {
        // 设置表单数据
        form.code = articleData.code || '';
        form.title = articleData.title || '';
        form.type = articleData.type || '1';
        form.subArticleList = articleData.subArticleList?.length
            ? [...articleData.subArticleList]
            : [];

        // 如果是新建模式且没有副文章，添加一个空的副文章
        if (!form.code && !form.subArticleList.length) {
            addSubArticle();
        }

        // 打开弹窗
        visible.value = true;
    }

    // 暴露方法供外部调用
    defineExpose({
        handleOpen
    });
</script>

<style lang="scss">
    .article-dialog {
        :deep(.el-dialog__body) {
            max-height: 70vh;
            overflow-y: auto;
        }
    }

    .sub-article-section {
        margin-top: 20px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 15px;
    }

    .sub-article-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }

    .sub-article-item {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px dashed #e4e7ed;
        border-radius: 4px;
        background-color: #f8f9fa;
    }

    .empty-sub-articles {
        margin: 30px 0;
    }
</style>
