<template>
    <div class="recharge-page">
        <div class="recharge-container">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1 class="page-title">账户充值</h1>
                <p class="page-subtitle">选择充值套餐，获得更多豆豆</p>
            </div>

            <!-- 当前余额卡片 -->
            <div class="card balance-card">
                <div class="card-title">当前余额</div>
                <div class="current-balance">
                    <text class="balance-amount">{{ store.user.integral || 0 }}</text>
                    <text class="balance-unit">豆豆</text>
                </div>
            </div>

            <!-- 充值套餐选择 -->
            <div class="card package-card">
                <div class="card-title">选择充值套餐</div>
                <div class="package-grid">
                    <div 
                        v-for="(item, index) in rechargePackages" 
                        :key="index"
                        :class="['package-item', { selected: selectedPackage === index }]"
                        @click="selectPackage(index)"
                    >
                        <div class="package-beans">{{ item.num }}豆豆</div>
                        <div class="package-price">¥{{ item.money }}</div>
                        <div v-if="item.giveNum" class="package-bonus">送{{ item.giveNum }}豆豆</div>
                    </div>
                </div>
            </div>

            <!-- 订单信息卡片 -->
            <div class="card order-card" v-if="totalPrice > 0">
                <div class="order-title">订单信息</div>
                <div class="order-item">
                    <text class="order-label">充值金额：</text>
                    <text class="order-value">¥{{ totalPrice.toFixed(2) }}</text>
                </div>
                <div class="order-item">
                    <text class="order-label">获得豆豆：</text>
                    <text class="order-value">{{ totalBeans }}豆豆</text>
                </div>
                <div class="order-divider"></div>
                <div class="order-item total-row">
                    <div class="order-total-label">合计：</div>
                    <div class="order-total">
                        <text class="order-total-highlight">¥{{ totalPrice.toFixed(2) }}</text>
                    </div>
                </div>
            </div>

            <!-- 提示信息 -->
            <div class="tip-text">
                请仔细核查并确认相关信息。因用户个人疏忽导致的充值错误，需由用户自行承担。一旦完成充值，概不退换。
            </div>

            <!-- 底部充值按钮 -->
            <div class="footer-bar">
                <el-button 
                    class="recharge-btn" 
                    type="primary" 
                    :disabled="totalPrice <= 0"
                    @click="handleRecharge"
                >
                    立即充值 ¥{{ totalPrice.toFixed(2) }}
                </el-button>
            </div>
        </div>

        <!-- 微信支付弹窗 -->
        <WechatPayment 
            v-model="showPaymentModal"
            :payment-data="paymentData"
            @success="handlePaymentSuccess"
            @cancel="handlePaymentCancel"
            @failed="handlePaymentFailed"
        />
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/store';
import { orderApi } from '@/api/user';
import WechatPayment from '@/components/common/WechatPayment.vue';

const router = useRouter();
const store = useMainStore();
const selectedPackage = ref(null);
const rechargePackages = ref([]);

// 支付相关状态
const showPaymentModal = ref(false);

const paymentData = computed(() => ({
    title: `充值${totalBeans.value}豆豆`,
    amount: Math.round(totalPrice.value * 100), // 转换为分
    body: `充值套餐 - ${totalBeans.value}豆豆`,
    packageId: selectedPackage.value !== null ? rechargePackages.value[selectedPackage.value].id : null
}));

// 计算总价
const totalPrice = computed(() => {
    if (selectedPackage.value !== null) {
        return rechargePackages.value[selectedPackage.value].money;
    }
    return 0;
});

// 计算总豆豆数
const totalBeans = computed(() => {
    if (selectedPackage.value !== null) {
        const pkg = rechargePackages.value[selectedPackage.value];
        return pkg.num + (pkg.giveNum || 0);
    }
    return 0;
});

// 获取充值套餐列表
const getPayPackageList = async () => {
    try {
        const res = await orderApi.getPayPackageList();
        if (res.result) {
            rechargePackages.value = res.result;
        }
    } catch (error) {
        console.error('获取充值套餐失败:', error);
        ElMessage.error('获取充值套餐失败');
    }
};

// 选择充值套餐
const selectPackage = (index) => {
    selectedPackage.value = index;
};

// 处理充值
const handleRecharge = async () => {
    if (totalPrice.value <= 0) {
        ElMessage.warning('请选择充值套餐');
        return;
    }

    if (selectedPackage.value === null) {
        ElMessage.warning('请选择充值套餐');
        return;
    }

    try {
        // 显示支付弹窗，订单创建将在支付组件中处理
        showPaymentModal.value = true;
        
    } catch (error) {
        console.error('发起支付失败:', error);
        ElMessage.error('发起支付失败，请重试');
    }
};

