<template>
    <div class="intimacy-ranking-container">
        <div class="ranking-header">
            <div class="crown-wrapper">
                <img src="@/assets/images/crown.png" alt="皇冠" class="crown-icon">
            </div>
            <div class="title-wrapper">
                <span class="header-title">读者亲密值榜单</span>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="6" animated>
                <template #template>
                    <div v-for="i in 6" :key="i" style="display: flex; margin-bottom: 20px; align-items: center;">
                        <el-skeleton-item variant="rect" style="width: 50px; height: 100px; margin-right: 15px;" />
                        <el-skeleton-item variant="circle" style="width: 36px; height: 36px; margin-right: 12px;" />
                        <div style="flex: 1;">
                            <el-skeleton-item variant="text" style="width: 40%; margin-bottom: 8px;" />
                            <el-skeleton-item variant="text" style="width: 30%; margin-bottom: 6px;" />
                            <el-skeleton-item variant="text" style="width: 50%;" />
                        </div>
                    </div>
                </template>
            </el-skeleton>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-container">
            <el-empty description="加载失败">
                <el-button type="primary" size="small" @click="fetchRankingData">重新加载</el-button>
            </el-empty>
        </div>
        
        <!-- 排行榜列表 -->
        <div v-else-if="!loading && rankingList.length > 0" class="ranking-list">
            <div v-for="(item, index) in rankingList.slice(0, 10)" :key="item.id || index" class="ranking-item">
                <div class="rank-side-bg" :class="`rank-color-${index + 1}`">
                    <span class="rank-num">{{ index + 1 }}</span>
                </div>
                
                <div class="item-content">
                    <div class="user-avatar">
                        <img :src="getBadgeImage(item)" alt="">
                    </div>
                    
                    <div class="user-info">
                        <div class="username">
                            <img :src="getUserAvatar(item)" alt="徽章" class="badge-img">
                            <span class="user-name">{{ getUserName(item) }}</span>
                        </div>
                        <div class="badge-wrap">
                            <div class="level-badge">
                                <span class="level-text">{{ getUserLevel(item, index) }}级</span>
                            </div>
                        </div>
                        <div class="intimacy-value">
                            {{ formatNumber(getIntimacyValue(item)) }} <span class="value-label">亲密值</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 无数据状态 -->
        <div v-else-if="!loading && !error" class="no-data">
            <el-empty description="暂无排行榜数据" />
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { homeApi } from '@/api/home.js';

export default defineComponent({
    name: 'IntimacyRanking',
    props: {
        bookId: {
            type: String,
            required: true
        }
    },
    setup(props) {
        // 响应式数据
        const loading = ref(true);
        const error = ref(false);
        const rankingList = ref([]);
        const pageNo = ref(1);
        const pageSize = ref(10);

        // 默认头像
        const defaultAvatar = ref('@/assets/images/center/headImage.png');

        // 获取排行榜数据
        const fetchRankingData = async () => {
            if (!props.bookId) {
                loading.value = false;
                return;
            }

            try {
                loading.value = true;
                error.value = false;

                const response = await homeApi.getIntimacyRankList({
                    bookId: props.bookId,
                    pageNo: pageNo.value,
                    pageSize: pageSize.value
                });

                if (response && response.success) {
                    const result = response.result;
                    if (result && result.records) {
                        rankingList.value = result.records;
                    } else if (Array.isArray(result)) {
                        rankingList.value = result;
                    } else {
                        rankingList.value = [];
                    }
                } else {
                    throw new Error(response?.message || '获取排行榜数据失败');
                }
            } catch (err) {
                console.error('获取亲密度排行榜失败:', err);
                error.value = true;
                ElMessage.error(err.message || '获取排行榜数据失败');
            } finally {
                loading.value = false;
            }
        };

        // 获取用户头像
        const getUserAvatar = (item) => {
            return item.headImage || item.hanHaiMember?.headImage || defaultAvatar.value;
        };

        // 获取用户名
        const getUserName = (item) => {
            return item.nickName || item.hanHaiMember?.nickName || '匿名用户';
        };

        // 获取用户等级
        const getUserLevel = (item, index) => {
            // 如果API返回了等级信息就使用，否则根据排名计算
            if (item.commonBookAchievement) {
                return item.commonBookAchievement.oldName || item.commonBookAchievement.title;
            }
            
            // 根据排名生成等级
            if (index === 0) return '五';
            if (index === 1) return '五';
            if (index === 2) return '四';
            if (index < 5) return '三';
            if (index < 7) return '二';
            return '一';
        };

        // 获取亲密值
        const getIntimacyValue = (item) => {
            return item.num || 0;
        };
        
        // 格式化数字显示
        const formatNumber = (num) => {
            if (!num) return '0';
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        };
        
        // 根据排名获取不同的徽章图片
        const getBadgeImage = (item) => {
            return item.icon || item.avatar || item.hanHaiMember?.headImage || defaultAvatar.value;
        };

        // 监听bookId变化
        watch(() => props.bookId, (newBookId) => {
            if (newBookId) {
                fetchRankingData();
            }
        }, { immediate: true });

        onMounted(() => {
            if (props.bookId) {
                fetchRankingData();
            }
        });

        return {
            loading,
            error,
            rankingList,
            fetchRankingData,
            getUserAvatar,
            getUserName,
            getUserLevel,
            getIntimacyValue,
            formatNumber,
            getBadgeImage
        };
    }
});
</script>

