<template>
  <view class="reader-container" :class="{ 'night-mode': nightMode }">
    <!-- 顶部导航栏 -->
    <view class="reader-header" v-if="showHeader">
      <view class="header-left">
        <text class="iconfont icon-back" @click="goBack"></text>
        <text class="novel-title">{{novelTitle}}</text>
      </view>
      <view class="header-right">
        <text class="iconfont icon-menu" @click="showMenu"></text>
      </view>
    </view>

    <!-- 阅读内容区域 -->
    <scroll-view 
      class="reader-content" 
      scroll-y 
      :scroll-top="scrollTop"
      @scroll="onScroll"
      @touchstart="onTouchStart"
      @touchend="onTouchEnd"
    >
      <view class="chapter-title">{{chapterTitle}}</view>
      <view class="content-text">
        <text>{{content}}</text>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text>加载中...</text>
      </view>
      
      <!-- 错误状态 -->
      <view v-if="error" class="error-container">
        <text>{{error}}</text>
        <button @click="loadChapterContent">重试</button>
      </view>
    </scroll-view>

    <!-- 底部控制栏 -->
    <view class="reader-footer" v-if="showFooter">
      <view class="progress-text">
        第{{currentChapter}}章 {{progress}}%
      </view>
      <view class="control-buttons">
        <text class="iconfont icon-catalog" @click="showCatalog"></text>
        <text class="iconfont icon-font" @click="showFontSettings"></text>
        <text class="iconfont icon-night" @click="toggleNightMode"></text>
        <text class="iconfont icon-download" @click="downloadChapter"></text>
      </view>
    </view>

    <!-- 广告位 -->
    <ad v-if="showAd" unit-id="您的广告单元ID" class="reader-ad"></ad>

    <!-- 设置面板 -->
    <view class="settings-panel" v-if="showSettings">
      <view class="font-size-controls">
        <text class="iconfont icon-font-small" @click="decreaseFontSize"></text>
        <text>字体大小: {{fontSize}}px</text>
        <text class="iconfont icon-font-large" @click="increaseFontSize"></text>
      </view>
      <view class="background-options">
        <view 
          v-for="bg in backgroundOptions" 
          :key="bg.value"
          class="bg-option"
          :class="{ active: backgroundColor === bg.value }"
          :style="{ backgroundColor: bg.value }"
          @click="changeBackground(bg.value)"
        ></view>
      </view>
    </view>

    <!-- 目录面板 -->
    <view class="catalog-panel" v-if="showCatalogPanel">
      <view class="catalog-header">
        <text class="catalog-title">目录</text>
        <text class="iconfont icon-close" @click="showCatalogPanel = false"></text>
      </view>
      <scroll-view class="chapter-list" scroll-y>
        <view 
          v-for="chapter in chapterList" 
          :key="chapter.id"
          class="chapter-item"
          :class="{ active: chapter.id === chapterId }"
          @click="selectChapter(chapter.id)"
        >
          <text>{{chapter.title}}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      novelId: '',
      chapterId: '',
      novelTitle: '加载中...',
      chapterTitle: '加载中...',
      content: '正在加载内容...',
      currentChapter: 1,
      totalChapters: 0,
      progress: 0,
      scrollTop: 0,
      showHeader: false,
      showFooter: false,
      showSettings: false,
      showCatalogPanel: false,
      showAd: false,
      nightMode: false,
      touchStartX: 0,
      touchStartY: 0,
      lastScrollPosition: 0,
      loading: false,
      error: null,
      fontSize: 18,
      backgroundColor: '#f5f0e1',
      backgroundOptions: [
        { value: '#f5f0e1', name: '羊皮纸' },
        { value: '#e8f5e9', name: '护眼绿' },
        { value: '#e3f2fd', name: '天空蓝' },
        { value: '#fce4ec', name: '粉红' },
        { value: '#1a1a1a', name: '夜间' }
      ],
      chapterList: []
    }
  },
  onLoad(options) {
    console.log('阅读器页面加载，参数:', options);
    
    // 确保参数获取方式正确
    this.novelId = options.novelId || '';
    this.chapterId = options.chapterId || '1';
    
    console.log('novelId:', this.novelId, 'chapterId:', this.chapterId);
    
    if (!this.novelId) {
      console.error('小说ID参数缺失');
      this.error = '小说ID参数缺失';
      uni.showToast({
        title: '小说ID参数缺失',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    
    this.loadChapterContent();
  },
  onShow() {
    console.log('reader onShow');
    
    // 确保页面显示时也能处理参数
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage && currentPage.options) {
      const options = currentPage.options;
      console.log('当前页面参数:', options);
      
      if (options.novelId && (!this.novelId || this.novelId !== options.novelId)) {
        this.novelId = options.novelId;
        this.chapterId = options.chapterId || '1';
        this.loadChapterContent();
      }
    }
  },
  // 添加所有生命周期钩子进行调试
  beforeCreate() {
    console.log('reader beforeCreate');
  },
  created() {
    console.log('reader created');
  },
  beforeMount() {
    console.log('reader beforeMount');
  },
  mounted() {
    console.log('reader mounted');
  },
  onReady() {
    console.log('reader onReady');
  },
  onHide() {
    console.log('reader onHide');
  },
  onUnload() {
    console.log('reader onUnload');
  },
  methods: {
    async loadChapterContent() {
      console.log('开始加载章节内容');
      
      this.loading = true;
      this.error = null;
      
      try {
        console.log('开始请求章节内容，章节ID:', this.chapterId);
        
    // 确保$http对象可用
    if (!this.$http || typeof this.$http.get !== 'function') {
      throw new Error('网络请求不可用');
    }
    
    // 使用若依框架的API调用方式
    const res = await this.$http.get(`/novel/chapter/${this.chapterId}`);
    console.log('章节内容响应:', res);
    
    if (res.code === 200) {
      this.novelTitle = res.data.novelTitle || '未知小说';
      this.chapterTitle = res.data.chapterTitle || '未知章节';
      this.content = res.data.content || '';
      this.currentChapter = res.data.chapterIndex || 1;
      this.totalChapters = res.data.totalChapters || 0;
      
      uni.showToast({
        title: '加载成功',
        icon: 'success',
        duration: 1500
      });
    } else {
      console.error('API返回错误状态码:', res.code);
      this.error = '加载失败: ' + (res.msg || '未知错误');
      uni.showToast({
        title: res.msg || '加载失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载章节内容失败:', error);
    this.error = '加载失败，请检查网络连接';
    uni.showToast({
      title: '加载失败，请检查网络连接',
      icon: 'none'
    });
  } finally {
    this.loading = false;
    uni.hideLoading();
  }
}
}}
</script>

<style>
.reader-container {
  position: relative;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: v-bind(backgroundColor);
  transition: background-color 0.3s ease;
}

.reader-header {
  height: 44px;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.reader-content {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
  line-height: 1.8;
  font-size: v-bind(fontSize + 'px');
  color: #333;
  margin-top: 44px;
  margin-bottom: 50px;
}

.chapter-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

.content-text {
  text-indent: 2em;
  line-height: 1.8;
}

.reader-footer {
  height: 50px;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.reader-ad {
  height: 90px;
  margin-bottom: 10px;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.error-container button {
  margin-top: 20px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
}

.settings-panel {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  z-index: 999;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.font-size-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.background-options {
  display: flex;
  justify-content: space-around;
}

.bg-option {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid transparent;
  cursor: pointer;
}

.bg-option.active {
  border-color: var(--primary-color);
}

.catalog-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  z-index: 1001;
}

.catalog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.chapter-list {
  height: calc(100vh - 60px);
}

.chapter-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.chapter-item.active {
  color: var(--primary-color);
  font-weight: bold;
}

/* 夜间模式样式 */
.night-mode .reader-content {
  color: #888;
}

.night-mode .content-text {
  color: #888;
}
</style>
