<template>
  <view class="book-detail-page">
    <!-- 导航栏 -->
    <nav-bar :title="$t('bookDetails.title')"></nav-bar>
    
    <scroll-view 
      scroll-y 
      class="detail-scroll"
      :style="{ height: scrollHeight + 'px' }"
    >
      <!-- 书籍信息 -->
      <view class="book-info">
        <image :src="bookInfo.images" class="cover" mode="aspectFill" />
        <text class="title">{{ bookInfo.name }}</text>
        <text class="author">{{ $t('bookDetails.authorName') }}{{ bookInfo.author?.authorName }}</text>
        
        <!-- 统计信息 -->
        <view class="stats">
          <view class="stat-item">
            <image src="@/static/icon/icon_look_c.png" mode="aspectFit" />
            <text>{{ readCount }}{{ $t('bookHome.readingCount') }}</text>
          </view>
          <view class="divider" />
          <view class="stat-item">
            <image src="@/static/icon/icon_listen_c.png" mode="aspectFit" />
            <text>{{ listenCount }}{{ $t('bookHome.listenCount') }}</text>
          </view>
          <view class="divider" />
          <view class="stat-item">
            <image src="@/static/icon/icon_bug_c.png" mode="aspectFit" />
            <text>{{ buyCount }}{{ $t('bookHome.purchased') }}</text>
          </view>
        </view>
      </view>
      
      <!-- 简介 -->
      <view class="introduction">
        <text class="section-title">{{ $t('bookDetails.introduction') }}</text>
        <text class="content">{{ bookInfo.author?.introduction }}</text>
      </view>
      
      <!-- 书评列表 (非iOS) -->
      <!-- <view v-if="!isIOS" class="comments-section">
        <view class="section-header">
          <text class="section-title">{{ $t('bookDetails.message') }}</text>
          <view v-if="commentList.length > 0" class="more-link" @click="goToReview">
            <text>{{ $t('bookDetails.more') }}</text>
            <wd-icon name="arrow-right" size="14px" />
          </view>
        </view>
        <view class="comment-wrapper">
          <CommentList 
            v-if="commentList.length > 0"
            :comments="commentList.slice(0, 2)" 
          />
          <text v-else class="empty-text">{{ nullText }}</text>
        </view>
      </view> -->
      
      <!-- 相关推荐 -->
      <view class="related-books">
        <text class="section-title">{{ $t('bookDetails.relatedBooks') }}</text>
        <scroll-view v-if="relatedBooks.length > 0" scroll-x class="book-scroll">
          <view class="book-list">
            <view 
              class="book-item" 
              v-for="item in relatedBooks" 
              :key="item.id"
              @click="goToDetail(item.id)"
            >
              <image :src="item.images" mode="aspectFill" />
              <text>{{ item.name }}</text>
            </view>
          </view>
        </scroll-view>
        <text v-else class="empty-text">{{ nullBookText }}</text>
      </view>
    </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <template v-if="bookInfo.isBuy || hasVip">
        <view class="action-btn read" @click="goToReader">
          <text>{{ $t('bookDetails.startReading') }}</text>
        </view>
        <!-- <view class="action-btn purchased">
          <wd-button disabled custom-class="purchased-btn">
            {{ $t('bookDetails.buttonText2') }}
          </wd-button>
        </view> -->
        <view class="action-btn listen" @click="goToListen">
          <text>{{ $t('bookDetails.startListening') }}</text>
        </view>
      </template>
      <template v-else>
        <view v-if="bookInfo.freeChapterCount > 0" class="action-btn read" @click="goToReader">
          <text>{{ $t('bookDetails.tryRead') }}</text>
        </view>
        <view class="action-btn buy" :class="{ 'buy-full': bookInfo.freeChapterCount === 0 }">
          <wd-button type="primary" @click="showPurchasePopup">
            {{ $t('bookDetails.buttonText1') }}
          </wd-button>
        </view>
        <view v-if="bookInfo.freeChapterCount > 0" class="action-btn listen" @click="goToListen">
          <text>{{ $t('bookDetails.tryListen') }}</text>
        </view>
      </template>
    </view>
    
    <!-- 购买弹窗 -->
    <GoodsSelector
      :show="purchaseVisible"
      :goods="goodsList"
      @confirm="handlePurchase"
      @close="closePurchasePopup"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { t } from '@/utils/i18n'
import { bookApi } from '@/api/modules/book'
import { useUserStore } from '@/stores/user'
import type { IBookDetail, IBook, IComment } from '@/types/book'
import type { IGoods } from '@/types/order'
import GoodsSelector from '@/components/order/GoodsSelector.vue'
import CommentList from '@/components/book/CommentList.vue'

