<template>
    <view class="group-goods" v-if="flashSaleList.length > 0">
        <view class="title-box x-bc">
            <view class="left-title">
                <text class="title-icon">⚡</text>
                <text class="title">限时秒杀</text>
                <view class="home-countdown" v-if="globalCountdown > 0">
                    <text class="time-block">{{ formatTimeObj(globalCountdown).h }}</text>
                    <text class="time-colon">:</text>
                    <text class="time-block">{{ formatTimeObj(globalCountdown).m }}</text>
                    <text class="time-colon">:</text>
                    <text class="time-block">{{ formatTimeObj(globalCountdown).s }}</text>
                </view>
            </view>
            <view class="group-people x-f" @tap="navTo('/pages_index/index/flashSaleList')">
                <text class="tip">更多</text>
                <text class="cuIcon-right">></text>
            </view>
        </view>
        <view class="goods-box">
            <view class="min-goods" v-for="(item, index) in flashSaleList" :key="item.id" @tap="showProduct(item)">
                <view class="img-box">
                    <image class="img" :src="item.productImage" mode="aspectFill"></image>
                </view>
                <view class="title ellipsis">{{ item.productName }}</view>
                <view class="price-box">
                    <text class="price">￥{{ item.flashPrice }}</text>
                    <view :class="['btn-grab', item.activityStatus === 'not_started' ? 'disabled' : '']">抢</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { getActiveFlashSaleList, getFlashSaleServerTime } from '@/api/flashSale.js';

