<template>
    <view class="container">
        <!-- 顶部统计 -->
        <view class="stats">
            <view class="stat-item">
                <view class="stat-label">红包数（个）</view>
                <view class="stat-value">{{ redPacketNum }}</view>
            </view>
            <view class="stat-item">
                <view class="stat-label">红包金额（元）</view>
                <view class="stat-value">{{ redPacketMoney }}</view>
            </view>
        </view>

        <!-- 分类标签 -->
        <view class="tabs">
            <view v-for="(tab, index) in tabList" :key="index" :class="['tab', { active: currentTab === index }]"
                @click="switchTab(index)">
                {{ tab }}
            </view>
        </view>

        <!-- 红包列表 -->
        <view class="content">
            <!-- 地区分组显示 -->
            <view v-if="currentTab === 2">
                <view v-for="(group, groupIndex) in redPacketList" :key="groupIndex">
                    <view class="ad_name">
                        <image src="https://static.hshuishang.com/Index_add.png" mode="widthFix" />
                        限{{ group.ad_name }}地区使用
                    </view>
                    <view v-for="(item, itemIndex) in group.packets" :key="itemIndex">
                        <view v-if="item.red_package_config">
                            <view class="item">
                                <view class="item_left">
                                    <view class="price">￥{{ item.red_package_config.money }}</view>
                                    <view class="full" v-if="item.red_package_config.full_amount">
                                        满{{ item.red_package_config.full_amount }}元可用
                                    </view>
                                </view>
                                <view class="item_center">
                                    <view class="title">{{ item.red_package_config.red_package_name }}</view>
                                    <view class="time">{{ item.red_package_config.end_time }}到期</view>
                                    <view class="desc">{{ item.red_package_config.belong_role === 1 ? '限指定店铺使用' :
                                        (item.red_package_config.belong_role === 2 ? '限指定地区使用' :
                                            '全平台使用') }}</view>
                                </view>
                                <view class="item_right" v-if="item.status === 2">
                                    <view class="status" @click="useRedPacket(item)">去使用</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 店铺分组显示 -->
            <view v-else-if="currentTab === 3">
                <view v-for="(group, groupIndex) in redPacketList" :key="groupIndex">
                    <view class="ad_name">
                        <image src="https://static.hshuishang.com/Index_add.png" mode="widthFix" />
                        {{ group.merchant_name }}
                    </view>
                    <view v-for="(item, itemIndex) in group.packets" :key="itemIndex">
                        <view v-if="item.red_package_config">
                            <view class="item">
                                <view class="item_left">
                                    <view class="price">￥{{ item.red_package_config.money }}</view>
                                    <view class="full" v-if="item.red_package_config.full_amount">满{{
                                        item.red_package_config.full_amount }}元可用</view>
                                </view>
                                <view class="item_center">
                                    <view class="title">{{ item.red_package_config.red_package_name }}</view>
                                    <view class="time">{{ item.red_package_config.end_time }}到期</view>
                                    <view class="desc">{{ item.red_package_config.belong_role === 1 ? '限指定店铺使用' :
                                        (item.red_package_config.belong_role === 2 ? '限指定地区使用' :
                                            '全平台使用') }}</view>
                                </view>
                                <view class="item_right" v-if="item.status === 2">
                                    <view class="status" @click="useRedPacket(item)">去使用</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 普通显示 -->
            <view v-else>
                <view v-for="(item, index) in redPacketList" :key="index">
                    <view v-if="item.red_package_config">
                        <view class="item">
                            <view class="item_left">
                                <view class="price">￥{{ item.red_package_config.money }}</view>
                                <view class="full" v-if="item.red_package_config.full_amount">满{{
                                    item.red_package_config.full_amount }}元可用</view>
                            </view>
                            <view class="item_center">
                                <view class="title">{{ item.red_package_config.red_package_name }}</view>
                                <view class="time">{{ item.red_package_config.end_time }}到期</view>
                                <view class="desc">{{ item.red_package_config.belong_role === 1 ? '限指定店铺使用' :
                                    (item.red_package_config.belong_role === 2 ? '限指定地区使用' :
                                        '全平台使用') }}</view>
                            </view>
                            <view class="item_right" v-if="item.status === 2">
                                <view class="status" @click="useRedPacket(item)">去使用</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { menuButtonInfo, NavgateTo, picUrl, request } from '../../../utils/index';
import { apiArr } from '../../../api/user';

