<template>
    <view class="pp">
        <!-- 顶部积分 -->
        <view class="pp-header">
            <view class="pp-header__row">
                <text class="pp-header__label">当前积分</text>
                <text class="pp-header__value">{{ userPoints }}</text>
            </view>
        </view>

        <!-- 步骤1: 选择积分套餐 (两列网格) -->
        <view class="pp-section">
            <view class="pp-section__title">选择积分套餐</view>
            <view class="pp-grid">
                <view v-for="item in products" :key="item.id" class="pp-grid__item"
                    :class="{ 'pp-grid__item--active': selectedId === item.id }" @tap="selectProduct(item)">
                    <text class="pp-grid__points">{{ item.points }}</text>
                    <text class="pp-grid__unit">积分</text>
                    <text class="pp-grid__price">￥{{ item.amount }}</text>
                    <view v-if="selectedId === item.id" class="pp-grid__check">
                        <u-icon name="checkbox-mark" color="#fff" size="20" />
                    </view>
                </view>
            </view>
        </view>

        <!-- 步骤2: 订单确认信息（选择商品后显示） -->
        <view v-if="selectedProduct" class="pp-section">
            <view class="pp-section__title">订单确认</view>
            <view class="pp-confirm">
                <view class="pp-confirm__row">
                    <text class="pp-confirm__label">商品名称</text>
                    <text class="pp-confirm__value">{{ selectedProduct.name }}</text>
                </view>
                <view class="pp-confirm__row">
                    <text class="pp-confirm__label">积分数量</text>
                    <text class="pp-confirm__value">{{ selectedProduct.points }} 积分</text>
                </view>
                <view class="pp-confirm__row">
                    <text class="pp-confirm__label">支付金额</text>
                    <text class="pp-confirm__value pp-confirm__value--price">￥{{ selectedProduct.amount }}</text>
                </view>
                <view class="pp-confirm__row">
                    <text class="pp-confirm__label">充值账号</text>
                    <text class="pp-confirm__value">{{ userInfo.nickname }} (ID: {{ userInfo.sn }})</text>
                </view>
            </view>
        </view>

        <view v-if="!products.length && !loading" class="pp-empty">
            <text>暂无积分套餐</text>
        </view>

        <!-- 底部按钮 -->
        <view v-if="selectedId" class="pp-bottom">
            <view class="pp-bottom__left">
                <text class="pp-bottom__total">￥{{ selectedProduct?.amount || '0.00' }}</text>
            </view>
            <view class="pp-bottom__btn" :class="{ 'pp-bottom__btn--disabled': submitting }" @tap="handleSubmit">
                <text v-if="!submitting">确认支付</text>
                <u-loading v-else color="#fff" size="36" />
            </view>
        </view>

        <!-- 支付组件 -->
        <payment v-model:show="payState.show" v-model:showCheck="payState.showCheck" :orderId="payState.orderId"
            :from="payState.from" redirect="/packages/pages/points_order_detail/points_order_detail"
            @success="onPaySuccess" @close="onPayClose" />
    </view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, reactive, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { pointsProducts, pointsCreateOrder } from '@/api/points'
import request from '@/utils/request'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const products = ref<any[]>([])
const userPoints = ref(0)
const loading = ref(false)
const selectedId = ref(0)
const submitting = ref(false)

const payState = reactive({
    show: false,
    showCheck: false,
    orderId: 0,
    from: 'points_order'
})

const selectedProduct = computed(() => {
    return products.value.find((p: any) => p.id === selectedId.value) || null
})

const fetchProducts = async () => {
    loading.value = true
    try {
        const data = await pointsProducts()
        products.value = data || []
    } finally {
        loading.value = false
    }
}

const fetchUserPoints = async () => {
    try {
        const res: any = await request.get(
            { url: '/community/userStats' },
            { isTransformResponse: false }
        )
        if (res?.code === 1 && res.data) {
            userPoints.value = res.data.user_points || 0
        }
    } catch (e) {
        // 静默
    }
}

const selectProduct = (item: any) => {
    if (selectedId.value === item.id) return
    selectedId.value = item.id
}

const handleSubmit = async () => {
    if (!selectedProduct.value || submitting.value) return
    submitting.value = true
    try {
        const orderRes = await pointsCreateOrder({
            product_id: selectedProduct.value.id
        })
        payState.orderId = orderRes.order_id
        payState.from = orderRes.from
        payState.show = true
    } catch (e: any) {
        uni.$u.toast(e?.msg || '下单失败')
    } finally {
        submitting.value = false
    }
}

const onPaySuccess = () => {
    uni.$u.toast('支付成功')
    fetchUserPoints()
    uni.redirectTo({
        url: `/packages/pages/points_order_detail/points_order_detail?order_id=${payState.orderId}`
    })
}

const onPayClose = () => {
    if (payState.orderId) {
        uni.navigateTo({
            url: `/packages/pages/points_order_detail/points_order_detail?order_id=${payState.orderId}`
        })
    }
}

onShow(() => {
    fetchProducts()
    fetchUserPoints()
    userStore.getUser()
    selectedId.value = 0
    payState.show = false
    payState.orderId = 0
})
</script>

<style lang="scss" scoped>
.pp {
    min-height: 100vh;
    background: #f5f5f5;
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.pp-header {
    background: linear-gradient(170deg, #185dff, #4d82ff);
    padding: 40rpx 32rpx 48rpx;

    &__row {
        display: flex;
        align-items: baseline;
        gap: 12rpx;
    }

    &__label {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
    }

    &__value {
        font-size: 56rpx;
        font-weight: 700;
        color: #fff;
    }
}

.pp-section {
    margin: 24rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 28rpx;

    &__title {
        font-size: 30rpx;
        font-weight: 600;
        color: #222;
        margin-bottom: 24rpx;
    }
}

/* 两列网格 */
.pp-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20rpx;
}

.pp-grid__item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f7f8fa;
    border-radius: 16rpx;
    padding: 32rpx 16rpx;
    border: 3rpx solid transparent;
    transition: all 0.2s;

    &--active {
        border-color: #185dff;
        background: #eef3ff;
    }
}

.pp-grid__points {
    font-size: 42rpx;
    font-weight: 700;
    color: #222;
    line-height: 1;
}

.pp-grid__unit {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
}

.pp-grid__price {
    font-size: 28rpx;
    font-weight: 600;
    color: #185dff;
    margin-top: 12rpx;
}

.pp-grid__check {
    position: absolute;
    top: -2rpx;
    right: -2rpx;
    width: 48rpx;
    height: 48rpx;
    background: #185dff;
    border-radius: 0 16rpx 0 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
}

/* 订单确认 */
.pp-confirm {
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 20rpx 24rpx;

    &__row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 14rpx 0;
    }

    &__label {
        font-size: 26rpx;
        color: #999;
    }

    &__value {
        font-size: 26rpx;
        color: #333;

        &--price {
            font-size: 32rpx;
            font-weight: 700;
            color: #185dff;
        }
    }
}

.pp-empty {
    text-align: center;
    padding: 120rpx 0;
    color: #999;
    font-size: 28rpx;
}

/* 底部栏 */
.pp-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx 32rpx;
    padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
    box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.06);

    &__left {
        flex: 1;
    }

    &__total {
        font-size: 40rpx;
        font-weight: 700;
        color: #185dff;
    }

    &__btn {
        background: #185dff;
        color: #fff;
        font-size: 30rpx;
        font-weight: 500;
        padding: 20rpx 64rpx;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 220rpx;

        &--disabled {
            opacity: 0.5;
        }
    }
}
</style>
