<template>
    <view class="container">
        <!-- 自定义头部 -->
        <view class="custom-header">
            <view class="header-left" @click="navBack">
                <image class="back-icon" src="/static/icons/chevron_right_dark.svg" style="transform: rotate(180deg);"></image>
            </view>
            <text class="header-title">履约者等级权益</text>
            <view class="header-right"></view>
        </view>
        <view class="header-placeholder"></view>

        <!-- 等级 Swiper -->
        <view class="swiper-container" v-if="!pageLoading">
            <swiper 
                class="level-swiper" 
                previous-margin="80rpx" 
                next-margin="80rpx" 
                :current="currentIndex"
                @change="swiperChange">
                <swiper-item v-for="(level, index) in processedLevels" :key="index" @click="changeLevel(index)">
                    <view class="level-card" :style="{ 
                        transform: currentIndex === index ? 'scale(1)' : 'scale(0.9)',
                        backgroundImage: 'url(' + level.backgroundUrl + ')',
                        backgroundSize: 'cover',
                        backgroundPosition: 'center'
                    }">
                        <view class="card-content">
                            <view class="card-header">
                                <view class="level-badge">L{{ index + 1 }}</view>
                                <view class="current-badge" v-if="level.isCurrent">当前等级</view>
                            </view>
                            <text class="level-name">{{ level.name }}</text>
                            <text class="level-score">所需积分: {{ level.upgradePoints || 0 }}</text>
                            <!-- Crown graphic overlay -->
                            <image class="crown-overlay" src="/static/icons/crown.svg" mode="aspectFit"></image>
                        </view>
                    </view>
                </swiper-item>
            </swiper>
            <!-- 自定义指示点 -->
            <view class="swiper-dots">
                <view 
                    class="dot" 
                    v-for="(item, index) in processedLevels" 
                    :key="index"
                    :class="{ active: currentIndex === index }">
                </view>
            </view>
        </view>

        <!-- 权益标题 -->
        <view class="benefits-title-row" v-if="!pageLoading && currentLevel">
            <text class="benefits-title">专属权益</text>
            <text class="benefits-count">({{ currentLevel.benefits ? currentLevel.benefits.length : 0 }})</text>
        </view>

        <!-- 权益列表 -->
        <view class="benefits-grid" v-if="!pageLoading && currentLevel">
            <view 
                class="benefit-item" 
                v-for="(benefit, index) in currentLevel.benefits" 
                :key="index"
                @click="showBenefitDetail(benefit)">
                <view class="benefit-icon-wrapper">
                    <image class="benefit-icon" :src="benefit.iconUrl" mode="aspectFit" v-if="benefit.iconUrl"></image>
                    <view class="benefit-icon-placeholder" v-else>{{ benefit.name[0] }}</view>
                </view>
                <text class="benefit-name">{{ benefit.name }}</text>
            </view>
            <view class="empty-benefits" v-if="!currentLevel.benefits || currentLevel.benefits.length === 0">
                <text>该等级暂无特殊权益</text>
            </view>
        </view>

        <!-- 权益详情弹窗 -->
        <view class="popup-mask" :class="{ 'show': isPopupShow }" @click="closePopup" @touchmove.stop.prevent>
            <view class="popup-modal" @click.stop>
                <view class="popup-icon-wrapper">
                     <image class="benefit-icon-large" :src="currentBenefit.iconUrl" mode="aspectFit" v-if="currentBenefit && currentBenefit.iconUrl"></image>
                     <view class="benefit-icon-placeholder-large" v-else>{{ currentBenefit ? currentBenefit.name[0] : '' }}</view>
                </view>
                <text class="popup-title">{{ currentBenefit ? currentBenefit.name : '' }}</text>
                <text class="popup-desc">{{ currentBenefit ? currentBenefit.statement : '' }}</text>
                <button class="popup-btn" @click="closePopup">我知道了</button>
            </view>
        </view>

    </view>
</template>

<script>
import { getMyProfile } from '@/api/fulfiller/fulfiller'
import { listAllLevelConfigs } from '@/api/fulfiller/levelConfig'
import { listAllLevelRights } from '@/api/fulfiller/levelRights'

