<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>

                    <div style="display: flex; align-items: center; gap: 10px">
                        <el-input
                            v-model="search"
                            placeholder="请输入弹窗名称"
                            style="width: 300px"
                        />
                        <el-select
                            v-model="deliveryPage"
                            placeholder="请选择投放页面"
                            clearable
                            style="width: 300px"
                        >
                            <el-option label="首页" value="1" />
                            <el-option label="订单完成页" value="2" />
                            <!-- 可以根据实际需求添加更多选项 -->
                        </el-select>
                        <el-button
                            type="primary"
                            @click="reload()"
                            style="width: 90px"
                            >查询</el-button
                        >
                        <el-button
                            type="primary"
                            plain
                            @click="reset"
                            style="width: 90px"
                            >重置</el-button
                        >
                    </div>
                </div>
            </template>

            <template #status="{ row }">
                <el-tag :type="row.status === '进行中' ? 'success' : 'info'">
                    {{ row.status }}
                </el-tag>
            </template>

            <template #afterCloseType="{ row }">
                <div class="flex flex-col">
                    <el-text v-if="row.userClose == 1">用户手动关闭</el-text>
                    <el-text v-if="row.autoClose == 1"
                        >显示{{ row.autoCloseTime }}秒后自动关闭</el-text
                    >
                </div>
            </template>

            <template #frequency="{ row }">
                <div>
                    <el-text v-if="row.frequency == 1"
                        >首次访问时出现，之后不出现</el-text
                    >
                    <el-text v-if="row.frequency == 2"
                        >间隔{{ row.frequencyTime }}小时后再次出现</el-text
                    >
                    <el-text v-if="row.frequency == 3">常驻</el-text>
                </div>
            </template>

            <template #time="{ row }">
                <div>
                    <div>起:{{ row.startTime }}</div>
                    <div>止:{{ row.endTime }}</div>
                </div>
            </template>

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

                    <el-button
                        type="danger"
                        link
                        @click="handleDelete(row)"
                        v-permission="'marketing:dialog:delete'"
                    >
                        [删除]
                    </el-button>
                </div>
            </template>
        </common-table>

        <!-- 弹窗编辑组件 -->
        <dialog-edit ref="dialogEditRef" @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 DialogEdit from './components/DialogEdit.vue';
    import request from '@/utils/request';

    const search = ref('');
    const deliveryPage = ref('');

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

    defineOptions({ name: 'DialogManage' });

    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '名称',
            prop: 'name',
            align: 'center',
            minWidth: 120
        },
        {
            label: '跳转页面',
            prop: 'jumpPage',
            align: 'center',
            minWidth: 200
        },
        {
            label: '投放端',
            prop: 'plat',
            align: 'center',
            minWidth: 100
        },
        {
            label: '投放页面',
            prop: 'deliveryPage',
            align: 'center',
            minWidth: 100
        },
        {
            label: '弹窗关闭设置',
            prop: 'autoClose',
            align: 'center',
            minWidth: 140,
            slot: 'afterCloseType'
        },
        {
            label: '出现频次',
            prop: 'frequency',
            align: 'center',
            minWidth: 150,
            slot: 'frequency'
        },
        {
            label: '状态',
            prop: 'status',
            align: 'center',
            minWidth: 100
        },
        {
            label: '起止时间',
            prop: 'time',
            align: 'center',
            minWidth: 180,
            slot: 'time'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 160,
            align: 'center',
            slot: 'action'
        }
    ]);

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

    const pageConfig = reactive({
        pageUrl: '/sys/dialogInfo/pagelist',
        fileName: '弹窗管理',
        cacheKey: 'dialogManageTable'
    });

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

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

    // 编辑/新建弹窗
    function handleUpdate(row) {
        if (row?.id) {
            // 编辑模式，获取弹窗详情
            request.get(`/sys/dialogInfo/getInfo/${row.id}`).then((res) => {
                if (res.data.code === 200) {
                    const data = res.data.data;
                    dialogEditRef.value.handleOpen(data);
                } else {
                    EleMessage.error(res.data.msg || '获取弹窗详情失败');
                }
            });
        } else {
            // 新建模式
            dialogEditRef.value.handleOpen();
        }
    }

    // 删除弹窗
    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(() => {
            // 根据API格式，使用正确的删除接口
            request
                .post('/sys/dialogInfo/delete', { idList: ids })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success('删除成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg);
                    }
                });
        });
    }

    // 处理弹窗状态更新
    function handleStatusUpdate(row) {
        const newStatus = row.status === '进行中' ? '已结束' : '进行中';
        const statusValue = newStatus === '进行中' ? 1 : 0;

        ElMessageBox.confirm(
            `确认${newStatus === '进行中' ? '启用' : '停用'}该弹窗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            request
                .post('/sys/dialogInfo/updateStatus', {
                    id: row.id,
                    status: statusValue
                })
                .then((res) => {
                    if (res.data.code === 200) {
                        EleMessage.success(
                            `${newStatus === '进行中' ? '启用' : '停用'}成功`
                        );
                        reload();
                    } else {
                        EleMessage.error(res.data.msg || '操作失败');
                    }
                });
        });
    }
</script>

<style scoped>
    /* 可以根据需要添加样式 */
</style>