export default {
    name: "FlashSale",
    data() {
        return {
            flashSaleList: [],
            timer: null,
            globalCountdown: 0,
            serverTimestamp: 0
        };
    },
    mounted() {
        this.getFlashSaleData();
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    methods: {
        async getFlashSaleData() {
            try {
                // 并发请求列表和服务器时间
                const [listRes, timeRes] = await Promise.all([
                    getActiveFlashSaleList(),
                    getFlashSaleServerTime()
                ]);

                let currentServerTime = Date.now();
                if (timeRes.code === 0 || timeRes.code === 200) {
                    currentServerTime = timeRes.serverTimestamp || timeRes.data?.serverTimestamp || Date.now();
                } else if (listRes.serverTimestamp) {
                    currentServerTime = listRes.serverTimestamp;
                }
                
                // 将服务器时间转为秒级用于校准倒计时
                const serverTimeSec = Math.floor(currentServerTime / 1000);

                if (listRes.code === 0 || listRes.code === 200) {
                    let list = listRes.data || [];
                    this.flashSaleList = list.slice(0, 6);
                    
                    // 基于服务器时间校准倒计时
                    this.flashSaleList.forEach(item => {
                        let targetTime = 0;
                        if (item.activityStatus === 'not_started') {
                            targetTime = Math.floor(new Date(item.startTime.replace(/-/g, '/')).getTime() / 1000);
                        } else if (item.activityStatus === 'ongoing') {
                            targetTime = Math.floor(new Date(item.endTime.replace(/-/g, '/')).getTime() / 1000);
                        }
                        
                        if (targetTime > 0) {
                            let diff = targetTime - serverTimeSec;
                            item.countdown = diff > 0 ? diff : 0;
                        }
                    });

                    if (this.flashSaleList.length > 0) {
                        this.globalCountdown = this.flashSaleList[0].countdown;
                    }
                    this.startCountdown();
                }
            } catch (error) {
                console.error('获取秒杀数据失败', error);
            }
        },
        startCountdown() {
            if (this.timer) {
                clearInterval(this.timer);
            }
            this.timer = setInterval(() => {
                let hasCountdown = false;
                if (this.globalCountdown > 0) {
                    this.globalCountdown--;
                }
                this.flashSaleList.forEach(item => {
                    if (item.countdown > 0) {
                        item.countdown--;
                        hasCountdown = true;
                    } else if (item.countdown === 0 && item.activityStatus === 'not_started') {
                        item.activityStatus = 'ongoing';
                        // 到达开始时间后，将倒计时切换为距离结束时间的倒计时
                        let endTimeSec = Math.floor(new Date(item.endTime.replace(/-/g, '/')).getTime() / 1000);
                        let nowSec = Math.floor(Date.now() / 1000); // 粗略计算，可结合初始偏差
                        let diff = endTimeSec - nowSec;
                        item.countdown = diff > 0 ? diff : 0;
                        if (item.countdown > 0) hasCountdown = true;
                    } else if (item.countdown === 0 && item.activityStatus === 'ongoing') {
                        item.activityStatus = 'ended';
                    }
                });
                if (!hasCountdown && this.globalCountdown <= 0) {
                    clearInterval(this.timer);
                }
            }, 1000);
        },
        formatTimeObj(seconds) {
            if (!seconds || seconds <= 0) return { h: '00', m: '00', s: '00' };
            let h = Math.floor(seconds / 3600);
            let m = Math.floor((seconds % 3600) / 60);
            let s = seconds % 60;
            return {
                h: h.toString().padStart(2, '0'),
                m: m.toString().padStart(2, '0'),
                s: s.toString().padStart(2, '0')
            };
        },
        navTo(url) {
            uni.navigateTo({
                url: url
            });
        },
        showProduct(item) {
            uni.navigateTo({
                url: '/pages_index/index/activityProductDetail?type=flash&id=' + item.id
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.group-goods {
    position: relative;
    z-index: 1;
    background: linear-gradient(180deg, #fff0f0 0%, #FFFFFF 20%);
    border-radius: 16upx;
    margin-bottom: 20upx;
    margin-top: 20upx;
    padding: 20upx;
}

.x-bc {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.x-f {
    display: flex;
    align-items: center;
}

.title-box {
    padding-bottom: 20rpx;

    .left-title {
        display: flex;
        align-items: center;
        
        .title-icon {
            font-size: 36rpx;
            color: #ff6a00;
            margin-right: 10rpx;
        }

        .title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-right: 16rpx;
        }

        .home-countdown {
            display: flex;
            align-items: center;

            .time-block {
                background: #ff6a00;
                color: #fff;
                font-size: 20rpx;
                padding: 2rpx 6rpx;
                border-radius: 6rpx;
                line-height: 28rpx;
            }

            .time-colon {
                color: #ff6a00;
                font-size: 24rpx;
                margin: 0 4rpx;
                font-weight: bold;
            }
        }
    }

    .group-people {
        .tip {
            font-size: 24rpx;
            color: #999999;
        }

        .cuIcon-right {
            font-size: 24rpx;
            color: #999;
            margin-left: 4rpx;
        }
    }
}

.goods-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: start;

    .min-goods {
        width: 210rpx;
        background: #fff;
        margin-bottom: 20rpx;
		margin: 0 14rpx;
        border-radius: 12rpx;
        overflow: hidden;

        .img-box {
            width: 210rpx;
            height: 210rpx;
            overflow: hidden;

            .img {
                width: 100%;
                height: 100%;
                background-color: #f5f5f5;
            }
        }

        .title {
            font-size: 24rpx;
            color: #333;
            margin: 10rpx 8rpx;
            line-height: 34rpx;
            height: 34rpx;
        }

        .ellipsis {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .price-box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 0 8rpx 10rpx;
            border: 1rpx solid #ff6a00;
            border-radius: 6rpx;
            overflow: hidden;

            .price {
                font-size: 24rpx;
                font-weight: bold;
                color: #ff6a00;
                padding: 0 6rpx;
                flex: 1;
            }

            .btn-grab {
                background: #ff6a00;
                color: #fff;
                font-size: 22rpx;
                padding: 4rpx 12rpx;
                
                &.disabled {
                    background: #ccc;
                    color: #fff;
                }
            }
        }
    }
}
</style>