export default {
    data() {
        return {
            currentIndex: 0,
            profile: null,
            levels: [], // 从后端获取的等级配置
            rightsList: [], // 从后端获取的所有权益列表
            isPopupShow: false,
            currentBenefit: null,
            pageLoading: true
        }
    },
    computed: {
        currentLevel() {
            return this.processedLevels[this.currentIndex];
        },
        // 合并等级与对应的权益详细信息
        processedLevels() {
            if (!this.levels.length) return [];
            return this.levels.map(lvl => {
                // 筛选出属于该等级的权益
                const benefits = (lvl.rights || []).map(rightId => {
                    return this.rightsList.find(r => r.id === rightId)
                }).filter(Boolean); // 过滤掉未找到的

                return {
                    ...lvl,
                    isCurrent: this.profile && this.profile.level === lvl.lvNo,
                    benefits: benefits
                }
            }).sort((a,b) => a.lvNo - b.lvNo); // 确保按级别排序
        }
    },
    async onLoad() {
        await this.initData();
    },
    methods: {
        async initData() {
            this.pageLoading = true;
            uni.showLoading({ title: '加载中...' });
            try {
                // 并行加载个人信息、等级配置、权益列表
                const [profileRes, levelsRes, rightsRes] = await Promise.all([
                    getMyProfile(),
                    listAllLevelConfigs(),
                    listAllLevelRights()
                ]);

                this.profile = profileRes.data;
                this.levels = levelsRes.data || [];
                this.rightsList = rightsRes.data || [];

                // 默认定位到用户当前等级
                if (this.profile) {
                    const idx = this.processedLevels.findIndex(lvl => lvl.lvNo === this.profile.level);
                    if (idx !== -1) {
                        this.currentIndex = idx;
                    }
                }
            } catch (err) {
                console.error('初始化等级页面失败:', err);
                uni.showToast({ title: err.message || err.msg || '请求失败', icon: 'none' });
            } finally {
                this.pageLoading = false;
                uni.hideLoading();
            }
        },
        navBack() {
             uni.navigateBack();
        },
        swiperChange(e) {
            this.currentIndex = e.detail.current;
        },
        changeLevel(index) {
            this.currentIndex = index;
        },
        showBenefitDetail(benefit) {
            this.currentBenefit = benefit;
            this.isPopupShow = true;
        },
        closePopup() {
            this.isPopupShow = false;
        }
    }
}
</script>

<style>
page {
    background-color: #fff;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
.custom-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88rpx;
    padding-top: var(--status-bar-height);
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 30rpx;
    padding-right: 30rpx;
    box-sizing: border-box;
    z-index: 100;
}
.header-placeholder {
    height: calc(88rpx + var(--status-bar-height));
}
.back-icon {
    width: 40rpx;
    height: 40rpx;
}
.header-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}
.header-right {
    width: 40rpx;
}

.swiper-container {
    position: relative;
    padding-bottom: 30rpx;
}
.level-swiper {
    height: 360rpx;
    margin-top: 20rpx;
}
.level-card {
    height: 320rpx; 
    border-radius: 30rpx;
    margin: 0 10rpx;
    transition: transform 0.3s;
    overflow: hidden;
    position: relative;
    box-shadow: 0 10rpx 20rpx rgba(0,0,0,0.1);
    background-color: #eee;
}

.card-content {
    padding: 30rpx;
    position: relative;
    z-index: 2;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: auto;
}
.level-badge {
    background: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.6);
    padding: 2rpx 12rpx;
    border-radius: 10rpx;
    font-size: 24rpx;
    color: #fff;
}
.current-badge {
    background-color: rgba(255,255,255,0.9);
    color: #333;
    font-size: 20rpx;
    padding: 4rpx 12rpx;
    border-radius: 20rpx;
    font-weight: bold;
}
.level-name {
    font-size: 44rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 10rpx;
    text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.2);
}
.level-score {
    font-size: 24rpx;
    color: rgba(255,255,255,0.9);
    margin-bottom: 20rpx;
}
.crown-overlay {
    position: absolute;
    bottom: -30rpx;
    right: -30rpx;
    width: 260rpx;
    height: 260rpx;
    opacity: 0.15;
    z-index: 1;
}

.swiper-dots {
    display: flex;
    justify-content: center;
    margin-top: 10rpx;
}
.dot {
    width: 12rpx;
    height: 12rpx;
    background-color: #E0E0E0;
    border-radius: 50%;
    margin: 0 6rpx;
    transition: all 0.3s;
}
.dot.active {
    width: 24rpx;
    background-color: #333;
    border-radius: 6rpx;
}

.benefits-title-row {
    padding: 20rpx 30rpx;
    display: flex;
    align-items: baseline;
}
.benefits-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}
.benefits-count {
    font-size: 28rpx;
    color: #999;
    margin-left: 10rpx;
}

.benefits-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20rpx;
}
.benefit-item {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
}
.benefit-icon-wrapper {
    width: 88rpx;
    height: 88rpx;
    background-color: #F8F8F8;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12rpx;
}
.benefit-icon {
    width: 44rpx;
    height: 44rpx;
}
.benefit-name {
    font-size: 22rpx;
    color: #666;
    text-align: center;
}

.empty-benefits {
    width: 100%;
    padding: 60rpx 0;
    text-align: center;
    color: #ccc;
    font-size: 26rpx;
}

.popup-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 999;
    display: none;
    align-items: center;
    justify-content: center;
}
.popup-mask.show {
    display: flex;
}
.popup-modal {
    width: 520rpx;
    background-color: #fff;
    border-radius: 30rpx;
    padding: 50rpx 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 10rpx 40rpx rgba(0,0,0,0.2);
}
.popup-icon-wrapper {
    width: 120rpx;
    height: 120rpx;
    background-color: #FFF8E1; 
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
}
.benefit-icon-large {
    width: 60rpx;
    height: 60rpx;
}
.popup-title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
}
.popup-desc {
    font-size: 28rpx;
    color: #666;
    text-align: center;
    line-height: 1.6;
    margin-bottom: 40rpx;
}
.popup-btn {
    width: 90%;
    height: 80rpx;
    line-height: 80rpx;
    background: linear-gradient(90deg, #333 0%, #111 100%);
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
}
</style>