const userStore = useUserStore()

// 路由参数
const bookId = ref(0)
const pageFrom = ref('')

// 会员状态
const hasVip = computed(() => userStore.userInfo?.userEbookVip?.length > 0 || false)

// 数据状态
const bookInfo = ref<IBookDetail>({
  id: 0,
  name: '',
  images: '',
  author: { authorName: '', introduction: '' },
  isBuy: false,
  freeChapterCount: 0
})
const goodsList = ref<IGoods[]>([])
const readCount = ref(0)
const listenCount = ref(0)
const buyCount = ref(0)
const commentList = ref<IComment[]>([])
const relatedBooks = ref<IBook[]>([])
const nullText = ref('')
const nullBookText = ref('')
const purchaseVisible = ref(false)
const scrollHeight = ref(0)

// 计算属性
const isIOS = computed(() => {
  // #ifdef APP-PLUS
  return uni.getSystemInfoSync().platform === 'ios'
  // #endif
  return false
})

// 生命周期
onLoad((options: any) => {
  if (options.id) {
    bookId.value = Number(options.id)
  }
  if (options.page) {
    pageFrom.value = options.page
  }
  
  initScrollHeight()
  loadBookCount()
  loadRecommendBooks()
})

onShow(() => {
  loadBookInfo()
  loadGoodsInfo()
  if (!isIOS.value) {
    loadComments()
  }
})

onMounted(() => {
  initScrollHeight()
})

// 初始化滚动区域高度
function initScrollHeight() {
  const systemInfo = uni.getSystemInfoSync()
  const statusBarHeight = systemInfo.statusBarHeight || 0
  let navBarHeight = 44
  if (systemInfo.model.includes('iPhone')) {
    const modelNumber = parseInt(systemInfo.model.match(/\d+/)?.[0] || '0')
    if (modelNumber >= 11) {
      navBarHeight = 48
    }
  }
  const totalNavHeight = statusBarHeight + navBarHeight
  const actionBarHeight = 110 // rpx转px约55
  scrollHeight.value = systemInfo.windowHeight - totalNavHeight - actionBarHeight / 2
}

// 加载书籍详情
async function loadBookInfo() {
  const res = await bookApi.getBookInfo(bookId.value)
  bookInfo.value = res.bookInfo
}

// 加载购买商品信息
async function loadGoodsInfo() {
  const res = await bookApi.getBookGoods(bookId.value)
  goodsList.value = res.productList || []
}

// 加载统计数据
async function loadBookCount() {
  const res = await bookApi.getBookReadCount(bookId.value)
  if (res.code === 0) {
    readCount.value = res.readCount || 0
    listenCount.value = res.listenCount || 0
    buyCount.value = res.buyCount || 0
  }
}

// 加载评论
async function loadComments() {
  const res = await bookApi.getBookComments(bookId.value, 1, 10)
  if (res.commentsTree && res.commentsTree.length > 0) {
    commentList.value = res.commentsTree
  } else {
    nullText.value = t('common.data_null')
  }
}

// 加载推荐书籍
async function loadRecommendBooks() {
  const res = await bookApi.getRecommendBook(bookId.value)
  if (res.bookList && res.bookList.length > 0) {
    relatedBooks.value = res.bookList
  } else {
    nullBookText.value = t('common.data_null')
  }
}

// 显示购买弹窗
function showPurchasePopup() {
  purchaseVisible.value = true
}

// 关闭购买弹窗
function closePurchasePopup() {
  purchaseVisible.value = false
}

// 处理购买
function handlePurchase(goods: IGoods) {
  uni.navigateTo({
    url: `/pages/order/goodsConfirm?goods=${goods.productId}`
  })
}

// 页面跳转
function goToReader() {
  const isBuy = bookInfo.value.isBuy ? 1 : 0
  const count = bookInfo.value.freeChapterCount || 0
  uni.navigateTo({
    url: `/pages/book/reader?isBuy=${isBuy}&bookId=${bookId.value}&count=${count}`
  })
}

function goToListen() {
  uni.navigateTo({
    url: `/pages/book/listen/index?bookId=${bookId.value}`
  })
}

function goToReview() {
  uni.navigateTo({
    url: `/pages/book/review?bookId=${bookId.value}&page=0`
  })
}

function goToDetail(id: number) {
  uni.navigateTo({
    url: `/pages/book/detail?id=${id}`
  })
}
</script>

