<!-- 合伙人推广海报 -->
<template>
    <div class="partner-poster">
        <div class="search-bar" style="margin-bottom: 12px">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入模板名称"
                style="width: 300px"
            />

            <el-button
                style="width: 90px; margin-left: 14px"
                type="primary"
                @click="handleSearch"
                >查询</el-button
            >
            <el-button style="width: 90px" type="info" @click="reset"
                >重置</el-button
            >
        </div>

        <!-- 表格 -->
        <common-table
            ref="tableRef"
            :page-config="{
                cacheKey: 'partnerPosterTable',
                fileName: '合伙人推广海报',
                pageUrl: '/user/userPartnerPosterTemplate/pagelist'
            }"
            :flex-table="true"
            :body-style="{ padding: '0px' }"
            :columns="columns"
            @selection-change="handleSelectionChange"
        >
            <template #toolbar="{ row }">
                <el-button type="primary" @click="openEdit()">
                    <el-icon><Plus /></el-icon>添加模板
                </el-button>
                <el-button type="danger" @click="handleDelete()"
                    >删除</el-button
                >
            </template>

            <!-- 图片列 -->
            <template #image="{ row }">
                <el-image
                    :src="row.background"
                    fit="contain"
                    style="width: 80px; height: 80px"
                    :preview-src-list="[row.background]"
                    :initial-index="0"
                    preview-teleported
                />
            </template>

            <!-- 状态列 -->
            <template #status="{ row }">
                <el-switch
                    v-model="row.status"
                    style="--el-switch-on-color: #13ce66"
                    active-value="1"
                    inactive-value="2"
                    @change="statusSwitchChange($event, row)"
                />
                <el-text style="margin-left: 5px">{{
                    row.status == 2 ? '已停用' : '已开启'
                }}</el-text>
            </template>

            <!-- 操作列 -->
            <template #operation="{ row }">
                <el-button type="primary" link @click="openEdit(row)"
                    >编辑</el-button
                >
                <el-button type="danger" link @click="handleDelete(row)"
                    >删除</el-button
                >
            </template>
        </common-table>

        <!-- 编辑弹窗 -->
        <poster-edit ref="posterEditRef" @success="handleEditSuccess" />
    </div>
</template>

<script setup>
    import { ref } from 'vue';
    import { Plus } from '@element-plus/icons-vue';
    import { ElMessage, ElMessageBox } from 'element-plus';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import PosterEdit from './poster-edit.vue';
    import {
        deletePosterTemplate,
        updatePosterTemplateStatus
    } from '@/api/marketing/partner';

    // 搜索关键词
    const searchKeyword = ref('');

    // 表格实例
    const tableRef = ref();

    // 选中的行数据
    const selectedRows = ref([]);

    // 编辑弹窗实例
    const posterEditRef = ref();

    // 表格列配置
    const columns = [
        { type: 'selection', width: 70, align: 'center' },
        { prop: 'name', label: '模板名称' },
        { prop: 'background', label: '图片', slot: 'image', align: 'center' },
        { prop: 'createTime', label: '添加时间', align: 'center' },
        { prop: 'status', label: '状态', slot: 'status', align: 'center' },
        { label: '操作', slot: 'operation', width: 150, align: 'center' }
    ];

    // 打开编辑弹窗
    const openEdit = (row) => {
        posterEditRef.value?.open(row);
    };

    // 处理表格选择变化
    const handleSelectionChange = (selection) => {
        selectedRows.value = selection;
    };

    // 处理搜索
    const handleSearch = () => {
        tableRef.value?.reload({ name: searchKeyword.value });
    };

    // 重置
    const reset = () => {
        searchKeyword.value = '';
        handleSearch();
    };

    // 删除海报
    const handleDelete = (row) => {
        const rows = row ? [row] : selectedRows.value;
        if (!rows.length) {
            ElMessage.warning('请选择要删除的数据');
            return;
        }

        ElMessageBox.confirm(
            `确认删除选中的 ${rows.length} 条数据吗？`,
            '提示',
            {
                type: 'warning'
            }
        ).then(async () => {
            try {
                const ids = rows.map((item) => item.id);
                await deletePosterTemplate({ ids });
                ElMessage.success('删除成功');
                handleSearch();
            } catch (error) {
                ElMessage.error(error.message);
            }
        });
    };

    // 修改状态
    const statusSwitchChange = (value, row) => {
        // 保存原始状态值，用于取消时恢复
        const originalStatus = value === '1' ? '2' : '1';

        let message = value == '2' ? '确认停用？' : '确认开启？';
        ElMessageBox.confirm(message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '关闭',
            type: 'warning'
        })
            .then(() => {
                updatePosterTemplateStatus({
                    id: row.id,
                    status: value
                })
                    .then((res) => {
                        if (res.data.code === 200) {
                            ElMessage.success('操作成功');
                            handleSearch();
                        } else {
                            ElMessage.error(res.data.msg);
                            // 如果API调用失败，恢复原始状态
                            row.status = originalStatus;
                        }
                    })
                    .catch(() => {
                        // API调用异常时，恢复原始状态
                        row.status = originalStatus;
                        ElMessage.error('操作失败');
                    });
            })
            .catch(() => {
                // 用户点击"关闭"按钮，恢复原始状态
                row.status = originalStatus;
            });
    };

    // 编辑成功回调
    const handleEditSuccess = () => {
        handleSearch();
    };
</script>

<style lang="scss" scoped>
    .partner-poster {
        padding: 16px;
        background-color: #fff;

        .toolbar {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
        }

        :deep(.el-switch__label) {
            font-size: 12px;
            &.is-active {
                color: var(--el-color-primary);
            }
        }
    }
</style>
