<template>
  <view class="reader-container">
    <!-- 顶部导航栏 -->
    <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>{{decodedContent}}</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>

    <!-- 目录面板 -->
    <view class="catalog-panel" v-if="showCatalogPanel">
      <!-- 章节列表 -->
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      novelId: '',
      chapterId: '',
      novelTitle: '加载中...',
      chapterTitle: '加载中...',
      content: '', // Base64编码的内容
      decodedContent: '正在加载内容...', // 解码后的内容
      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
    }
  },
  onLoad(options) {
    console.log('阅读器页面加载，参数:', options);
    
    // 确保参数正确获取
    this.novelId = options.novelId || '';
    this.chapterId = options.chapterId || '1';
    
    if (!this.novelId) {
      this.error = '小说ID参数缺失';
      return;
    }
    
    this.loadChapterContent();
  },
  methods: {
    // 添加onScroll方法
    onScroll(e) {
      this.lastScrollPosition = e.detail.scrollTop;
      // 计算阅读进度
      this.calculateProgress();
    },
    
    onTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.touchStartY = e.touches[0].clientY;
    },
    
    onTouchEnd(e) {
      const endX = e.changedTouches[0].clientX;
      const endY = e.changedTouches[0].clientY;
      const diffX = endX - this.touchStartX;
      const diffY = endY - this.touchStartY;
      
      // 横向滑动大于纵向滑动，且滑动距离大于50px
      if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
        if (diffX > 0) {
          this.prevChapter(); // 右滑，上一章
        } else {
          this.nextChapter(); // 左滑，下一章
        }
      }
    },
    
    // Base64解码
    decodeBase64(content) {
      if (typeof content !== 'string') {
        console.error('Base64解码失败：内容不是字符串');
        return '内容格式错误';
      }
      
      try {
        // 处理可能的URL安全Base64编码
        let base64 = content.replace(/-/g, '+').replace(/_/g, '/');
        
        // 添加必要的填充字符
        const pad = base64.length % 4;
        if (pad) {
          if (pad === 1) {
            throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding');
          }
          base64 += new Array(5-pad).join('=');
        }
        
        // 解码
        const decoded = uni.base64ToArrayBuffer(base64);
        const textDecoder = new TextDecoder('utf-8');
        return textDecoder.decode(decoded);
      } catch (error) {
        console.error('Base64解码失败:', error);
        return '内容解码失败，请稍后再试。';
      }
    },
    
    async loadChapterContent() {
      this.loading = true;
      this.error = null;
      
      try {
        console.log('开始请求章节内容，章节ID:', this.chapterId);
        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.decodedContent = this.decodeBase64(this.content);
          
          // 设置章节信息
          this.currentChapter = res.data.chapterIndex || 1;
          this.totalChapters = res.data.totalChapters || 0;
        } else {
          console.error('API返回错误状态码:', res.code);
          this.error = '加载失败，请重试';
        }
      } catch (error) {
        console.error('加载章节内容失败:', error);
        this.error = '加载失败，请检查网络连接';
      } finally {
        this.loading = false;
      }
    },
    
    calculateProgress() {
      // 根据滚动位置计算阅读进度
      // 这里需要获取内容区域的实际高度，由于uni-app中获取节点高度较为复杂，暂时用模拟数据
      // 实际项目中应该通过uni.createSelectorQuery()获取
      this.progress = Math.min(100, Math.round((this.lastScrollPosition / 1000) * 100));
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    prevChapter() {
      if (this.currentChapter > 1) {
        this.chapterId = parseInt(this.chapterId) - 1;
        this.loadChapterContent();
      } else {
        uni.showToast({ title: '已经是第一章了', icon: 'none' });
      }
    },
    
    nextChapter() {
      if (this.currentChapter < this.totalChapters) {
        this.chapterId = parseInt(this.chapterId) + 1;
        this.loadChapterContent();
      } else {
        uni.showToast({ title: '已经是最后一章了', icon: 'none' });
      }
    },
    
    showMenu() {
      // 显示/隐藏顶部和底部栏
      this.showHeader = !this.showHeader;
      this.showFooter = !this.showFooter;
    },
    
    showCatalog() {
      this.showCatalogPanel = true;
    },
    
    showFontSettings() {
      this.showSettings = true;
    },
    
    toggleNightMode() {
      this.nightMode = !this.nightMode;
      // 切换夜间模式样式
    },
    
    setAdStrategy() {
      // 设置广告显示策略，如每阅读三章显示一次广告
      const readChapters = uni.getStorageSync('readChapters') || 0;
      this.showAd = readChapters > 0 && readChapters % 3 === 0;
    },
    
    downloadChapter() {
      // 下载本章内容供离线阅读
    }
  }
}
</script>

<style>
.reader-container {
  position: relative;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f0e1; /* 羊皮纸色背景 */
}

.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;
}

.reader-content {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
  line-height: 1.8;
  font-size: 18px;
  color: #333;
}

.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;
}

.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;
}

/* 夜间模式样式 */
.night-mode {
  background-color: #1a1a1a;
  color: #888;
}

.night-mode .reader-content {
  background-color: #1a1a1a;
  color: #888;
}
</style>
