<template>
    <view class="packet-page">
        <!-- Background -->
        <image src="/packet/static/index/background.png" class="bg-image" mode="widthFix"></image>

        <!-- Main Content -->
        <view class="content-wrapper">
            <!-- Headline -->
            <image src="/packet/static/index/headline.png" class="headline-image" mode="widthFix"></image>

            <!-- Red Envelope Section -->
            <view class="envelope-section">
                <!-- Red Envelope Image -->
                <image src="/packet/static/index/red_envelope.png" class="envelope-image" mode="widthFix"></image>

                <!-- Amount Display -->
                <view class="amount-wrapper">
                    <view class="amount-display">
                        <text class="currency">¥</text>
                        <text class="amount-value">{{ amount }}</text>
                    </view>
                </view>

                <!-- Receive Button -->
                <view class="receive-btn-wrapper" @click="handleReceive">
                    <image src="/packet/static/index/btn_receive.png" class="btn-image" mode="widthFix"></image>
                    <text class="btn-text" v-if="!redBagData.drawStatus">领{{ amount }}元红包 | 买书卖书都能用</text>
                    <text class="btn-text" v-else>已领取</text>
                </view>
            </view>

            <!-- Info Card -->
            <view class="info-card-section">
                <image src="/packet/static/index/info_frame.png" class="info-frame" mode="widthFix"></image>
                <view class="info-content">
                    <view class="info-list">
                        <view class="info-item">
                            <text>买书立减</text>
                            <text class="spacer"></text>
                            <text>卖书加价</text>
                        </view>
                        <view class="info-item">
                            <text>伴你轻松度过大学四年</text>
                        </view>
                        <view class="info-item">
                            <text>官方补贴</text>
                            <text class="spacer"></text>
                            <text>无门槛使用</text>
                        </view>
                    </view>
                    <view class="rule-footer">
                        <text class="rule-text">活动规则</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import { silentLogin } from '@/api/auth'

    export default {
        data() {
            return {
                amount: '1.58',
                bianhao: '', // 红包编号
                redBagData: null // 红包数据
            }
        },
        onLoad(options) {
            let bianhao = options.bianhao;

            // 兼容扫码进入场景，当前页的 scene 里带了 bianhao
            if (!bianhao && options.scene) {
                const decodeScene = decodeURIComponent(options.scene);
                const paramPairs = decodeScene.split('&');
                paramPairs.forEach((pair) => {
                    const [key, value] = pair.split('=');
                    if (key === 'bianhao') {
                        bianhao = value;
                    }
                });
            }

            // 兼容从 App.vue 缓存中获取 (因为如果是扫小程序码直接进入这个页面，App.vue的onLaunch会先执行并存入缓存，然后执行页面的onLoad)
            if (!bianhao) {
                bianhao = uni.getStorageSync('scene_bianhao');
            }

            if (bianhao) {
                this.bianhao = bianhao;
                uni.removeStorageSync('scene_bianhao');
                // 调用扫码接口获取红包信息
                this.scanRedBag();
            }
        },
        onShow() {
            // 如果是从其他页面返回，重新获取红包数据
            if (this.bianhao) {
                this.scanRedBag();
            }
        },
        methods: {
            // 请求前确保 token 可用，避免扫码冷启动时出现 401
            async ensureTokenReady() {
                const token = uni.getStorageSync('token')
                if (token) return true
                try {
                    await silentLogin()
                    return !!uni.getStorageSync('token')
                } catch (e) {
                    return false
                }
            },
            // 扫码获取红包信息
            async scanRedBag() {
                if (!this.bianhao) {
                    // 如果没有编号，提示用户扫码
                    uni.showModal({
                        title: '提示',
                        content: '请扫描红包二维码',
                        showCancel: false
                    });
                    return;
                }

                const loginReady = await this.ensureTokenReady()
                if (!loginReady) {
                    uni.showToast({
                        title: '登录状态失效，请稍后重试',
                        icon: 'none'
                    });
                    return;
                }

                this.$u.api.scanRedBagAjax(this.bianhao).then(res => {
                    console.log('扫码获取红包信息成功:', res);
                    if (res.code === 200) {
                        this.redBagData = res.data;
                        this.amount = res.data.redPrice;
                    } else {
                        uni.showToast({
                            title: res.msg || '获取红包信息失败',
                            icon: 'none'
                        });
                    }
                })
            },
            // 领取红包
            async handleReceive() {
                // 如果已领取，提示用户
                if (this.redBagData && this.redBagData.drawStatus === 1) {
                    uni.showToast({
                        title: '红包已领取',
                        icon: 'none'
                    });
                    return;
                }

                if (!this.bianhao) {
                    uni.showToast({
                        title: '红包编号缺失',
                        icon: 'none'
                    });
                    return;
                }

                const loginReady = await this.ensureTokenReady()
                if (!loginReady) {
                    uni.showToast({
                        title: '登录状态失效，请稍后重试',
                        icon: 'none'
                    });
                    return;
                }

                // 显示领取中提示
                uni.showLoading({
                    title: '领取中...'
                });

                try {
                    const res = await this.$u.api.getRedBagAjax(this.bianhao);
                    uni.hideLoading();
                    if (res.code === 200) {
                        // 更新红包数据
                        this.redBagData = res.data;
                        uni.showToast({
                            title: '领取成功',
                            icon: 'success'
                        });
                        // 跳转到 get 页面，并传递红包数据
                        setTimeout(() => {
                            uni.redirectTo({
                                url: '/packet/pages/get?bianhao=' + this.bianhao
                            });
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.msg || '领取失败',
                            icon: 'none'
                        });
                    }
                } catch (e) {
                    uni.hideLoading();
                    console.error('领取红包失败:', e);
                    uni.showToast({
                        title: '网络错误',
                        icon: 'none'
                    });
                }
            },
            handleShare() {
                // Share logic
            }
        }
    }
