<template>
	<view style="padding-bottom: 20px;">
		<view class="top-bar">
		  <image class="top-bar-bg" src="@/static/images/mingqi-beij@2x.png" mode="aspectFill"></image>
		  <view class="library-info">
        <image class="avatar" src="@/static/images/avatar.png" mode="aspectFill"></image>
        <view class="library-name">葛店经济技术开发区图书馆</view>
      </view>
      <uni-icons class="search-icon" type="search" size="30" @click="onToSearch"></uni-icons>
		</view>

    <view class="status-cards">
      <view class="status-card" @click="toBorrowPage(1)">
        <view class="status-icon icon-color1" >
          <uni-icons custom-prefix="iconfont" type="icon-daiban02" size="22"></uni-icons>
        </view>
        <view class="status-label">在借中</view>
      </view>
      <view class="status-card" @click="toBorrowPage(2)">
        <view class="status-icon icon-color2" >
          <uni-icons custom-prefix="iconfont" type="icon-zuofei05" size="22"></uni-icons>
        </view>
        <view class="status-label">将过期</view>
      </view>
      <view class="status-card" @click="toBorrowPage(3)">
        <view class="status-icon icon-color3" >
          <uni-icons custom-prefix="iconfont" type="icon-yuqi04" size="22"></uni-icons>
        </view>
        <view class="status-label">已过期</view>
      </view>
      <view class="status-card" @click="toBorrowCar">
        <view class="status-icon icon-color4" >
          <uni-icons custom-prefix="iconfont" type="icon-a-zhidu4" size="22"></uni-icons>
        </view>
        <view class="status-label">借阅清单</view>
      </view>
    </view>

    <swiper class="banner-swiper" interval="3000" circular :vertical="false" :indicator-dots="true" :autoplay="true">
      <swiper-item>
        <image data-post-id="3" src="https://qiniu.aiyxlib.com/1605060269830"></image>
      </swiper-item>
      <swiper-item>
        <image data-post-id="4" src="https://qiniu.aiyxlib.com/1605060269830"></image>
      </swiper-item>
    </swiper>

    <!-- circular -->
    <swiper class="menu-swiper" interval="6000"  :vertical="false" :indicator-dots="true" :autoplay="false">
      <swiper-item>
        <view class="menu-grid">
          <view class="menu-item"  @click="onToSearch">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-ziyuan" size="22"></uni-icons>
            </view>
            <view class="menu-label">书目检索</view>
          </view>
          <view class="menu-item"  @click="onToScan">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-saomajieshu1" size="22"></uni-icons>
            </view>
            <view class="menu-label">扫码借书</view>
          </view>
          <view class="menu-item">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-z_renew_normal" size="24"></uni-icons>
            </view>
            <view class="menu-label">图书续借</view>
          </view>
          <view class="menu-item" >
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-guanwaizhuanjie1" size="26"></uni-icons>
            </view>
            <view class="menu-label">图书转借</view>
          </view>
          <view class="menu-item" @click="toRanking">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-paihangbang" size="22"></uni-icons>
            </view>
            <view class="menu-label">借阅排行</view>
          </view>
          <view class="menu-item" @click="toActivityList">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-remenhuodong" size="26"></uni-icons>
            </view>
            <view class="menu-label">活动报名</view>
          </view>
          <view class="menu-item" @click="toFeedback">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-duzheliuyan" size="26"></uni-icons>
            </view>
            <view class="menu-label">读者留言</view>
          </view>
          <view class="menu-item" @click="toLibraryCard">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-duzhezheng" size="26"></uni-icons>
            </view>
            <view class="menu-label">电子证</view>
          </view>
        </view>
      </swiper-item>
      <swiper-item>
        <view class="menu-grid">
          <view class="menu-item">
            <view class="menu-icon">
              <uni-icons custom-prefix="iconfont" type="icon-yonghuxinxi-gerenxinxi" size="20"></uni-icons>
            </view>
            <view class="menu-label">个人中心</view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 借阅证区域：登录后隐藏 -->
    <view class="library-card-section" @click="toCheckLogin" v-if="!isBindLibraryCard">
      <view class="section-title">借阅证</view>
        <image class="card-icon" src="@/static/images/card-img2.png"></image>
        <view class="card-tip">您还没有绑定读者证哦～</view>
      <button class="bind-btn">立即绑定</button>
    </view>

    <view class="recommendation-section">
      <view class="section-title">
        <text class="left-txt">图书推荐</text>
        <view class="more-link" @click="getMoreBoook">
          <text style="margin-right: 5px;">查看更多</text>
          <uni-icons custom-prefix="iconfont" type="icon-gengduo" size="12"></uni-icons>
        </view>
      </view>
      <view class="recommendation-list">
        <uni-load-more status="loading" v-if="isLoading"></uni-load-more>
        <view v-else class="book-item" v-for="(item,index) in recommendedBooks" @click="goToBookDetail(item)" :key="index" >
          <image class="book-cover" :src="item.cover"></image>
          <view class="book-title">{{item.title}}</view>
        </view>
      </view>
    </view>
    
	</view>