<style lang="scss" scoped>
.book-detail-page {
  background: #fff;
  min-height: 100vh;
  
  .book-info {
    text-align: center;
    padding: 40rpx 30rpx;
    
    .cover {
      width: 300rpx;
      height: 400rpx;
      border-radius: 10rpx;
      margin: 0 auto 20rpx;
    }
    
    .title {
      display: block;
      font-size: 42rpx;
      font-weight: bold;
      line-height: 50rpx;
      padding: 20rpx 30rpx;
      color: #333;
    }
    
    .author {
      display: block;
      font-size: 32rpx;
      line-height: 34rpx;
      padding: 10rpx 0;
      color: #666;
    }
    
    .stats {
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;
      
      .stat-item {
        flex: 1;
        text-align: center;
        
        image {
          width: 40rpx;
          height: 40rpx;
          display: block;
          margin: 0 auto 10rpx;
        }
        
        text {
          display: block;
          font-size: 28rpx;
          color: #999;
        }
      }
      
      .divider {
        width: 1rpx;
        height: 45rpx;
        background: #999;
      }
    }
  }
  
  .introduction {
    padding: 40rpx 30rpx 0;
    
    .section-title {
      display: block;
      font-size: 34rpx;
      line-height: 50rpx;
      padding-bottom: 10rpx;
      color: #333;
      font-weight: 500;
    }
    
    .content {
      font-size: 30rpx;
      line-height: 46rpx;
      color: #999;
    }
  }
  
  .comments-section {
    padding: 40rpx 30rpx 0;
    
    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
      
      .section-title {
        font-size: 34rpx;
        line-height: 50rpx;
        color: #333;
        font-weight: 500;
      }
      
      .more-link {
        color: #999;
        font-size: 28rpx;
        display: flex;
        align-items: center;
      }
    }
    
    .comment-wrapper {
      background: #f7faf9;
      border-radius: 10rpx;
      padding: 20rpx;
    }
  }
  
  .related-books {
    padding: 40rpx 30rpx 40rpx;
    
    .section-title {
      display: block;
      font-size: 34rpx;
      line-height: 50rpx;
      margin-bottom: 20rpx;
      color: #333;
      font-weight: 500;
    }
    
    .book-scroll {
      white-space: nowrap;
      
      .book-list {
        display: inline-flex;
        gap: 25rpx;
        
        .book-item {
          display: inline-block;
          
          image {
            width: 150rpx;
            height: 190rpx;
            border-radius: 10rpx;
            display: block;
          }
          
          text {
            display: block;
            width: 150rpx;
            text-align: center;
            font-size: 28rpx;
            color: #333;
            line-height: 40rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            padding-top: 10rpx;
          }
        }
      }
    }
  }
  
  .empty-text {
    display: block;
    text-align: center;
    padding: 50rpx 0;
    font-size: 28rpx;
    color: #999;
  }
  
  .bottom-placeholder {
    height: 110rpx;
  }
  
  .action-bar {
    width: 100%;
    height: 110rpx;
    background: #f7faf9;
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .action-btn {
      &.read, &.listen {
        flex: 1;
        text-align: center;
        
        text {
          font-size: 30rpx;
        }
      }
      
      &.read text {
        color: #6bba6b;
      }
      
      &.listen text {
        color: #f7cb5e;
      }
      
      &.purchased, &.buy {
        flex: 1;
        padding: 0 20rpx;
      }
      
      &.buy-full {
        flex: 1;
        padding: 0 30rpx;
        text-align: center;
      }
    }
  }
  
  .purchase-popup {
    padding: 60rpx 30rpx 40rpx;
    
    .book-info-mini {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      
      image {
        width: 120rpx;
        height: 160rpx;
        border-radius: 10rpx;
      }
      
      .info {
        flex: 1;
        padding-left: 40rpx;
        
        .name {
          display: block;
          font-size: 30rpx;
          line-height: 38rpx;
          color: #333;
          max-height: 76rpx;
          overflow: hidden;
        }
        
        .price {
          display: block;
          padding-top: 20rpx;
          font-size: 36rpx;
          color: #ff4703;
          font-weight: bold;
        }
      }
    }
    
    .spec-section {
      margin-bottom: 40rpx;
      
      .spec-title {
        font-size: 30rpx;
        color: #333;
        display: block;
        margin-bottom: 20rpx;
      }
      
      .spec-item {
        border: 1rpx solid #ddd;
        padding: 20rpx;
        border-radius: 10rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        &.active {
          border-color: #54a966;
          
          text {
            color: #54a966;
          }
        }
        
        text {
          font-size: 26rpx;
          line-height: 34rpx;
          color: #333;
        }
      }
    }
  }
}
</style>
