<!-- 红包码活动列表 -->
<template>
    <div class="red-bag-activity">
        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns" :tools="false"
            :body-style="{ padding: '10px 0' }">
            <template #toolbar>
                <div style="display: flex; align-items: center; gap: 10px">
                    <el-select v-model="activityStatus" placeholder="活动状态" clearable style="width: 250px">
                        <!-- 0-未开始 1-进行中 2-已结束 -->
                        <el-option label="未开始" :value="0" />
                        <el-option label="进行中" :value="1" />
                        <el-option label="已结束" :value="2" />
                    </el-select>
                    <el-button type="primary" @click="reload()">查询</el-button>
                    <el-button type="primary" plain @click="reset">重置</el-button>
                    <el-button type="primary" :icon="PlusOutlined" @click="handleAdd()"
                        v-permission="'marketing:redBag:add'">
                        新增
                    </el-button>
                </div>
            </template>

            <template #activityStatus="{ row }">
                <el-tag :type="row.activityStatus === 1 ? 'success' : 'info'">
                    {{ activityStatusMap[row.activityStatus] }}
                </el-tag>
            </template>

            <template #action="{ row }">
                <el-button link type="primary" v-permission="'marketing:redBag:detail'" @click="handleDetail(row)">
                    [查看数据]
                </el-button>
                <el-button v-if="row.activityStatus === 1" link type="danger" v-permission="'marketing:redBag:end'"
                    @click="handleEnd(row)">
                    [结束活动]
                </el-button>
                <el-button link type="primary" v-permission="'marketing:redBag:download'" @click="handleDownload(row)">
                    [下载文件]
                </el-button>
            </template>
        </common-table>

        <!-- 新增红包活动弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增红包活动" width="500px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
                <el-form-item label="红包码名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入红包码名称" />
                </el-form-item>
                <el-form-item label="红包码数量" prop="redNum">
                    <el-input-number v-model="formData.redNum" :min="1" :max="999999" placeholder="请输入红包码数量"
                        style="width: 100%" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                    确定
                </el-button>
            </template>
        </el-dialog>

        <red-bag-detail ref="detailRef" />
    </div>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import { ElMessage, ElMessageBox } from 'element-plus';
    import { PlusOutlined } from '@/components/icons';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import RedBagDetail from './red-bag-detail.vue';
    import request from '@/utils/request';

    defineOptions({ name: 'RedBagActivity' });

    const activityStatus = ref();
    const reset = () => {
        activityStatus.value = undefined;
        reload();
    };

    // 活动状态映射
    const activityStatusMap = {
        0: '未开始',
        1: '进行中',
        2: '已结束'
    };

    // 表格列配置
    const columns = ref([
        {
            label: '红包码名称',
            prop: 'name',
            align: 'center',
            minWidth: 180
        },
        {
            label: '创建日期',
            prop: 'createTime',
            align: 'center',
            minWidth: 160
        },
        {
            label: '活动状态',
            prop: 'activityStatus',
            align: 'center',
            slot: 'activityStatus',
            minWidth: 100
        },
        {
            label: '红包码数量',
            prop: 'redNum',
            align: 'center',
            minWidth: 120
        },
        {
            label: '扫码次数',
            prop: 'scanNum',
            align: 'center',
            minWidth: 100
        },
        {
            label: '扫码人数',
            prop: 'scanUserNum',
            align: 'center',
            minWidth: 100
        },
        {
            label: '累计扫码红包金额',
            prop: 'scillSumNum',
            align: 'center',
            minWidth: 150
        },
        {
            label: '累计现金红包金额',
            prop: 'cashSumNum',
            align: 'center',
            minWidth: 150
        },
        {
            label: '人均红包金额',
            prop: 'userAvgNum',
            align: 'center',
            minWidth: 120
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 270,
            align: 'center',
            slot: 'action',
            fixed: 'right'
        }
    ]);

    // 页面配置
    const pageRef = ref(null);
    const pageConfig = reactive({
        pageUrl: '/activity/red/bag/activity/redBag/pagelist',
        fileName: '红包码活动',
        cacheKey: 'redBagActivityTable'
    });

    // 刷新表格
    function reload() {
        pageRef.value?.reload({ activityStatus: activityStatus.value });
    }

    // 新增红包活动相关
    const dialogVisible = ref(false);
    const submitLoading = ref(false);
    const formRef = ref(null);
    const formData = ref({
        name: '',
        redNum: null
    });

    const formRules = {
        name: [
            { required: true, message: '请输入红包码名称', trigger: 'blur' }
        ],
        redNum: [
            { required: true, message: '请输入红包码数量', trigger: 'blur' }
        ]
    };

    const handleAdd = () => {
        formData.value = {
            name: '',
            redNum: null
        };
        dialogVisible.value = true;
    };

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

            submitLoading.value = true;
            try {
                const res = await request.post(
                    '/activity/red/bag/activity/redBag/add',
                    formData.value
                );
                if (res.data.code === 200) {
                    ElMessage.success('新增成功');
                    dialogVisible.value = false;
                    reload();
                } else {
                    ElMessage.error(res.data.msg || '新增失败');
                }
            } catch (error) {
                ElMessage.error('新增失败');
            } finally {
                submitLoading.value = false;
            }
        });
    };

    // 结束活动
    const handleEnd = (row) => {
        ElMessageBox.confirm('确认结束该活动吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            try {
                const res = await request.post(
                    '/activity/red/bag/activity/redBag/end',
                    {
                        id: row.id
                    }
                );
                if (res.data.code === 200) {
                    ElMessage.success('已结束活动');
                    reload();
                } else {
                    ElMessage.error(res.data.msg || '结束活动失败');
                }
            } catch (error) {
                ElMessage.error('结束活动失败');
            }
        });
    };

    // 下载文件
    const handleDownload = async (row) => {
        request({
            url: '/activity/red/bag/detail/activity/redBag/detail/download',
            method: 'POST',
            data: { activityId: row.id },
        }).then(res => {
            console.log(res, 'xxx')
            if (res.data.code == 200) {
                ElMessage.success(res.data.data)
            } else {
                ElMessage.error(res.data.msg)
            }
        })
    };

    // 查看详情
    const detailRef = ref(null);

    const handleDetail = (row) => {
        detailRef.value?.open(row);
    };
</script>

<style lang="scss" scoped>
    .red-bag-activity {
        padding: 0;
    }
</style>