export default {
    data() {
        return {
            currentTab: 0, // 当前选中的标签索引
            tabList: ['全部', '平台', '地区', '店铺', '历史记录'], // 标签列表
            redPacketList: [],
            changeIndex: 0,
            redPacketNum: 0,
            redPacketMoney: 0.00,
            page_num: 1,
            page_size: 20,
            loading: false,
            hasMore: true,
        }
    },
    methods: {
        async getMyRedPacket(changeIndex, isLoadMore = false) {
            if (this.loading) return;
            this.loading = true;
            
            const params = {
                user_id: uni.getStorageSync('userId'),
                belong_role: changeIndex == 0 ? '' : changeIndex,
                page_num: this.page_num,
                page_size: this.page_size,
            }
            const res = await request(apiArr.redPackageMyred, 'POST', params);
            
            if (!res || !res.rows) {
                this.loading = false;
                this.hasMore = false;
                return;
            }
            
            let processedList = res.rows
            .filter(item => item.status !== 3)
            .map(item => {
                const newItem = { ...item };

                if (newItem?.agent_info?.ad?.ad_name) {
                    newItem.agent_info.ad.ad_name = newItem.agent_info.ad.ad_name.split(',').join('');
                }

                return newItem;
            });

            if (this.currentTab == 2) {
                // 地区标签：按 ad_name 分组
                const grouped = {};
                processedList.forEach(item => {
                    if (item?.agent_info?.ad?.ad_name) {
                        const adName = item.agent_info.ad.ad_name;
                        if (!grouped[adName]) {
                            grouped[adName] = {
                                ad_name: adName,
                                packets: []
                            };
                        }
                        grouped[adName].packets.push(item);
                    }
                });
                
                if (isLoadMore) {
                    // 合并分组数据
                    const existingGroups = { ...this.redPacketList.reduce((acc, group) => {
                        acc[group.ad_name] = group;
                        return acc;
                    }, {}) };
                    
                    Object.keys(grouped).forEach(adName => {
                        if (existingGroups[adName]) {
                            existingGroups[adName].packets = [...existingGroups[adName].packets, ...grouped[adName].packets];
                        } else {
                            existingGroups[adName] = grouped[adName];
                        }
                    });
                    
                    this.redPacketList = Object.values(existingGroups);
                } else {
                    this.redPacketList = Object.values(grouped);
                }
            } else if (this.currentTab == 3) {
                // 店铺标签：按 merchant_name 分组
                const grouped = {};
                processedList.forEach(item => {
                    if (item?.merchant_info?.merchant_name) {
                        const merchantName = item.merchant_info.merchant_name;
                        if (!grouped[merchantName]) {
                            grouped[merchantName] = {
                                merchant_name: merchantName,
                                packets: []
                            };
                        }
                        grouped[merchantName].packets.push(item);
                    }
                });
                
                if (isLoadMore) {
                    // 合并分组数据
                    const existingGroups = { ...this.redPacketList.reduce((acc, group) => {
                        acc[group.merchant_name] = group;
                        return acc;
                    }, {}) };
                    
                    Object.keys(grouped).forEach(merchantName => {
                        if (existingGroups[merchantName]) {
                            existingGroups[merchantName].packets = [...existingGroups[merchantName].packets, ...grouped[merchantName].packets];
                        } else {
                            existingGroups[merchantName] = grouped[merchantName];
                        }
                    });
                    
                    this.redPacketList = Object.values(existingGroups);
                } else {
                    this.redPacketList = Object.values(grouped);
                }
            } else {
                if (isLoadMore) {
                    this.redPacketList = [...this.redPacketList, ...processedList];
                } else {
                    this.redPacketList = processedList;
                }
            }
            
            this.redPacketNum = processedList.filter(item => item.red_package_config).length;
            this.redPacketMoney = processedList.reduce((total, item) =>
                item.red_package_config ? total + item.red_package_config.money : total, 0.00
            ).toFixed(2);
            
            // 检查是否有更多数据
            this.hasMore = processedList.length === this.page_size;
            this.loading = false;
        },
        useRedPacket(item) {
            console.log('使用红包:', item);
            if (item.belong_role == 1) {
                uni.setStorageSync('merchantInfo', item.merchant_info);
                NavgateTo('/packages/localLife/detail/index')
            } else if (item.belong_role == 2) {
                NavgateTo('/pages/index/index');
            } else if (item.belong_role == 3) {
                NavgateTo('/packages/shop/index/index');
            }
        },
        switchTab(index) {
            this.currentTab = index;
            console.log('选中的标签:', this.tabList[index]);
            if (index == 0) {
                this.changeIndex = 0;
            } else if (index == 1) {
                this.changeIndex = 3;
            } else if (index == 2) {
                this.changeIndex = 2;
            } else if (index == 3) {
                this.changeIndex = 1;
            }
            // 重置分页状态
            this.page_num = 1;
            this.loading = false;
            this.hasMore = true;
            this.redPacketList = [];
            this.getMyRedPacket(this.changeIndex);
            if (this.tabList[index] == '历史记录') {
                NavgateTo('/packages/user/history/index');
            }
        },
        onReachBottom() {
            if (this.loading || !this.hasMore) return;
            this.page_num++;
            this.getMyRedPacket(this.changeIndex, true);
        }
    },
    onShow() {
        // 重置分页状态
        this.page_num = 1;
        this.loading = false;
        this.hasMore = true;
        this.redPacketList = [];
        this.switchTab(0);
        this.getMyRedPacket(0);
    }
}
</script>

<style>
@import url("./index.css");
</style>