<template>
    <ele-page flex-table>
        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns">
            <template #toolbar>
                <div style="display: flex; align-items: center; gap: 10px">
                    <!-- <el-button
            type="primary"
            plain
            :icon="PlusOutlined"
            @click="handleUpdate()"
          >
            新建文章
          </el-button> -->
                    <!-- <el-button
            type="danger"
            plain
            :icon="DeleteOutlined"
            @click="handleDelete()"
          >
            删除
          </el-button> -->

                    <div style="display: flex; align-items: center; gap: 10px">
                        <el-input
                            v-model="search"
                            placeholder="请输入文章名称"
                            style="width: 300px"
                        />
                        <el-button type="primary" @click="reload()"
                            >查询</el-button
                        >
                        <el-button type="primary" plain @click="reset"
                            >重置</el-button
                        >
                    </div>
                </div>
            </template>

            <template #status="{ row }">
                <el-switch
                    :model-value="row.status === '1'"
                    style="--el-switch-on-color: #13ce66"
                    @change="statusSwitchChange($event, row)"
                />
                <el-text style="margin-left: 5px">{{
                    row.status === '1' ? '已开启' : '已关闭'
                }}</el-text>
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="primary"
                        link
                        @click="handleUpdate(row)"
                        v-permission="'marketing:article:edit'"
                    >
                        [编辑]
                    </el-button>
                </div>
            </template>
        </common-table>

        <!-- 使用文章编辑弹窗组件 -->
        <article-dialog ref="articleDialogRef" @success="handleDialogSuccess" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { ElMessageBox } from 'element-plus/es';
    import { EleMessage } from 'ele-admin-plus/es';
    import { PlusOutlined, DeleteOutlined } from '@/components/icons';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import ArticleDialog from './components/ArticleDialog.vue';
    import request from '@/utils/request';

    const search = ref('');
    const reset = () => {
        search.value = '';
        reload();
    };

    defineOptions({ name: 'ArticleManage' });

    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '文章名称',
            prop: 'title',
            align: 'center',
            minWidth: 140
        },
        {
            label: '字数',
            prop: 'wordNum',
            align: 'center'
        },
        // {
        //   label: '添加时间',
        //   prop: 'createTime',
        //   align: 'center',
        // },
        {
            label: '状态',
            prop: 'status',
            align: 'center',
            slot: 'status'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 160,
            align: 'center',
            slot: 'action'
        }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/sys/articleInfo/list',
        fileName: '文章管理',
        cacheKey: 'articleManageTable'
    });

    //刷新表格
    function reload(where) {
        pageRef.value?.reload({ ...where, title: search.value });
    }

    //修改状态
    const statusSwitchChange = (value, row) => {
        let message = value ? '确认开启？' : '确认关闭？';
        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '关闭',
            type: 'warning'
        })
            .then(() => {
                const status = value ? '1' : '0';
                request
                    .post('/sys/articleInfo/updateStatus', {
                        code: row.code,
                        status: status
                    })
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('操作成功');
                            reload();
                        } else {
                            EleMessage.error(res.data.msg);
                        }
                    });
            })
            .catch(() => {
                row.status = value ? '0' : '1';
            });
    };

    //删除
    function handleDelete(row) {
        let ids = [];
        let message = '确认删除该文章？';

        if (row?.id) {
            // 单个删除
            ids = [row.id];
        } else {
            // 批量删除
            const selections = pageRef.value?.getSelections();
            if (!selections || selections.length === 0) {
                EleMessage.warning('请选择要删除的数据');
                return;
            }
            ids = selections.map((item) => item.id);
            message = `确认删除选中的 ${ids.length} 条数据？`;
        }

        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            request
                .post('/sys/articleInfo/delete', { idList: ids })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success('删除成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg);
                    }
                });
        });
    }

    // 文章编辑相关
    const articleDialogRef = ref(null);

    // 处理弹窗成功提交的事件
    function handleDialogSuccess() {
        reload();
    }

    //编辑页面
    function handleUpdate(row) {
        // 如果是编辑模式，获取文章详情
        if (row?.code) {
            request.get(`/sys/articleInfo/getInfo/${row.code}`).then((res) => {
                if (res.data.code === 200) {
                    articleDialogRef.value.handleOpen(res.data.data);
                } else {
                    EleMessage.error(res.data.msg || '获取文章详情失败');
                }
            });
        } else {
            // 新建模式
            articleDialogRef.value.handleOpen({
                code: '',
                title: '',
                subArticleList: []
            });
        }
    }
</script>

<style scoped>
    /* 样式已移至组件内 */
</style>