<style lang="scss" scoped>
.intimacy-ranking-container {
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
    overflow: hidden;
    padding: 0 15px 15px;
    
    .ranking-header {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px 0 15px;
        position: relative;
        
        .crown-wrapper {
            margin-bottom: 8px;
            
            .crown-icon {
                width: 40px;
                height: 40px;
                display: block;
            }
        }
        
        .title-wrapper {
            .header-title {
                font-size: 18px;
                font-weight: bold;
                color: #333;
                line-height: 1.4;
            }
        }
    }

    // 加载和错误状态样式
    .loading-container,
    .error-container,
    .no-data {
        padding: 30px 20px;
        text-align: center;
    }

    .loading-container {
        .el-skeleton {
            text-align: left;
        }
    }

    .ranking-list {
        display: flex;
        flex-direction: column;
        gap: 20px;
        
        .ranking-item {
            position: relative;
            border-radius: 10px;
            overflow: hidden;
            background-color: #fff;
            display: flex;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            
            .rank-side-bg {
                width: 50px;
                height: 100px;
                display: flex;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
                
                .rank-num {
                    font-size: 22px;
                    font-weight: 600;
                    color: #986514;
                }
                
                &.rank-color-1 {
                    background-color: #FFEECC;
                }
                
                &.rank-color-2 {
                    background-color: #E9ECEF;
                    .rank-num {
                        color: #777;
                    }
                }
                
                &.rank-color-3 {
                    background-color: #FFE7E0;
                    .rank-num {
                        color: #A05E2B;
                    }
                }
                
                &.rank-color-4, &.rank-color-5, &.rank-color-6, 
                &.rank-color-7, &.rank-color-8, &.rank-color-9, &.rank-color-10 {
                    background-color: #F8F8F8;
                    .rank-num {
                        color: #999;
                    }
                }
            }
            
            .item-content {
                flex: 1;
                display: flex;
                padding: 10px 15px;
                align-items: center;
                
                .user-avatar {
                    width: 36px;
                    height: 36px;
                    border-radius: 50%;
                    overflow: hidden;
                    margin-right: 12px;
                    
                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                        border-radius: 50%;
                    }
                }
                
                .user-info {
                    flex: 1;
                    text-align: center;
                    
                    .username {
                        font-size: 15px;
                        color: #333;
                        font-weight: 500;
                        margin-bottom: 4px;
                        display: flex;
                        align-items: center;
                        width: 100%;
                        
                        .badge-img {
                            width: 20px;
                            height: 20px;
                            border-radius: 50%;
                            margin-right: 6px;
                            flex-shrink: 0;
                        }
                        
                        .user-name {
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            width: 105px;
                        }
                    }
                    
                    .badge-wrap {
                        margin-bottom: 3px;
                        
                        .level-badge {
                            display: inline-flex;
                            align-items: center;
                            background-color: #F0E6FF;
                            border-radius: 15px;
                            padding: 2px 8px;
                            
                            .level-text {
                                color: #9B72FF;
                                font-size: 12px;
                            }
                        }
                    }
                    
                    .intimacy-value {
                        font-size: 13px;
                        color: #888;
                        
                        .value-label {
                            color: #999;
                        }
                    }
                }
            }
        }
    }
}
</style>