// 支付成功回调
const handlePaymentSuccess = async (orderId) => {
    try {
        ElMessage.success(`充值成功，获得${totalBeans.value}豆豆`);
        
        // 更新用户信息
        await store.getUserInfo();
        
        // 关闭支付弹窗
        showPaymentModal.value = false;
        
        // 重置状态
        selectedPackage.value = null;
        
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
            router.back();
        }, 2000);
        
    } catch (error) {
        console.error('更新用户信息失败:', error);
        ElMessage.error('支付成功，但更新用户信息失败，请刷新页面');
        
        // 即使更新失败，也要关闭弹窗
        showPaymentModal.value = false;
        selectedPackage.value = null;
    }
};

// 支付取消回调
const handlePaymentCancel = () => {
    showPaymentModal.value = false;
    ElMessage.info('已取消支付');
};

// 支付失败回调
const handlePaymentFailed = (errorMessage) => {
    showPaymentModal.value = false;
    ElMessage.error(errorMessage || '支付失败，请重试');
};

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

<style lang="scss" scoped>
.recharge-page {
    min-height: 100vh;
    background: #f5f7fa;
    padding: 20px 0;
}

.recharge-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 20px;
}

.page-header {
    text-align: center;
    margin-bottom: 30px;

    .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #0A2463;
        margin: 0 0 8px 0;
    }

    .page-subtitle {
        font-size: 14px;
        color: #666;
        margin: 0;
    }
}

.card {
    background: #fff;
    border-radius: 12px;
    margin-bottom: 20px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #ebeef5;
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 20px;
}

// 当前余额卡片
.balance-card {
    background: linear-gradient(135deg, #0A2463 0%, #1e3a8a 100%);
    color: #fff;
    text-align: center;

    .card-title {
        color: #fff;
        opacity: 0.9;
        font-size: 16px;
    }

    .current-balance {
        display: flex;
        align-items: baseline;
        justify-content: center;
        gap: 8px;
        margin-top: 10px;

        .balance-amount {
            font-size: 36px;
            font-weight: bold;
        }

        .balance-unit {
            font-size: 16px;
            opacity: 0.8;
        }
    }
}

// 充值套餐
.package-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 16px;
}

.package-item {
    background: #fafbfc;
    border: 2px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px 16px;
    text-align: center;
    transition: all 0.2s;
    cursor: pointer;
    position: relative;

    &:hover {
        border-color: #0A2463;
        background: rgba(10, 36, 99, 0.05);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(10, 36, 99, 0.15);
    }

    &.selected {
        border-color: #0A2463;
        background: rgba(10, 36, 99, 0.05);
        box-shadow: 0 4px 12px rgba(10, 36, 99, 0.15);
        
        &::before {
            content: '✓';
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            background: #0A2463;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }
    }

    .package-beans {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 8px;
    }

    .package-price {
        font-size: 16px;
        color: #0A2463;
        font-weight: 500;
        margin-bottom: 6px;
    }

    .package-bonus {
        font-size: 12px;
        color: #e6a23c;
        background: rgba(230, 162, 60, 0.1);
        padding: 2px 8px;
        border-radius: 4px;
        display: inline-block;
    }
}

// 订单信息
.order-card {
    .order-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 20px;
    }

    .order-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .order-label {
            font-size: 14px;
            color: #606266;
        }

        .order-value {
            font-size: 14px;
            color: #303133;
            font-weight: 500;
        }

        &.total-row {
            margin-bottom: 0;
            margin-top: 12px;
            padding-top: 12px;

            .order-total-label {
                font-size: 16px;
                color: #303133;
                font-weight: 600;
            }

            .order-total-highlight {
                font-size: 18px;
                color: #0A2463;
                font-weight: bold;
            }
        }
    }

    .order-divider {
        height: 1px;
        background: #ebeef5;
        margin: 12px 0;
    }
}

.tip-text {
    color: #909399;
    font-size: 12px;
    margin: 0 20px 20px 20px;
    line-height: 1.6;
    text-align: center;
    background: #fdf6ec;
    padding: 12px;
    border-radius: 6px;
    border-left: 4px solid #e6a23c;
}

.footer-bar {
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #ebeef5;
}

.recharge-btn {
    width: 100%;
    background: #0A2463;
    color: #fff;
    font-size: 16px;
    border-radius: 6px;
    height: 44px;
    border: none;
    font-weight: 500;
    transition: all 0.2s;

    &:hover:not(:disabled) {
        background: #1e3a8a;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(10, 36, 99, 0.3);
    }

    &:active:not(:disabled) {
        transform: translateY(0);
    }

    &:disabled {
        background: #c0c4cc;
        color: #fff;
        cursor: not-allowed;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .recharge-container {
        max-width: 100%;
        padding: 0 16px;
    }

    .package-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .package-item {
        padding: 16px 12px;

        .package-beans {
            font-size: 18px;
        }

        .package-price {
            font-size: 14px;
        }
    }
}

@media (max-width: 480px) {
    .page-header .page-title {
        font-size: 24px;
    }

    .card {
        padding: 20px 16px;
    }

    .package-grid {
        gap: 12px;
    }
}
</style> 