<template>
	<view>
		<view class="ranking-header">
      <image
       class="ranking-heander-bg"
        src="@/static/images/ranking-bg.png"
        mode="aspectFill"
      />
      <view class="ranking-header-txt">
        <view class="ranking-title">
          <uni-icons custom-prefix="iconfont" type="icon-paihangbang2" size="20"></uni-icons>
          <text class="title-text">读者借阅排行</text>
        </view>
        <text class="ranking-header-tip">由本图书馆近30天读者借阅次数生成排行榜单</text>
      </view>
    </view>

    <view class="ranking-list">
      <!-- 加载中状态 -->
      <view class="loading" v-if="loading">
        <uni-icons type="loading" size="40" color="#01a4fe" spin></uni-icons>
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty" v-else-if="rankingData.length === 0">
        <uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80" color="#ccc"></uni-icons>
        <text style="margin-top: 20px;">暂无读者排行数据</text>
      </view>

      <view 
        class="ranking-item" 
        :class="[
          index === 0 ? 'first-item' : '',
          index === 1 ? 'two-item' : '',
          index === 2 ? 'three-item' : ''
        ]"
        v-for="(item, index) in rankingData" 
        :key="index"
        v-else
      >
        <!-- 第一名 -->
        <uni-icons class="ranking-icon" v-if="index === 0" custom-prefix="iconfont" type="icon-TOP2" size="26" color="#E6CB97"></uni-icons>
        <!-- 第二名 -->
        <uni-icons class="ranking-icon" v-if="index === 1" custom-prefix="iconfont" type="icon-TOP" size="26" color="#a2b2c3"></uni-icons>
        <!-- 第三名 -->
        <uni-icons class="ranking-icon" v-if="index === 2" custom-prefix="iconfont" type="icon-TOP1" size="26" color="#D0BA9D"></uni-icons>
        <!-- 4~10名 显示数字 -->
        <view  v-if="index >= 3" class="ranking-common-icon"> 
          <uni-icons custom-prefix="iconfont" type="icon-tag" size="28" color="#8899ab"></uni-icons>
          <text class="common-num">{{ index + 1 }}</text>
        </view>
         <!-- 书籍封面 -->
        <view class="ranking-item-img">
          <image
            class="book-cover"
            :src="item.cover || defaultCover"
            mode="scaleToFill"
            @error="onImgError"
          />
        </view>

        <!-- 书籍信息 -->
        <view class="ranking-book-info">
          <text class="book-info-title">{{ item.TITLE || '暂无书名' }}</text>
          <text class="book-info-name">{{ item.AUTHOR || '佚名' }}</text>
          <text class="book-info-desc line-clamp-3">
            借阅次数：{{ item.TOTALNUM || 0 }} 次
          </text>
        </view>
      </view>
    </view>
	</view>
</template>



<script>
import { FetchInitScreenSetting } from '@/api/user';
import { FetchBookRanking } from '@/api/book';
import config from '@/utils/config';

export default {
	data() {
		return {
      rankingData: [],
      defaultCover: '/static/images/default-book.png',
      loading: true,
		};
	},

  onLoad() {
    this.getScreenSetting();
  },

  methods: {
    async getScreenSetting() {
      try {
        const res = await FetchInitScreenSetting({ libcode: config.LIB_CODE });
        this.getReadRanking(res.data);
      } catch (err) {
        console.error('获取屏幕配置失败：', err);
      }
    },

    getFormattedDate(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    },

    getReadRanking(result) {
      const currentDate = new Date()
      currentDate.setDate(currentDate.getDate() - 30)
      const year = currentDate.getFullYear()
      const month = currentDate.getMonth() + 1
      const day = currentDate.getDate()
      const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`

      const params = {
        'libcode': 'GD',
        'starttime': formattedDate,
        'endtime': this.getFormattedDate(new Date()),
        'rownum': 10,
        'thirdAppid': result.open_lib_appId?.context || '',
        'thirdSecret': result.open_lib_secret?.context || '',
        'thirdUrl': result.open_lib_http?.context || ''
      }

      FetchBookRanking(params).then(res => {
        // console.log('排行接口返回数据', res)
        const innerStr = res.data;
        const resultJson = JSON.parse(innerStr);
        // console.log(resultJson)

        if (resultJson.success && resultJson.resultlist.length > 0) {
          // 按借阅次数降序
          this.rankingData = resultJson.resultlist.sort((a, b) => b.TOTALNUM - a.TOTALNUM);
        } else {
          this.rankingData = [];
        }
        this.loading = false;
      }).catch(error => {
        console.error('排行接口错误', error)
        this.rankingData = [];
        this.loading = false;
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ranking-header{
  position: relative;
  width: 100%;
  height: 150px;
  .ranking-heander-bg{
    width: 100%;
    height: 100%;
  }
  .ranking-header-txt{
    position: absolute;
    top: 0;
    left: 0;
    height: 150px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    .ranking-title{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      font-size: 26px;
      font-weight: bold;
      color: #1a1a1a;
      ::v-deep .uni-icons{
        color: #01a4fe !important;
      }
      .title-text{
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.15),
                    0 1px 2px rgba(0, 0, 0, 0.1);
        letter-spacing: 1px;
        margin-left: 8px;
      }
    }
    .ranking-header-tip,
    .ranking-num{
      color: #333;
      font-size: 14px;
      padding-top: 15px;
    }
  }
}
.ranking-list{
  position: relative;
  background-color: #fff;
  border-radius: 26px 26px 0 0;
  margin-top: -30px;
  z-index: 999;
  padding: 20px 0;
  min-height: 60vh;
}

/* 加载中状态 */
.loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 50vh;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 空状态 */
.empty {
  height: 50vh;
}

.ranking-item{
  position: relative;
  display: flex;
  justify-content: space-between;
  margin: 30px 20px 0 20px;
  padding: 10px;
  background-color: #f7f8fc;
  border-radius: 6px;
  .ranking-item-img{
    margin-right: 10px;
    .book-cover{
      width: 100px;
      height: 150px;
      border-radius: 10px;
      padding: 0 10px;
      background-color: #fff;
    }
  }
  .ranking-book-info{
    flex: 1;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    color: #666;
    .book-info-title{
      font-size: 16px;
      font-weight: bold;
      color: #000;
      padding-top: 10px;
    }
    .book-info-name,
    .book-info-desc{
      padding-top: 10px;
      line-height: 24px;
    }
  }
  &.first-item{
    background-color: #fBF0BB;
  }
  &.two-item{
    background-color: #e9eff6;
  }
   &.three-item{
    background-color: #fBF0BB;
  }
  .ranking-icon{
    position: absolute;
    right: 10px;
    top: -10px;
  }
  .ranking-common-icon{
    position: absolute;
    right: 10px;
    top: -4px;
    .common-num{
      position: absolute;
      left: 0;
      top: 0;
      width: 28px;
      height: 28px;
      text-align: center;
      color: #fff;
    }
  }
}
</style>