<template>
  <scroll-view scroll-y class="detail-page">
    <!-- 封面区域 -->
    <view class="cover-section">
      <image :src="novel.cover" class="cover-image" />
      <view class="cover-overlay">
        <text class="title">{{ novel.title }}</text>
        <text class="author">{{ novel.author }}</text>
        
        <!-- VIP专享标识 -->
        <view v-if="isVIPOnly" class="vip-tag">
          <uni-icons type="crown-filled" color="#ffc53d" size="16"></uni-icons>
          <text>VIP专享</text>
        </view>
      </view>
    </view>
    
    <!-- 基本信息 -->
    <view class="info-card">
      <view class="info-item">
        <uni-icons type="flag" size="18" color="#666"></uni-icons>
        <text>状态：{{ novel.status }}</text>
      </view>
      <view class="info-item">
        <uni-icons type="list" size="18" color="#666"></uni-icons>
        <text>分类：{{ novel.category }}</text>
      </view>
      <view class="info-item">
        <uni-icons type="eye" size="18" color="#666"></uni-icons>
        <text>人气：{{ formatCount(novel.views) }}</text>
      </view>
      <view class="info-item">
        <uni-icons type="calendar" size="18" color="#666"></uni-icons>
        <text>更新：{{ novel.updateTime }}</text>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="read-btn" @click="startReading">
        {{ lastChapter ? '继续阅读' : '开始阅读' }}
      </button>
      <button class="add-btn" @click="addToBookshelf">
        <uni-icons :type="inBookshelf ? 'star-filled' : 'star'" color="#ffc53d" size="18"></uni-icons>
        {{ inBookshelf ? '已在书架' : '加入书架' }}
      </button>
    </view>
    
    <!-- 简介 -->
    <view class="description">
      <text class="section-title">内容简介</text>
      <text class="content">{{ novel.description }}</text>
    </view>
    
    <!-- 章节列表 -->
    <view class="chapter-list">
      <text class="section-title">目录</text>
      <view class="chapter-header">
        <text>共{{ novel.chapterCount }}章</text>
        <text @click="reverseOrder">{{ sortDesc ? '正序' : '倒序' }}</text>
      </view>
      
      <view class="chapter-item" 
            v-for="chapter in sortedChapters" 
            :key="chapter.id"
            @click="readChapter(chapter)"
      >
        <text class="chapter-title">{{ chapter.title }}</text>
        <view class="chapter-meta">
          <text>{{ formatDate(chapter.updateTime) }}</text>
          <!-- VIP章节标识 -->
          <view v-if="chapter.vip" class="chapter-vip">
            <uni-icons type="crown" size="14" color="#ffc53d"></uni-icons>
            <text>VIP</text>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { useVipStore } from '@/stores/vip'
import { request } from '@/utils/request'

const props = defineProps({
  novelId: {
    type: Number,
    required: true
  }
})

const novel = ref({
  id: 1,
  title: '哎呀电子科技传奇',
  author: '哎呀作者',
  cover: '/static/covers/novel1.jpg',
  status: '连载中',
  category: '都市异能',
  views: 12500,
  updateTime: '2025-06-10 12:30',
  description: '这是一个关于哎呀电子科技崛起的故事，讲述了一群程序员如何通过技术创新改变世界...',
  chapterCount: 120,
  vipOnly: true // 整本VIP专享
})

const chapters = ref([
  { id: 1, title: '第1章 命运的转折', updateTime: '2025-05-01', vip: false },
  { id: 2, title: '第2章 初遇哎呀科技', updateTime: '2025-05-03', vip: false },
  // ...中间章节
  { id: 100, title: '第100章 突破性进展', updateTime: '2025-06-05', vip: true },
  { id: 101, title: '第101章 VIP专享章节', updateTime: '2025-06-10', vip: true }
])

const sortDesc = ref(false)
const lastChapter = ref(null)
const inBookshelf = ref(false)

const userStore = useUserStore()
const vipStore = useVipStore()

