<template>
    <view class="vip-page">
        <view class="vip-header" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="vip-header__nav">
                <u-icon name="arrow-left" color="#fff" size="36" @click="goBack" />
                <text class="vip-header__title">VIP会员</text>
                <view style="width: 36rpx" />
            </view>
            <view class="vip-user">
                <image class="vip-user__avatar" :src="userInfo.avatar || '/static/images/avatar.png'"
                    mode="aspectFill" />
                <view class="vip-user__info">
                    <text class="vip-user__name">{{ userInfo.nickname || '用户' }}</text>
                    <view class="vip-user__status-row">
                        <text class="vip-user__status">{{ vipLevelName }}</text>
                        <text v-if="vipRemainDays" class="vip-user__remain">剩余{{ vipRemainDays }}天</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 已开通VIP：展示权益网格 -->
        <template v-if="isVip">
            <view class="vip-benefits-grid">
                <view class="vip-benefits-grid__header">
                    <text class="vip-benefits-grid__title">会员专属权益</text>
                </view>
                <view class="vip-benefits-grid__list">
                    <view v-for="(item, idx) in benefitList" :key="idx" class="benefit-card">
                        <image class="benefit-card__icon" :src="item.icon" mode="aspectFit" />
                        <view class="benefit-card__tag">
                            <text>{{ item.tag }}</text>
                        </view>
                        <text class="benefit-card__desc">{{ item.desc }}</text>
                    </view>
                </view>
            </view>
        </template>

        <!-- 未开通VIP：套餐选择 + 权益列表 + FAQ + 购买按钮 -->
        <template v-else>
            <view class="vip-plans">
                <view class="vip-plans__title">
                    <text>选择会员套餐</text>
                </view>
                <view class="vip-plans__list">
                    <view v-for="plan in levels" :key="plan.id" class="plan-card"
                        :class="{ 'plan-card--active': selectedId === plan.id, 'plan-card--hot': plan.is_recommend === 1 }"
                        @tap="selectedId = plan.id">
                        <view v-if="plan.is_recommend === 1" class="plan-card__badge">推荐</view>
                        <text class="plan-card__name">{{ plan.name }}</text>
                        <view class="plan-card__price">
                            <text class="plan-card__symbol">¥</text>
                            <text class="plan-card__amount">{{ plan.price }}</text>
                        </view>
                        <text class="plan-card__duration">{{ plan.duration }}天</text>
                    </view>
                </view>
            </view>

            <view v-if="currentLevel" class="vip-benefits">
                <view class="vip-benefits__header">
                    <text class="vip-benefits__title">会员专属权益</text>
                </view>
                <view class="vip-benefits__list">
                    <view v-for="(item, idx) in benefitList" :key="idx" class="benefit-row">
                        <view class="benefit-row__tag">
                            <text>{{ item.tag }}</text>
                        </view>
                        <text class="benefit-row__desc">{{ item.desc }}</text>
                    </view>
                </view>
            </view>

            <view class="vip-faq">
                <view class="vip-faq__title">
                    <text>常见问题</text>
                </view>
                <view v-for="(q, idx) in faqs" :key="idx" class="faq-item" @tap="q.open = !q.open">
                    <view class="faq-item__header">
                        <text class="faq-item__q">{{ q.question }}</text>
                        <u-icon :name="q.open ? 'arrow-up' : 'arrow-down'" size="24" color="#999" />
                    </view>
                    <view v-if="q.open" class="faq-item__answer">
                        <text>{{ q.answer }}</text>
                    </view>
                </view>
            </view>

            <view v-if="!loading && levels.length" class="vip-bottom">
                <view class="vip-bottom__btn" :class="{ 'vip-bottom__btn--disabled': submitting || isCurrentLevel }"
                    @tap="handleSubscribe">
                    <text v-if="isCurrentLevel">当前已是{{ currentLevel?.name }}</text>
                    <text v-else-if="!submitting">立即开通 ¥{{ currentLevel?.price || '' }}</text>
                    <u-loading v-else color="#fff" size="36" />
                </view>
                <text class="vip-bottom__tip">开通即表示同意《VIP服务协议》</text>
            </view>

            <payment v-model:show="payState.show" v-model:showCheck="payState.showCheck" :orderId="payState.orderId"
                :from="payState.from" @success="onPaySuccess" @close="onPayClose" />
        </template>
    </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { vipLevels, vipCreateOrder } from '@/api/vip'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const statusBarHeight = ref(0)
