<template>
  <view class="lending-container">
    <!-- 固定只有两个 tab -->
    <view class="tab-sticky">
      <my-tabs
        :tabData="tabData"
        :defaultIndex="currentIndex"
        :config="{ textColor: '#333' }"
        @tabClick="tabClick"
      />
    </view>

    <swiper
      class="swiper"
      :current="currentIndex"
      :style="{ height: currentSwiperHeight + 'px' }"
      @animationfinish="onSwiperEnd"
      @change="onSwiperChange"
    >
      <!-- 在借中 -->
      <swiper-item>
        <view class="list-wrapper">
          <uni-load-more status="loading" v-if="loadingLending" />

          <view class="empty" v-else-if="lendingList.length === 0">
            <uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80"></uni-icons>
            <text style="margin-top: 20px;">暂无在借记录</text>
          </view>

          <lending-list-item
            class="list-item-lending"
            v-for="(item, index) in lendingList"
            :key="index"
            :data="item"
            :is-lending="true"
          />
        </view>
      </swiper-item>

      <!-- 全部（历史借阅） -->
      <swiper-item>
        <view class="list-wrapper">
          <uni-load-more status="loading" v-if="loadingAll" />

          <view class="empty" v-else-if="allList.length === 0">
            <uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80"></uni-icons>
            <text style="margin-top: 20px;">暂无历史借阅记录</text>
          </view>

          <lending-list-item
            class="list-item-all"
            v-for="(item, index) in allList"
            :key="index"
            :data="item"
            :is-lending="false"
          />

          <uni-load-more
            v-if="allList.length > 0 && hasMoreAll"
            :status="loadMoreStatusAll"
          />
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import { FetchInitScreenSetting } from '@/api/user';
import { FetchHistoryloan, FetchRdloanlist, FetchCoverByISBN } from '@/api/book';
import myTabs from "@/components/my-tabs/my-tabs.vue";
import lendingListItem from "@/components/lending-list-item/lending-list-item.vue";
import { getCurrentReaderCard } from '@/utils/storage';
import config from '@/utils/config';
import { loadBookCoversBase64 } from '@/utils/bookCover';

export default {
  components: { myTabs, lendingListItem },
  data() {
    return {
      screenConfig: {},
      tabData: [
        { label: '在借中', status: 'lending' },
        { label: '历史借阅', status: 'all' },
      ],
      currentIndex: 0,

      // 全部（历史）独立数据
      allList: [],
      loadingAll: false,
      pageAll: 1,
      hasMoreAll: true,
      loadMoreStatusAll: '',

      // 在借中 独立数据
      lendingList: [],
      loadingLending: false,

      swiperHeightData: {},
      currentSwiperHeight: 400,
    };
  },

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

  onShow() {
    const tabIndex = uni.getStorageSync('switch_tab_index');
    if (tabIndex !== '') {
      this.currentIndex = Number(tabIndex);
      uni.removeStorageSync('switch_tab_index');
    }
  },

  onPullDownRefresh() {
    if (this.currentIndex === 0) {
      this.getLendingList();
    } else {
      this.getAllList(true);
    }
  },

  onReachBottom() {
    if (this.currentIndex === 0) {
      this.getLendingList();
    } else if (this.currentIndex === 1 && this.hasMoreAll) {
      this.getAllList();
    }
  },

  methods: {
    async getScreenSetting() {
      try {
        const res = await FetchInitScreenSetting({ libcode: config.LIB_CODE });
        const data = res.data;
        this.screenConfig = {
          thirdUrl: data.open_lib_http?.context || '',
          thirdAppid: data.open_lib_appId?.context || '',
          thirdSecret: data.open_lib_secret?.context || '',
          sm4Key: data.sm4_key?.context || ''
        };

        // 默认加载第一个 tab
        this.getLendingList(true);
      } catch (err) {}
    },

    async getAllList(isRefresh = false) {
      if (this.loadingAll) return;
      this.loadingAll = true;

      if (isRefresh) {
        this.pageAll = 1;
        this.allList = [];
        this.hasMoreAll = true;
        this.loadMoreStatusAll = '';
      }

      try {
        // 使用带缓存降级的函数获取读者证
        const currentReaderCard = await getCurrentReaderCard();
        
        const params = {
          ...this.screenConfig,
          rdid: currentReaderCard.bindValue,
          logtype: '30002',
          page: this.pageAll,
          rows: 10,
        };

        const res = await FetchHistoryloan(params);
        const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
        let list = result.hloanlist || [];

        this.allList = [...this.allList, ...list];
        
        // 加载封面
        await this.loadCoversForList(this.allList);
        this.hasMoreAll = list.length === 10;
        this.loadMoreStatusAll = this.hasMoreAll ? '' : 'no-more';

        if (this.hasMoreAll) this.pageAll++;
      } catch (err) {
      } finally {
        this.loadingAll = false;
        uni.stopPullDownRefresh();
        setTimeout(() => {
          this.calcHeight('all');
        }, 100);
      }
    },

    async getLendingList() {
      this.loadingLending = true;
      try {
        // 使用带缓存降级的函数获取读者证
        const currentReaderCard = await getCurrentReaderCard();
        
        const params = {
          ...this.screenConfig,
          rdid: currentReaderCard.bindValue,
        };
        const res = await FetchRdloanlist(params);
        const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
        let list = result.loanlist || [];

        this.lendingList = list.map(item => ({
          ...item,
          loantime: item.loandate || '',
          returntime: item.returndate || '',
        }));
        
        // 加载封面
        await this.loadCoversForList(this.lendingList);
      } catch (err) {
      } finally {
        this.loadingLending = false;
        uni.stopPullDownRefresh();
        setTimeout(() => {
          this.calcHeight('lending');
        }, 100);
      }
    },

    // 加载封面
    async loadCoversForList(list) {
      await loadBookCoversBase64(list, (index, coverUrl) => {
        if (list[index]) {
          this.$set(list[index], 'cover', coverUrl);
        }
      });
    },
    
    // 高度自适应（修复版）
    calcHeight(type) {
      const selector = `.list-item-${type}`;
      const query = uni.createSelectorQuery().in(this);
      
      query.selectAll(selector).boundingClientRect((res) => {
        let totalHeight = 200;
        if (res && res.length > 0) {
          totalHeight = res.reduce((sum, rect) => sum + rect.height, 0);
          totalHeight += res.length * 10 + 40;
        }
        this.swiperHeightData[type] = totalHeight;
        this.currentSwiperHeight = totalHeight + 20;
      }).exec();
    },

    tabClick(index) {
      this.currentIndex = index;
      if (index === 0) {
        if (this.lendingList.length === 0) {
          this.getLendingList();
        } else {
          this.currentSwiperHeight = this.swiperHeightData.lending || 600;
        }
      } else {
        if (this.allList.length === 0) {
          this.getAllList(true);
        } else {
          this.currentSwiperHeight = this.swiperHeightData.all || 600;
        }
      }
    },

    onSwiperChange(e) {
      if (e.detail.source === 'touch') this.currentIndex = e.detail.current;
    },

    onSwiperEnd() {
      this.tabClick(this.currentIndex);
    },
  }
};
</script>

<style lang="scss" scoped>
.lending-container {
  background: #f5f5f5;
  min-height: 100vh;
}
.tab-sticky {
  position: sticky;
  top: 0;
  z-index: 99;
  background: #fff;
}
.swiper {
  width: 100%;
  transition: height 0.2s ease;
}
.list-wrapper {
  padding: 10px;
  box-sizing: border-box;
}

</style>