<template>
  <view>
    <!-- 章节间广告 -->
    <ad-banner v-if="showMidAd" :ads="midAds" />
    
    <scroll-view scroll-y>
      <!-- 章节内容 -->
      <view v-for="chapter in chapters" :key="chapter.id">
        <text>{{ chapter.title }}</text>
        <rich-text :nodes="chapter.content" />
      </view>
      
      <!-- 章节底部广告 -->
      <ad-banner :ads="chapterAds" />
    </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button @click="prevChapter">上一章</button>
      <button @click="showCatalog">目录</button>
      <button @click="nextChapter">下一章</button>
    </view>
  </view>
</template>

<script>
import AdBanner from '@/components/AdBanner';

export default {
  components: { AdBanner },
  data() {
    return {
      novel: {},
      chapters: [],
      currentChapter: 0,
      // 确保数组初始化
      midAds: [],
      chapterAds: [],
      showMidAd: false
    };
  },
  onLoad(options) {
    this.novelId = options.id;
    this.loadNovelData();
    this.scheduleMidAd();
  },
  methods: {
    async loadNovelData() {
      // 加载小说详情
      const novelRes = await this.$http.get(`/novel/detail/${this.novelId}`);
      if (novelRes.data) {
        this.novel = novelRes.data;
      }
      
      // 加载章节列表
      const chapterRes = await this.$http.get(`/chapter/list/${this.novelId}`);
      if (chapterRes.rows && Array.isArray(chapterRes.rows)) {
        this.chapters = chapterRes.rows;
      }
      
      // 加载当前章节内容
      if (this.chapters.length > 0) {
        await this.loadChapterContent(0);
      }
      
      // 加载章节广告
      const adRes = await this.$http.get('/java-api/ad/position?code=CHAPTER_FOOTER');
      this.chapterAds = adRes.data;
    },
    
    async loadChapterContent(index) {
      if (index < 0 || index >= this.chapters.length) return;
      
      const chapterId = this.chapters[index].id;
      const res = await this.$http.get(`/chapter/content/${chapterId}`);
      
      // 更新章节内容
      if (res.data) {
        this.$set(this.chapters, index, {
          ...this.chapters[index],
          content: res.data.content
        });
        this.currentChapter = index;
      }}
,
    
    // 定时显示中间广告
    scheduleMidAd() {
      setTimeout(async () => {
        const res = await this.$http.get('/java-api/ad/position?code=MID_CHAPTER');
        this.midAds = res.data;
        this.showMidAd = true;
        
        // 10秒后隐藏
        setTimeout(() => this.showMidAd = false, 10000);
      }, 30000); // 30秒后显示
    },
    
    prevChapter() {
      this.loadChapterContent(this.currentChapter - 1);
    },
    
    nextChapter() {
      this.loadChapterContent(this.currentChapter + 1);
    },
    
    showCatalog() {
      uni.navigateTo({
        url: `/pages/novel/catalog?id=${this.novelId}`
      });
    }
  }
}
</script>