<template>
    <ele-page flex-table>
        <div class="h-full bg-white p-5 rounded-lg">
            <!-- Top Stats -->
            <div class="grid grid-cols-3 gap-4 mb-4">
                <div
                    class="bg-[#eef9f5] p-6 rounded-lg relative overflow-hidden"
                >
                    <div class="flex justify-between items-start">
                        <div>
                            <div class="text-xl font-bold mb-2">普通红包</div>
                            <div class="text-gray-500 text-sm mb-4"
                                >所有商品通用</div
                            >
                            <div class="text-gray-600"
                                >已建数量：{{ count1 }}</div
                            >
                        </div>
                        <el-button
                            type="primary"
                            @click="handleCreate('1')"
                            :icon="Lightning"
                            >新建</el-button
                        >
                    </div>
                    <!-- Decorative Icon/Shape if needed -->
                </div>
                <div
                    class="bg-[#eef9f5] p-6 rounded-lg relative overflow-hidden"
                >
                    <div class="flex justify-between items-start">
                        <div>
                            <div class="text-xl font-bold mb-2">惊喜红包</div>
                            <div class="text-gray-500 text-sm mb-4"
                                >所有商品可用</div
                            >
                            <div class="text-gray-600"
                                >已建数量：{{ count2 }}</div
                            >
                        </div>
                        <el-button
                            type="primary"
                            @click="handleCreate('2')"
                            :icon="Lightning"
                            >新建
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- Tabs -->
            <el-tabs
                v-model="activeTab"
                @tab-click="handleTabClick"
                class="mb-2"
            >
                <el-tab-pane label="红包列表" :name="undefined" />
                <el-tab-pane label="惊喜红包" name="2" />
                <el-tab-pane label="普通红包" name="1" />
            </el-tabs>

            <!-- Table -->
            <common-table
                ref="tableRef"
                :columns="columns"
                :page-config="pageConfig"
                :bodyStyle="{ padding: 0 }"
            >
                <template #toolbar>
                    <div class="flex items-center space-x-4">
                        <el-input
                            v-model="searchForm.name"
                            placeholder="名称"
                            class="!w-[200px]"
                            clearable
                        />

                        <dict-data
                            code="red_packet_status"
                            v-model="searchForm.status"
                            placeholder="请选择活动状态"
                            class="!w-[200px]"
                        />
                        <el-button type="primary" @click="reload"
                            >搜索</el-button
                        >
                        <el-button @click="reset" style="margin-left: 10px"
                            >重置</el-button
                        >
                    </div>
                </template>

                <!-- Columns Slots -->
                <template #status="{ row }">
                    <dict-data
                        code="red_packet_status"
                        v-model="row.status"
                        type="tag"
                    />
                </template>

                <template #amount="{ row }">
                    <span v-if="row.type === 2 || row.type === '2'"
                        >{{ row.minMoney }}-{{ row.maxMoney }}元</span
                    >
                    <span v-else>{{ row.faceMoney }}元</span>
                </template>

                <template #threshold="{ row }">
                    <span v-if="!row.thresholdMoney || row.thresholdMoney === 0"
                        >无门槛</span
                    >
                    <span v-else>满{{ row.thresholdMoney }}可用</span>
                </template>

                <template #distribution="{ row }">
                    <div v-if="row.restNum !== undefined"
                        >已领 {{ (row.totalNum || 0) - row.restNum }}</div
                    >
                    <div v-else-if="row.sendNum !== undefined"
                        >已领 {{ row.sendNum }}</div
                    >
                    <div v-else>已领 -</div>
                    <div class="text-gray-400 text-xs"
                        >总数 {{ row.totalNum }}</div
                    >
                </template>

                <template #time="{ row }">
                    <div v-if="!row.effectDays || row.effectDays === 0">
                        <div>起：{{ row.effectStartTime }}</div>
                        <div>止：{{ row.effectEndTime }}</div>
                    </div>
                    <div v-else>
                        自领取之后{{ row.effectDays }}自然日之内有效
                    </div>
                </template>

                <template #action="{ row }">
                    <div class="flex flex-col space-y-1 text-xs">
                        <div class="flex space-x-2">
                            <el-button
                                type="primary"
                                link
                                @click="handleViewDetail(row)"
                                >查看详情</el-button
                            >
                            <el-button
                                type="warning"
                                link
                                @click="handleCopyData(row)"
                                >复制</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                @click="handleEdit(row)"
                                >修改</el-button
                            >
                        </div>
                        <div class="flex space-x-2">
                            <el-button
                                type="success"
                                link
                                @click="handleShowData(row)"
                                >数据</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                @click="handleOperationRecord(row)"
                                >操作记录</el-button
                            >
                            <el-button
                                v-if="row.status !== 'ended'"
                                type="danger"
                                link
                                @click="handleEnd(row)"
                                >结束</el-button
                            >
                        </div>
                    </div>
                </template>
            </common-table>
        </div>

        <RedPacketDialog ref="redPacketDialogRef" @success="reload" />
        <RedPacketDetailDialog ref="redPacketDetailDialogRef" />
        <RedPacketDataDialog ref="redPacketDataDialogRef" />
        <RedPacketLinkDialog ref="redPacketLinkDialogRef" />
        <RedPacketLogDialog ref="redPacketLogDialogRef" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import { ElMessageBox } from 'element-plus/es';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import RedPacketDialog from './components/RedPacketDialog.vue';
    import RedPacketDetailDialog from './components/RedPacketDetailDialog.vue';
    import RedPacketDataDialog from './components/RedPacketDataDialog.vue';
    import RedPacketLinkDialog from './components/RedPacketLinkDialog.vue';
    import RedPacketLogDialog from './components/RedPacketLogDialog.vue';
    import { Lightning } from '@element-plus/icons-vue';
    import request from '@/utils/request';

    defineOptions({ name: 'RedPacketManage' });

    const tableRef = ref(null);
    const activeTab = ref(undefined);
    const count1 = ref(0);
    const count2 = ref(0);

    // Dialog Refs
    const redPacketDialogRef = ref(null);
    const redPacketDetailDialogRef = ref(null);
    const redPacketDataDialogRef = ref(null);
    const redPacketLinkDialogRef = ref(null);
    const redPacketLogDialogRef = ref(null);

    const handleShowData = (row) => {
        redPacketDataDialogRef.value?.open(row.id);
    };

    const searchForm = reactive({
        name: '',
        status: ''
    });

    const columns = ref([
        { label: '活动名称', prop: 'couponName', minWidth: 150 },
        { label: '状态', slot: 'status', width: 100 },
        { label: '红包面额', slot: 'amount', minWidth: 100 },
        { label: '优惠方式', slot: 'threshold', minWidth: 120 },
        { label: '发放量', slot: 'distribution', minWidth: 120 },
        {
            label: '是否可以叠加使用',
            slot: 'stackType',
            minWidth: 120,
            formatter: (row) => (row.stackType === '1' ? '是' : '否')
        },
        { label: '使用时间', slot: 'time', minWidth: 220 },
        { label: '操作', slot: 'action', width: 200, fixed: 'right' }
    ]);

    const fetchCounts = async () => {
        try {
            const res1 = await request.get(
                '/shop/couponInfo/pagelist?type=1&page=1&limit=1'
            );
            if (res1.data.code === 200) {
                count1.value = res1.data.total || 0;
            }

            const res2 = await request.get(
                '/shop/couponInfo/pagelist?type=2&page=1&limit=1'
            );
            if (res2.data.code === 200) {
                count2.value = res2.data.total || 0;
            }
        } catch (error) {
            console.error('Failed to fetch counts:', error);
        }
    };

    const pageConfig = reactive({
        pageUrl: '/shop/couponInfo/pagelist',
        rowKey: 'id',
        params: {
            type: activeTab.value
        }
    });

    const reload = (where) => {
        tableRef.value?.reload(where);
        fetchCounts();
    };

    const reset = () => {
        searchForm.name = '';
        searchForm.status = '';
        reload();
    };

    const handleTabClick = () => {
        pageConfig.params.type = activeTab.value;
        reload();
    };

    const handleCreate = (type) => {
        redPacketDialogRef.value?.open(type, null);
    };

    const handleEdit = (row) => {
        redPacketDialogRef.value?.open(String(row.type), { ...row });
    };

    const handleViewDetail = (row) => {
        redPacketDetailDialogRef.value?.open(row.id);
    };

    const handleCopyData = (row) => {
        EleMessage.success('复制数据成功');
    };

    const handleOperationRecord = (row) => {
        redPacketLogDialogRef.value?.open(row.id);
    };

    const handleEnd = (row) => {
        ElMessageBox.confirm(
            '结束后，该优惠券不能再被领取，领券链接失效（请及时删除推广或装修），但已领取的优惠券仍能使用。是否确认结束优惠券？',
            { title: '结束活动', type: 'warning' }
        )
            .then(async () => {
                try {
                    const res = await request.post('/shop/couponInfo/end', {
                        couponId: row.id
                    });
                    if (res.data.code === 200) {
                        EleMessage.success('结束活动成功');
                        reload();
                    } else {
                        EleMessage.error(res.data.msg);
                    }
                } catch (error) {
                    console.error(error);
                    EleMessage.error('结束活动失败');
                }
            })
            .catch(() => {});
    };

    onMounted(() => {
        fetchCounts();
    });
</script>

<style scoped>
    /* Add any custom styles here */
</style>