const selectedId = ref(0)
const levels = ref<any[]>([])
const loading = ref(false)
const submitting = ref(false)

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

const currentLevel = computed(() => levels.value.find((l: any) => l.id === selectedId.value) || null)

const vipInfo = computed(() => userInfo.value.vip_info || {})
const isVip = computed(() => !!vipInfo.value.is_vip)

const defaultBenefits = [
    { tag: '深度分析', desc: 'AI深度分析报告，每日无限次', icon: '/static/icons/vip_analysis.png' },
    { tag: '跟单提醒', desc: '跟单实时提醒', icon: '/static/icons/vip_follow.png' },
    { tag: '去除广告', desc: '去除广告', icon: '/static/icons/vip_adblock.png' },
    { tag: '专家方案', desc: '专家方案优先查看', icon: '/static/icons/vip_expert.png' },
    { tag: '专属客服', desc: '专属VIP客服', icon: '/static/icons/vip_service.png' },
    { tag: '数据导出', desc: '赛事数据导出', icon: '/static/icons/vip_export.png' }
]

const benefitList = computed(() => {
    if (currentLevel.value?.benefits && Array.isArray(currentLevel.value.benefits)) {
        return currentLevel.value.benefits
    }
    return defaultBenefits
})

const isCurrentLevel = computed(() => {
    if (!vipInfo.value.is_vip || !currentLevel.value) return false
    return vipInfo.value.vip_level === currentLevel.value.level
})

const vipLevelName = computed(() => {
    if (vipInfo.value.is_vip) {
        return vipInfo.value.vip_level_name || 'VIP会员'
    }
    return '普通用户'
})

const vipRemainDays = computed(() => {
    if (!vipInfo.value.is_vip) return ''
    const ts = vipInfo.value.vip_expire_timestamp
    if (!ts) return ''
    const days = Math.ceil((ts * 1000 - Date.now()) / (1000 * 60 * 60 * 24))
    return days > 0 ? days : ''
})

const faqs = reactive([
    { question: 'VIP开通后可以退款吗？', answer: 'VIP为虚拟服务，开通后不支持退款。请确认后再开通。', open: false },
    { question: '套餐到期后会自动续费吗？', answer: '不会自动续费。到期后需要手动重新订阅。', open: false },
    { question: '不同套餐的权益有区别吗？', answer: '不同等级享有不同权益，详见各套餐权益描述。', open: false },
    { question: '如何查看VIP到期时间？', answer: '可在个人中心页面查看VIP状态和到期时间。', open: false },
])

onMounted(() => {
    const sysInfo = uni.getSystemInfoSync()
    // #ifdef APP-PLUS || MP
    statusBarHeight.value = sysInfo.statusBarHeight || 44
    // #endif
    // #ifdef H5
    statusBarHeight.value = 0
    // #endif
})

const fetchLevels = async () => {
    loading.value = true
    try {
        const data = await vipLevels()
        levels.value = data || []
        if (levels.value.length) {
            const recommend = levels.value.find((l: any) => l.is_recommend === 1)
            selectedId.value = recommend ? recommend.id : levels.value[0].id
        }
    } finally {
        loading.value = false
    }
}

const handleSubscribe = async () => {
    if (!currentLevel.value || submitting.value || isCurrentLevel.value) return
    submitting.value = true
    try {
        const res = await vipCreateOrder({ level_id: currentLevel.value.id })
        payState.orderId = res.order_id
        payState.from = res.from
        payState.show = true
    } catch (e: any) {
        uni.$u.toast(e?.msg || '下单失败')
    } finally {
        submitting.value = false
    }
}

