<template>
  <view class="reader-container" :style="readerStyles">
    <!-- 顶部导航 -->
    <view class="reader-header">
      <uni-icons type="arrowleft" size="28" color="#fff" @click="goBack"></uni-icons>
      <text class="novel-title">{{ novelTitle }}</text>
      <view class="header-actions">
        <uni-icons type="more" size="28" color="#fff"></uni-icons>
      </view>
    </view>
    
    <!-- 阅读区域 -->
    <scroll-view scroll-y class="reader-content" :scroll-top="scrollTop" @scroll="onScroll">
      <view class="chapter-title">{{ chapterDetail.title }}</view>
      <rich-text :nodes="chapterContent" class="content-text"></rich-text>
    </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="reader-footer">
      <view class="progress">
        <text>{{ chapterDetail.chapterNumber }}/{{ totalChapters }}</text>
        <text>{{ progress }}%</text>
      </view>
      <view class="actions">
        <button class="action-btn" @click="prevChapter">
          <uni-icons type="arrow-up" size="24"></uni-icons>
          <text>上一章</text>
        </button>
        <button class="action-btn" @click="toggleMenu">
          <uni-icons type="list" size="24"></uni-icons>
          <text>目录</text>
        </button>
        <button class="action-btn" @click="toggleSettings">
          <uni-icons type="gear" size="24"></uni-icons>
          <text>设置</text>
        </button>
        <button class="action-btn" @click="nextChapter">
          <uni-icons type="arrow-down" size="24"></uni-icons>
          <text>下一章</text>
        </button>
      </view>
    </view>
    
    <!-- 目录抽屉 -->
    <uni-drawer ref="drawer" mode="right" :width="300">
      <view class="drawer-content">
        <text class="drawer-title">目录</text>
        <scroll-view scroll-y class="chapter-list">
          <view 
            v-for="chapter in chapters" 
            :key="chapter.id" 
            class="chapter-item"
            :class="{ active: chapter.id === chapterDetail.id }"
            @click="selectChapter(chapter)"
          >
            <text>{{ chapter.chapterNumber }}. {{ chapter.title }}</text>
          </view>
        </scroll-view>
      </view>
    </uni-drawer>
  </view>
</template>

<script>
import novelService from '@/services/novelService'

export default {
  data() {
    return {
      novelId: null,
      chapterId: null,
      novelTitle: '',
      chapterDetail: {},
      chapterContent: '',
      chapters: [],
      totalChapters: 0,
      progress: 0,
      scrollTop: 0,
      readerStyles: {
        fontSize: '32rpx',
        lineHeight: '1.8',
        backgroundColor: '#f8f2e0',
        color: '#333'
      }
    }
  },
  async onLoad(options) {
    this.novelId = options.novelId
    this.chapterId = options.chapterId || 1
    
    await this.loadNovelData()
    await this.loadChapter()
  },
  methods: {
    async loadNovelData() {
      // 获取小说基本信息
      const novel = await novelService.getNovelDetail(this.novelId)
      this.novelTitle = novel.title
      
      // 获取章节列表
      this.chapters = await novelService.getChapters(this.novelId)
      this.totalChapters = this.chapters.length
    },
    
    async loadChapter() {
      uni.showLoading({ title: '加载中...' })
      
      try {
        const chapter = await novelService.getChapterContent(this.novelId, this.chapterId)
        this.chapterDetail = chapter
        
        // 处理章节内容
        this.chapterContent = this.formatContent(chapter.content)
        
        // 计算阅读进度
        this.progress = Math.round((this.chapterId / this.totalChapters) * 100)
        
        // 保存阅读进度
        this.saveReadingProgress()
        
      } catch (error) {
        uni.showToast({
          title: '加载章节失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    formatContent(content) {
      // 将文本内容转换为带格式的HTML
      const paragraphs = content.split('\n\n')
      return paragraphs.map(p => `<p>${p}</p>`).join('')
    },
    
    saveReadingProgress() {
      // 保存到本地
      uni.setStorageSync('readingProgress', {
        novelId: this.novelId,
        chapterId: this.chapterId
      })
      
      // 如果已登录，同步到服务器
      if (uni.getStorageSync('token')) {
        this.$http.post('/reading/progress', {
          novelId: this.novelId,
          chapterId: this.chapterId
        })
      }
    },
    
    prevChapter() {
      if (this.chapterId > 1) {
        this.chapterId--
        this.loadChapter()
      } else {
        uni.showToast({
          title: '已经是第一章',
          icon: 'none'
        })
      }
    },
    
    nextChapter() {
      if (this.chapterId < this.totalChapters) {
        this.chapterId++
        this.loadChapter()
      } else {
        uni.showToast({
          title: '已是最新章节',
          icon: 'none'
        })
      }
    },
    
    selectChapter(chapter) {
      this.chapterId = chapter.id
      this.$refs.drawer.close()
      this.loadChapter()
    },
    
    toggleMenu() {
      this.$refs.drawer.open()
    },
    
    toggleSettings() {
      uni.navigateTo({
        url: '/pages/reader/settings'
      })
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    onScroll(e) {
      // 记录滚动位置
      this.scrollTop = e.detail.scrollTop
    }
  }
}
</script>

<style scoped>
.reader-container {
  position: relative;
  height: 100vh;
  padding: 20rpx;
  box-sizing: border-box;
}

.reader-header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  z-index: 100;
}

.novel-title {
  font-size: 32rpx;
  max-width: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.reader-content {
  height: calc(100vh - 200rpx);
  padding-top: 80rpx;
  padding-bottom: 120rpx;
}

.chapter-title {
  font-size: 40rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  color: #2a5caa;
}

.content-text {
  font-size: 32rpx;
  line-height: 1.8;
}

.reader-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.9);
  padding: 20rpx;
  border-top: 1rpx solid #eee;
}

.progress {
  display: flex;
  justify-content: space-between;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.actions {
  display: flex;
  justify-content: space-between;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border: none;
  font-size: 24rpx;
  padding: 10rpx;
}

.drawer-content {
  padding: 30rpx;
}

.drawer-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
  padding-bottom: 20rpx;
}

.chapter-list {
  height: calc(100vh - 150rpx);
}

.chapter-item {
  padding: 20rpx 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
  font-size: 28rpx;
}

.chapter-item.active {
  color: #2a5caa;
  font-weight: bold;
}
</style>