</script>

<style lang="scss" scoped>
    .packet-page {
        height: 100vh;
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;

        .bg-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
        }

        .content-wrapper {
            position: relative;
            z-index: 1;
            width: 100%;
            padding: 40rpx 30rpx;
            box-sizing: border-box;

            .headline-image {
                width: 80%;
                margin-left: 10%;
                margin-bottom: 30rpx;
                margin-top: 30rpx;
            }

            .envelope-section {
                position: relative;

                .envelope-image {
                    width: 90%;
                    display: block;
                    margin: 0 auto;
                }

                .amount-wrapper {
                    position: absolute;
                    top: 12%;
                    left: 50%;
                    transform: translateX(-50%);
                    text-align: center;

                    .amount-display {
                        display: flex;
                        align-items: baseline;
                        justify-content: center;

                        .currency {
                            font-size: 78rpx;
                            color: #FF4444;
                            font-weight: bold;
                            margin-right: 4rpx;
                        }

                        .amount-value {
                            font-size: 156rpx;
                            color: #FF4444;
                            font-weight: bold;
                        }
                    }
                }

                .receive-btn-wrapper {
                    position: absolute;
                    bottom: 15%;
                    left: 52%;
                    transform: translateX(-50%);
                    width: 84%;

                    .btn-image {
                        width: 100%;
                        height: auto;
                    }

                    .btn-text {
                        position: absolute;
                        top: 45%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        font-size: 32rpx;
                        color: #D73800;
                        font-weight: 500;
                        white-space: nowrap;
                    }
                }
            }

            .info-card-section {
                position: relative;
                margin-bottom: 20rpx;

                .info-frame {
                    width: 100%;
                    display: block;
                }

                .info-content {
                    position: absolute;
                    top: 20%;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    padding: 30rpx;
                    box-sizing: border-box;

                    .info-list {
                        padding: 0 20rpx;

                        .info-item {
                            font-family: Fotor_HelloFont_GongYiTi;
                            font-size: 40rpx;
                            color: #000000;
                            line-height: 64rpx;
                            text-align: center;

                            .spacer {
                                flex: 1;
                                margin: 0 16rpx;
                            }

                            .star {
                                color: #FFB300;
                                margin-left: 8rpx;
                            }
                        }
                    }

                    .rule-footer {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        margin-top: 30rpx;

                        .rule-text {
                            font-size: 26rpx;
                            color: #666;
                            text-decoration: underline;
                        }

                        .share-btn-wrapper {
                            position: absolute;
                            bottom: 20rpx;
                            right: 20rpx;
                            width: 120rpx;
                            height: 120rpx;

                            .share-btn-image {
                                width: 100%;
                                height: 100%;
                            }

                            .share-text {
                                position: absolute;
                                top: 50%;
                                left: 50%;
                                transform: translate(-50%, -50%);
                                font-size: 22rpx;
                                color: #fff;
                                font-weight: bold;
                                text-align: center;
                                line-height: 1.3;
                            }
                        }
                    }
                }
            }
        }
    }
</style>