const onPaySuccess = () => {
    uni.$u.toast('支付成功，VIP已开通')
    userStore.getUser()
}

const onPayClose = () => {
    // 关闭支付弹窗
}

const goBack = () => uni.navigateBack()

onShow(() => {
    fetchLevels()
    userStore.getUser()
    payState.show = false
    payState.orderId = 0
})
</script>

<style lang="scss" scoped>
.vip-page {
    min-height: 100vh;
    background: #f5f5f5;
    padding-bottom: 180rpx;
}

.vip-header {
    background: linear-gradient(135deg, #202C4F, #34426C);
    padding-bottom: 40rpx;

    &__nav {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 32rpx;
    }

    &__title {
        font-size: 34rpx;
        font-weight: 600;
        color: #f0ad4e;
    }
}

.vip-user {
    display: flex;
    align-items: center;
    padding: 20rpx 32rpx;

    &__avatar {
        width: 128rpx;
        height: 128rpx;
        border-radius: 24rpx;
        flex-shrink: 0;
    }

    &__info {
        margin-left: 24rpx;
        flex: 1;
    }

    &__name {
        font-size: 34rpx;
        font-weight: 600;
        color: #fff;
        display: block;
    }

    &__status-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 8rpx;
    }

    &__status {
        font-size: 24rpx;
        color: #e6e6e6;
    }

    &__remain {
        font-size: 24rpx;
        color: #e6e6e6;
    }
}

.vip-plans {
    margin: -20rpx 24rpx 0;
    background: #fff;
    border-radius: 20rpx;
    padding: 32rpx;
    position: relative;
    z-index: 1;
    box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);

    &__title {
        font-size: 30rpx;
        font-weight: 700;
        color: #1a1a1a;
        margin-bottom: 28rpx;
    }

    &__list {
        display: flex;
        gap: 18rpx;
    }
}