</template>

<script>
export default {
	data() {
		return {
			isLoading: true,
			recommendedBooks: [],
      token: "",
      userInfo: {},
      isBindLibraryCard: false // 标记是否已登录/绑定借阅证
		};
	},
  onLoad() {
    this.getRecommendBooks();
    this.checkLoginStatus(); // 页面加载检查登录状态
  },
  // 页面显示时刷新状态（从登录页返回时生效）
  onShow() {
    this.checkLoginStatus();
  },
  methods:{
    // 检查登录状态，控制借阅证区域显示隐藏
    checkLoginStatus() {
      this.loadUser();
      // 如果有 token，说明已登录 → 隐藏借阅证提示
      this.isBindLibraryCard = !!this.token;
    },
    
    getRecommendBooks() {
      setTimeout(() => {
        this.recommendedBooks = [
          {
            isbn: '9787544741110',
            title: '人工智能基础——数学知识',
            cover: 'https://qiniu.aiyxlib.com/1606124577077'
          },
          {
            isbn: '9787539938032',
            title: 'Vim 8文本处理实战',
            cover: 'https://qiniu.aiyxlib.com/1606178450151'
          },
          {
            isbn: '9787536692930',
            title: 'Oracle从入门到精通',
            cover: 'https://qiniu.aiyxlib.com/1606123986028'
          }
        ];
        this.isLoading = false;
      }, 1200);
    },

    goToBookDetail(item) {
      console.log('item',item)
      uni.navigateTo({
        url: "/subpkg/pages/book-detail/book-detail?isbn=" + item.isbn
      })
    },
    getMoreBoook(){
      uni.navigateTo({
        url: "/subpkg/pages/book-list/book-list"
      })
    },
    onToSearch() {
      uni.switchTab({
        url: "/pages/search/search"
      });
    },
    // 统一读取用户信息
    loadUser() {
      this.token = uni.getStorageSync("token") || ""
      this.userInfo = uni.getStorageSync("user-info") || {}
    },

    toCheckLogin(pageName) {
      this.loadUser();
      if (!this.token) {
        uni.getUserProfile({
          desc: "绑定读者证",
          success: (res) => {
            const userInfo = JSON.parse(res.rawData);
            uni.setStorageSync("wxUserInfo", userInfo);
            uni.setStorageSync("wxSignature", res.signature);
            
            uni.navigateTo({
              url: "/pages/login/login"
            });
          },
          fail: () => {
            uni.showToast({ title: "授权失败", icon: "error" });
          }
        });
        return
      }
    },
    toRanking(){
      uni.navigateTo({
        url: "/subpkg/pages/ranking/ranking"
      })
    },
    toActivityList(){
      uni.navigateTo({
        url: "/subpkg/pages/activity-list/activity-list"
      })
    },
    toBorrowPage(index) {
      uni.setStorageSync('switch_tab_index', index);
      uni.navigateTo({
        url: '/subpkg/pages/myLending/myLending'
      });
    },
    toBorrowCar() {
      uni.switchTab({
        url: '/pages/lendCar/lendCar'
      });
    },
    toFeedback() {
      uni.navigateTo({
        url: '/subpkg/pages/feedback-list/feedback-list'
      });
    },
    toLibraryCard(){
      uni.navigateTo({
        url: '/subpkg/pages/reader-card/reader-card'
      });
    },
    onToScan() {
      // 调用微信扫码
      uni.scanCode({
        onlyFromCamera: true,  // 只允许相机扫码
        scanType: ['barCode'], // 只扫图书条形码（ISBN）
        success: (res) => {
          uni.showToast({
            title: '扫码结果：'+ res.result,
            icon: 'none'
          })
          console.log('扫码结果：', res.result)
          
          // 获取真实ISBN
          let isbn = res.result || ''
          
          // ===== 测试模式：没有扫到真实图书，用测试ISBN =====
          if (!isbn || isbn.length < 10) {
            isbn = '9787020167319' // 活着 余华
          }

          // 跳转到图书详情页
          uni.navigateTo({
            url: '/subpkg/pages/book-detail/book-detail?isbn=' + isbn
          })
        },
        fail: (err) => {
          console.log('扫码失败：', err)
          uni.showToast({
            title: '扫码取消或失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.top-bar{
  .search-icon{
    position: absolute;
    right: 16px;
    top: 15px;
    z-index: 22;
    ::v-deep .uni-icons{
     color: #fff !important;
    }
  }
}

.status-cards {
  display: flex;
  background-color: $uni-white;
  margin: 10px;
  border-radius: 8px;
  padding: 20px 10px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  .status-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .status-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
    margin-bottom: 6px;
    border-radius: 50%;
  }
  .icon-color1{
    background-color: #e4f2ff;
  }
  .icon-color2{
    background-color: #ffeff0;
  }
  .icon-color3{
    background-color: #e4fff4;
  }
  .icon-color4{
    background-color: #fef8e2;
  }
  .status-label {
    font-size: 12px;
    color: $uni-main-color;
  }
}

swiper.banner-swiper{
  width: 100%;
  height: 130px;
}
swiper.banner-swiper image{
  width: 100%;
  height: 130px;
}
swiper.menu-swiper{
  width:100%;
  margin-top: 10px;
  background-color: $uni-white;
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  .menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 0;
    .menu-icon{
      display: flex;
      flex-direction: column;
      justify-content: center;
      height: 30px;
      ::v-deep .uni-icons{
        color: #01a4fe !important;
      }
    }
    .menu-label {
      font-size: 12px;
      color: $uni-main-color;
      text-align: center;
    }
  }
}

.library-card-section {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 20px 0;
  .section-title {
    font-size: 22px;
    font-weight: bold;
    background: linear-gradient(140deg, #01a4ff, #2ec8fe);
    -webkit-background-clip: text;
    color: transparent;
    letter-spacing: 0.1em;
    margin-bottom: 5px;
  }
  .card-icon {
    width: 80px;
    height: 80px;
  }
  .card-tip {
    font-size: 12px;
    color: $uni-secondary-color;
    margin: 5px 0;
  }
  .bind-btn {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border: 1px solid #06a8ff ;
    width: 128px !important;
    height: 28px;
    border-radius: 28px;
    background: linear-gradient(140deg, #01a4ff, #2ec8fe);
    font-size: 14px;
    color: $uni-white;
    line-height: 28px;
  }
}

.recommendation-section {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 0 0 10px 0;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  .section-title{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    padding: 0 10px;
    .left-txt{
      color: #343434;
      font-size: 15px;
      font-weight: 700;
    }
    .more-link{
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      color: $uni-base-color;
      font-size: 11px;
    }
  }

}
</style>