// 是否是VIP专享书籍
const isVIPOnly = computed(() => {
  return novel.value.vipOnly
})

// 排序后的章节列表
const sortedChapters = computed(() => {
  return sortDesc.value 
    ? [...chapters.value].reverse() 
    : chapters.value
})

// 格式化数字
const formatCount = (num) => {
  if (num > 10000) return (num / 10000).toFixed(1) + '万'
  return num
}

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr.slice(5) // 显示月-日
}

// 开始阅读
const startReading = () => {
  if (isVIPOnly.value && !vipStore.isVIP) {
    uni.showModal({
      title: 'VIP专享内容',
      content: '此书籍为VIP专享，开通会员即可无限制阅读',
      confirmText: '开通会员',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/vip/index' })
        }
      }
    })
    return
  }
  
  const chapterId = lastChapter.value?.id || chapters.value[0].id
  readChapter({ id: chapterId })
}

// 阅读章节
const readChapter = (chapter) => {
  if (chapter.vip && !vipStore.isVIP) {
    uni.showModal({
      title: 'VIP章节',
      content: '此章节为VIP专享，开通会员即可阅读',
      confirmText: '开通会员',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/vip/index' })
        }
      }
    })
    return
  }
  
  uni.navigateTo({
    url: `/pages/reader/index?novelId=${novel.value.id}&chapterId=${chapter.id}`
  })
}

// 加入书架
const addToBookshelf = () => {
  inBookshelf.value = !inBookshelf.value
  uni.showToast({
    title: inBookshelf.value ? '已加入书架' : '已移除书架',
    icon: 'none'
  })
}

// 切换排序
const reverseOrder = () => {
  sortDesc.value = !sortDesc.value
}

// 加载数据
onMounted(async () => {
  // 获取小说详情
  const res = await request({
    url: `/novel/${props.novelId}`,
    method: 'GET'
  })
  novel.value = res.data.novel
  chapters.value = res.data.chapters
  
  // 获取最后阅读章节
  if (userStore.userId) {
    const progressRes = await request({
      url: `/reading/progress?novelId=${props.novelId}`,
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${uni.getStorageSync('token')}`
      }
    })
    lastChapter.value = progressRes.data.lastChapter
  }
})
</script>

<style scoped>
.detail-page {
  height: 100vh;
  background-color: var(--bg-color);
  padding-bottom: 50px;
}

.cover-section {
  position: relative;
  height: 300px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0,0,0,0.7));
  padding: 20px;
  color: white;
}

.title {
  font-size: 24px;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.author {
  font-size: 16px;
  opacity: 0.8;
  display: block;
}

.vip-tag {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0,0,0,0.6);
  border: 1px solid #ffc53d;
  border-radius: 15px;
  padding: 5px 10px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.vip-tag text {
  margin-left: 5px;
}

.info-card {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 15px;
  margin: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-item text {
  margin-left: 8px;
}

.action-buttons {
  display: flex;
  padding: 0 15px;
  margin: 20px 0;
}

.read-btn {
  flex: 2;
  background: linear-gradient(to right, #2a5caa, #1a3353);
  color: white;
  border: none;
  border-radius: 24px;
  height: 44px;
  line-height: 44px;
  font-weight: bold;
  margin-right: 10px;
}

.add-btn {
  flex: 1;
  background-color: var(--card-bg);
  border: 1px solid var(--primary-color);
  color: var(--primary-color);
  border-radius: 24px;
  height: 44px;
  line-height: 44px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.description {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 15px;
  margin: 15px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}

.content {
  font-size: 14px;
  line-height: 1.8;
  color: var(--text-color);
}

.chapter-list {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 15px;
  margin: 15px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chapter-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.chapter-title {
  font-size: 16px;
  display: block;
  margin-bottom: 5px;
}

.chapter-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.chapter-vip {
  display: flex;
  align-items: center;
  color: #ffc53d;
}

.chapter-vip text {
  margin-left: 3px;
}
</style>