<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 v-if="item.red_package_config.manjian" class="manjian">
                                        {{ item.red_package_config.manjian }}
                                    </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 v-if="item.red_package_config.manjian" class="manjian">
                                        {{ item.red_package_config.manjian }}
                                    </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 v-if="item.red_package_config.manjian" class="manjian">
                                    {{ item.red_package_config.manjian }}
                                </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,
        }
    },
    methods: {
        async getMyRedPacket(changeIndex) {
            const params = {
                user_id: uni.getStorageSync('userId'),
                belong_role: changeIndex == 0 ? '' : changeIndex,
            }
            const res = await request(apiArr.redPackageMyred, 'POST', params);
            let processedList = res.rows.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);
                    }
                });
                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);
                    }
                });
                this.redPacketList = Object.values(grouped);
            } else {
                this.redPacketList = processedList;
            }
            this.redPacketNum = res.rows.filter(item => item.red_package_config).length;
            this.redPacketMoney = res.rows.reduce((total, item) =>
                item.red_package_config ? total + item.red_package_config.money : total, 0.00
            ).toFixed(2);
        },
        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.getMyRedPacket(this.changeIndex);
            if (this.tabList[index] == '历史记录') {
                NavgateTo('/packages/user/history/index');
            }
        }
    },
    onShow() {
        this.switchTab(0);
        this.getMyRedPacket(0);
    }
}
</script>

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