.plan-card {
    flex: 1;
    border: 3rpx solid #eaeaea;
    border-radius: 20rpx;
    padding: 28rpx 16rpx 24rpx;
    text-align: center;
    position: relative;
    transition: all 0.25s ease;
    background: #fafafa;
    overflow: hidden;

    &--active {
        border-color: #005fff;
        background: linear-gradient(180deg, #f0f5ff 0%, #fff 100%);
        box-shadow: 0 6rpx 20rpx rgba(0, 95, 255, 0.15);
    }

    &--hot {
        .plan-card__badge {
            display: flex;
        }
    }

    &__badge {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        background: #005fff;
        color: #fff;
        font-size: 18rpx;
        font-weight: 600;
        padding: 4rpx 14rpx;
        border-radius: 0 18rpx 0 14rpx;
        align-items: center;
    }

    &__check {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 40rpx;
        height: 40rpx;
        background: #005fff;
        border-radius: 0 20rpx 0 18rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &__name {
        font-size: 26rpx;
        color: #333;
        font-weight: 600;
        display: block;
        margin-bottom: 16rpx;
    }

    &__divider {
        width: 40rpx;
        height: 4rpx;
        background: #e0e0e0;
        border-radius: 2rpx;
        margin: 0 auto 16rpx;
    }

    &--active &__divider {
        background: #005fff;
    }

    &__price {
        display: flex;
        align-items: baseline;
        justify-content: center;
        margin-bottom: 4rpx;
    }

    &__symbol {
        font-size: 20rpx;
        color: #005fff;
        font-weight: 700;
        margin-right: 2rpx;
    }

    &__amount {
        font-size: 34rpx;
        font-weight: 800;
        color: #005fff;
        line-height: 1;
    }

    &__duration {
        font-size: 16rpx;
        color: #999;
        display: block;
        margin-top: 6rpx;
    }

    &__avg {
        font-size: 14rpx;
        color: #005fff;
        display: block;
        margin-top: 8rpx;
        opacity: 0.7;
    }

    &--active &__name {
        color: #005fff;
    }
}

.vip-benefits {
    margin: 20rpx 24rpx 0;
    background: #fff;
    border-radius: 24rpx;
    padding: 32rpx;

    &__header {
        display: flex;
        align-items: center;
        margin-bottom: 24rpx;
    }

    &__title {
        font-size: 30rpx;
        font-weight: 700;
        color: #000;
    }

    &__count {
        width: 40rpx;
        height: 40rpx;
        background: #005fff;
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 12rpx;

        text {
            font-size: 24rpx;
            font-weight: 600;
            color: #fff;
        }
    }

    &__list {
        display: flex;
        flex-direction: column;
        gap: 16rpx;
    }

    &__content {
        font-size: 26rpx;
        color: #666;
        line-height: 1.8;
    }
}

.benefit-row {
    display: flex;
    align-items: center;
    background: #e5edff;
    border-radius: 24rpx;
    padding: 16rpx 20rpx;
    gap: 16rpx;

    &__tag {
        background: #4d83ff;
        border-radius: 12rpx;
        padding: 4rpx 16rpx;
        flex-shrink: 0;

        text {
            font-size: 24rpx;
            color: #fff;
            font-weight: 500;
            white-space: nowrap;
        }
    }

    &__desc {
        font-size: 26rpx;
        color: #4d83ff;
        font-weight: 500;
    }
}

.vip-faq {
    margin: 20rpx 24rpx 0;
    background: #fff;
    border-radius: 16rpx;
    padding: 28rpx;

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

.faq-item {
    border-bottom: 1rpx solid #f5f5f5;
    padding: 20rpx 0;

    &:last-child {
        border-bottom: none;
    }

    &__header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    &__q {
        font-size: 26rpx;
        color: #333;
        flex: 1;
    }

    &__answer {
        margin-top: 12rpx;
        font-size: 24rpx;
        color: #999;
        line-height: 1.6;
    }
}

.vip-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 20rpx 32rpx;
    padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
    border-top: 1rpx solid #f0f0f0;
    z-index: 10;

    &__btn {
        background: #0059f0;
        color: #fff;
        text-align: center;
        padding: 24rpx 0;
        border-radius: 64rpx;
        font-size: 30rpx;
        font-weight: 600;

        &--disabled {
            opacity: 0.5;
        }
    }

    &__tip {
        display: block;
        text-align: center;
        font-size: 20rpx;
        color: #ccc;
        margin-top: 12rpx;
    }
}

.vip-benefits-grid {
    margin: -20rpx 24rpx 0;
    background: #fff;
    border-radius: 24rpx;
    padding: 32rpx;
    position: relative;
    z-index: 1;

    &__header {
        display: flex;
        align-items: center;
        margin-bottom: 28rpx;
    }

    &__title {
        font-size: 30rpx;
        font-weight: 700;
        color: #0059f0;
    }

    &__count {
        width: 40rpx;
        height: 40rpx;
        background: #005fff;
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 12rpx;

        text {
            font-size: 24rpx;
            font-weight: 600;
            color: #fff;
        }
    }

    &__list {
        display: flex;
        flex-wrap: wrap;
        gap: 18rpx;
    }
}

.benefit-card {
    width: calc(50% - 9rpx);
    background: #e5edff;
    border-radius: 24rpx;
    padding: 28rpx 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    &__icon {
        width: 128rpx;
        height: 128rpx;
        margin-bottom: 16rpx;
    }

    &__tag {
        background: #4d83ff;
        border-radius: 12rpx;
        padding: 4rpx 16rpx;
        margin-bottom: 12rpx;

        text {
            font-size: 24rpx;
            color: #fff;
            font-weight: 500;
        }
    }

    &__desc {
        font-size: 22rpx;
        color: #4d83ff;
        text-align: center;
    }
}
</style>
