<template>
  <view class="novel-home">
    <!-- 顶部导航栏 -->
    <view class="header">
      <image src="/static/logo.png" class="logo" />
      <view class="search-box" @click="goToSearch">
        <uni-icons type="search" size="18" color="#999" />
        <text class="placeholder">搜索书名或作者</text>
      </view>
      <view class="user-icon" @click="goToUserCenter">
        <uni-icons type="person" size="24" color="#333" />
      </view>
    </view>
    
    <!-- 轮播图 -->
    <swiper class="banner" :autoplay="true" :interval="3000" circular>
      <swiper-item v-for="(item, index) in banners" :key="index">
        <image :src="item.image" mode="aspectFill" @click="readNovel(item.novelId)" />
      </swiper-item>
    </swiper>
    
    <!-- 分类导航 -->
    <view class="category-nav">
      <view v-for="category in categories" :key="category.id" class="nav-item">
        <image :src="category.icon" class="nav-icon" />
        <text>{{ category.name }}</text>
      </view>
    </view>
    
    <!-- 推荐书单 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">编辑推荐</text>
        <text class="more" @click="goToBookList">更多 ></text>
      </view>
      <scroll-view scroll-x class="book-list">
        <view v-for="book in recommendedBooks" :key="book.id" class="book-item" @click="readNovel(book.id, 1)">
          <image :src="book.cover" class="book-cover" />
          <text class="book-title">{{ book.title }}</text>
          <text class="book-author">{{ book.author }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 热门连载 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">热门连载</text>
      </view>
      <view v-for="book in serialBooks" :key="book.id" class="book-row" @click="readNovel(book.id, 1)">
        <image :src="book.cover" class="row-cover" />
        <view class="book-info">
          <text class="row-title">{{ book.title }}</text>
          <text class="row-author">{{ book.author }}</text>
          <text class="row-desc">{{ book.description }}</text>
          <view class="row-tags">
            <text v-for="tag in book.tags" :key="tag" class="tag">{{ tag }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 阅读登录提示组件 -->
    <login-prompt v-if="showLoginPrompt" @login="goToLogin" @continue="continueReading" />
  </view>
</template>
<script>
	import novelService from '@/services/novelService'
	
export default {
  data() {
    return {
      banners: [],
      categories: [],
      recommendedBooks: [],
      serialBooks: [],
      currentReading: null,
      //showLoginPrompt: false,
      maxFreeChapters: 5,
      freeChaptersRead: 0,
      currentChapter: 1, // 当前阅读章节
      maxFreeChapters: 5, // 最大免费章节数
	      readingTime: 0, // 阅读时长（秒）
	      timer: null
    }
  },
    async onLoad() {
      await this.loadHomeData()
    },
  mounted() {
    // 开始阅读计时
    this.timer = setInterval(() => {
      this.readingTime++
    }, 1000)
  },
  beforeDestroy() {
    // 清除计时器
    clearInterval(this.timer)
  },
  computed: {
    // 计算显示哪些章节
    visibleChapters() {
      return this.chapters.filter(chap => chap.id <= this.currentChapter)
    },
    // 是否显示登录提示
    showLoginPrompt() {
      return this.currentChapter > this.maxFreeChapters && !this.$store.getters.token
    },
    // 剩余免费章节数
    remainingFreeChapters() {
      return this.maxFreeChapters - this.currentChapter
    },
    // 总章节数
    totalChapters() {
      return this.chapters.length
    }
  },
  onLoad() {
    // 从本地存储获取阅读进度
    const progress = uni.getStorageSync('readingProgress') || {}
    this.currentReading = progress.currentReading || null
    this.freeChaptersRead = progress.freeChaptersRead || 0
    
    // 如果用户正在阅读小说，显示继续阅读提示
    if (this.currentReading) {
      setTimeout(() => {
        uni.showToast({
          title: `继续阅读《${this.currentReading.title}》`,
          icon: 'none',
          duration: 3000
        })
      }, 1000)
    }
  },
  methods: {
    async loadHomeData() {
      uni.showLoading({ title: '加载中...' })
      
      try {
        const homeData = await novelService.getHomeRecommend()
        
        this.banners = homeData.banners || []
        this.categories = homeData.categories || []
        this.recommendedBooks = homeData.recommended || []
        this.serialBooks = homeData.serializing || []
        
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    // 开始/继续阅读小说
    readNovel(novelId, chapterId = 1) {
      // 查找小说信息
      const novel = this.findNovelById(novelId)
      
      // 检查是否需要登录提示
      if (this.freeChaptersRead >= this.maxFreeChapters && !this.$store.getters.token) {
        this.showLoginPrompt = true
        this.currentReading = {
          id: novelId,
          title: novel.title,
          chapterId
        }
        return
      }
      
      // 记录阅读进度
      this.recordReadingProgress(novelId, chapterId)
      
      // 跳转到阅读页
      uni.navigateTo({
        url: `/pages/novel/reader?novelId=${novelId}&chapterId=${chapterId}`
      })
    },
    
    // 继续阅读（临时允许）
    continueReading() {
      if (this.currentReading) {
        // 增加已读章节计数
        this.freeChaptersRead += 1
        
        // 保存进度
        this.recordReadingProgress(this.currentReading.id, this.currentReading.chapterId)
        
        // 跳转到阅读页
        uni.navigateTo({
          url: `/pages/novel/reader?novelId=${this.currentReading.id}&chapterId=${this.currentReading.chapterId}`
        })
        
        this.showLoginPrompt = false
      }
    },
    
    // 记录阅读进度
    recordReadingProgress(novelId, chapterId) {
      const novel = this.findNovelById(novelId)
      
      // 更新当前阅读
      this.currentReading = {
        id: novelId,
        title: novel.title,
        chapterId
      }
      
      // 更新已读免费章节数
      if (!this.$store.getters.token) {
        this.freeChaptersRead += 1
      }
      
      // 保存到本地存储
      uni.setStorageSync('readingProgress', {
        currentReading: this.currentReading,
        freeChaptersRead: this.freeChaptersRead
      })
    },
    
    // 根据ID查找小说
    findNovelById(id) {
      // 在实际应用中，这里应该调用API获取小说详情
      // 这里简化为在所有书籍中查找
      const allBooks = [...this.recommendedBooks, ...this.serialBooks]
      return allBooks.find(book => book.id === id) || { title: '未知小说' }
    },
    
    goToSearch() {
      uni.navigateTo({ url: '/pages/search/index' })
    },
    
    goToUserCenter() {
      if (this.$store.getters.token) {
        uni.navigateTo({ url: '/pages/user/index' })
      } else {
        uni.navigateTo({ url: '/pages/login' })
      }
    },
    
    goToBookList() {
      uni.navigateTo({ url: '/pages/book/list' })
    },
    
    goToLogin() {
      uni.navigateTo({ url: '/pages/login' })
    },
    // 下一章
    nextChapter() {
      if (this.currentChapter < this.totalChapters) {
        this.currentChapter++
        
        // 阅读到第五章时提示
        if (this.currentChapter === this.maxFreeChapters) {
          uni.showToast({
            title: '免费章节已读完，登录后继续',
            icon: 'none',
            duration: 3000
          })
        }
      }
    },
      // 根据阅读时长奖励金币
      rewardReadingTime() {
        const minutes = Math.floor(this.readingTime / 60)
        if (minutes > 0 && minutes % 5 === 0) {
          const coins = minutes / 5
          this.$store.commit('addCoins', coins)
          uni.showToast({ title: `阅读奖励: ${coins}金币` })
        }
      },
    // 跳转登录页
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login'
      })
    },
    
    // 继续阅读（临时允许阅读剩余免费章节）
    continueReading() {
      if (this.remainingFreeChapters > 0) {
        this.nextChapter()
      }
    }
  },

  onUnload() {
    // 保存阅读进度
    uni.setStorageSync('readingProgress', this.currentChapter)
    console.log('首页已加载')
  },
  unlockChapter() {
    if (this.currentChapter > this.maxFreeChapters) {
      if (this.$store.getters.vipLevel > 0) {
        // VIP用户直接解锁
        return true
      } else if (this.$store.getters.coins > 10) {
        // 消耗金币解锁
        this.$store.commit('deductCoins', 10)
        return true
      } else {
        // 提示获取金币方式
        uni.showModal({
          title: '解锁章节',
          content: '观看广告可获取金币解锁本章节',
          confirmText: '观看广告',
          success: () => {
            this.watchAdToUnlock()
          }
        })
        return false
      }
    }
    return true
  },
  
  watchAdToUnlock() {
    // 实现广告观看逻辑
    // 观看成功后增加金币
    this.$store.commit('addCoins', 5)
    uni.showToast({ title: '获得5金币' })
  }
}
</script>

</script>

<style lang="scss">
.novel-home {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: white;
  
  .logo {
    width: 120rpx;
    height: 60rpx;
    margin-right: 20rpx;
  }
  
  .search-box {
    flex: 1;
    background: #f0f0f0;
    border-radius: 30rpx;
    padding: 15rpx 25rpx;
    display: flex;
    align-items: center;
    
    .placeholder {
      color: #999;
      font-size: 28rpx;
      margin-left: 10rpx;
    }
  }
  
  .user-icon {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20rpx;
  }
}

.banner {
  height: 300rpx;
  margin: 20rpx 0;
  border-radius: 16rpx;
  overflow: hidden;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.category-nav {
  display: flex;
  justify-content: space-around;
  background: white;
  border-radius: 16rpx;
  padding: 30rpx 0;
  margin-bottom: 30rpx;
  
  .nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .nav-icon {
      width: 80rpx;
      height: 80rpx;
      margin-bottom: 15rpx;
    }
    
    text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.section {
  background: white;
  border-radius: 16rpx;
  padding: 25rpx;
  margin-bottom: 30rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .more {
      font-size: 26rpx;
      color: #999;
    }
  }
}

.book-list {
  white-space: nowrap;
  
  .book-item {
    display: inline-block;
    width: 180rpx;
    margin-right: 25rpx;
    vertical-align: top;
    
    .book-cover {
      width: 180rpx;
      height: 240rpx;
      border-radius: 8rpx;
    }
    
    .book-title {
      display: block;
      font-size: 26rpx;
      font-weight: bold;
      margin-top: 15rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .book-author {
      display: block;
      font-size: 24rpx;
      color: #999;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.book-row {
  display: flex;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #eee;
  
  &:last-child {
    border-bottom: none;
  }
  
  .row-cover {
    width: 160rpx;
    height: 210rpx;
    border-radius: 8rpx;
    margin-right: 25rpx;
  }
  
  .book-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .row-title {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .row-author {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 15rpx;
    }
    
    .row-desc {
      font-size: 26rpx;
      color: #666;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      margin-bottom: 15rpx;
    }
  }
  
  .row-tags {
    display: flex;
    flex-wrap: wrap;
    
    .tag {
      font-size: 22rpx;
      color: #e74c3c;
      border: 1rpx solid #e74c3c;
      border-radius: 20rpx;
      padding: 5rpx 15rpx;
      margin-right: 15rpx;
      margin-bottom: 10rpx;
    }
  }
}
</style>

