<template>
  <view class="listen-page">
    <!-- 导航栏 -->
    <nav-bar :title="$t('listen.title')"></nav-bar>

    <!-- 书籍信息 -->
    <view class="book-info">
      <image :src="bookInfo.images" class="cover" mode="aspectFill" />
      <view class="info">
        <text class="title">{{ bookInfo.name }}</text>
        <text class="author">{{ $t('bookDetails.authorName') }}{{ bookInfo.author?.authorName }}</text>
      </view>
      <wd-button 
        v-if="!bookInfo.isBuy && !hasVip" 
        type="primary"
        size="small"
        @click="purchaseVisible = true"
      >
        {{ $t('bookDetails.buy') }}
      </wd-button>
    </view>
    
    <!-- 章节列表 -->
    <view class="chapter-section">
      <text class="section-title">{{ $t('book.zjContents') }}</text>
      <scroll-view 
        scroll-y
        style="height: calc(100vh - 570rpx);"
      >
        <view v-if="chapterList.length > 0" class="chapter-list">
          <view 
            v-for="(chapter, index) in chapterList" 
            :key="chapter.id"
            class="chapter-item"
            :class="{ active: index === activeIndex }"
            @click="playChapter(chapter, index)"
          >
            <text class="chapter-text" :class="{ locked: isLocked(index) }">
              {{ chapter.chapter }}{{ chapter.content ? ' - ' + chapter.content : '' }}
            </text>
            <wd-icon v-if="isLocked(index)" name="lock-on" size="20px" />
          </view>
        </view>
        
        <text v-else class="empty-text">{{ nullText }}</text>
      </scroll-view>
    </view>

    <!-- 购买弹窗 -->
    <GoodsSelector
      :show="purchaseVisible"
      :goods="goodsList"
      @confirm="handlePurchase"
      @close="closePurchasePopup"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } 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, IChapter } from '@/types/book'
import type { IGoods } from '@/types/order'
import GoodsSelector from '@/components/order/GoodsSelector.vue'

const userStore = useUserStore()

// 路由参数
const bookId = ref(0)
const fromIndex = ref(-1)

// 会员状态
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 chapterList = ref<IChapter[]>([])
const activeIndex = ref(-1)
const nullText = ref('')

// 生命周期
onLoad((options: any) => {
  if (options.bookId) {
    bookId.value = Number(options.bookId)
  }
  if (options.index !== undefined) {
    fromIndex.value = Number(options.index)
    activeIndex.value = fromIndex.value
  }
  loadGoodsInfo()
})

onShow(() => {
  loadBookInfo()
  loadChapterList()
})

// 购买弹窗状态
const purchaseVisible = ref(false)
const goodsList = ref<IGoods[]>([])

// 关闭购买弹窗
function closePurchasePopup() {
  purchaseVisible.value = false
}
// 确认购买
function handlePurchase(goods: IGoods) {
  uni.navigateTo({
    url: `/pages/order/goodsConfirm?goods=${goods.productId}`
  })
}


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

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

// 加载章节列表
async function loadChapterList() {
  const res = await bookApi.getBookChapter({
    bookId: bookId.value
  })
  
  if (res.chapterList && res.chapterList.length > 0) {
    chapterList.value = res.chapterList
  } else {
    nullText.value = t('common.data_null')
  }
}

// 判断章节是否锁定
function isLocked(index: number): boolean {
  return !bookInfo.value.isBuy && index + 1 > bookInfo.value.freeChapterCount && !hasVip.value
}

// 播放章节
function playChapter(chapter: IChapter, index: number) {
  // 检查是否锁定
  if (isLocked(index)) {
    uni.showToast({
      title: t('book.afterPurchase'),
      icon: 'none'
    })
    return
  }
  
  // 检查是否有音频
  if (!chapter.voices) {
    uni.showToast({
      title: t('book.voices_null'),
      icon: 'none'
    })
    return
  }
  
  // 更新选中索引
  activeIndex.value = index
  
  // 跳转到播放器页面
  const isBuy = bookInfo.value.isBuy ? 0 : 1
  uni.navigateTo({
    url: `/pages/book/listen/player?bookId=${bookId.value}&isBuy=${isBuy}&count=${bookInfo.value.freeChapterCount}&index=${index}`
  })
}

// 去购买
function goToPurchase() {
  uni.navigateTo({
    url: `/pages/book/order?id=${bookId.value}`
  })
}
</script>

<style lang="scss" scoped>
.listen-page {
  background: #f7faf9;
  min-height: 100vh;
}

.book-info {
  margin: 20rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
  position: relative;
  
  .cover {
    width: 180rpx;
    height: 240rpx;
    border-radius: 10rpx;
    flex-shrink: 0;
  }
  
  .info {
    flex: 1;
    padding: 0 20rpx;
    
    .title {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      line-height: 44rpx;
      max-height: 88rpx;
      overflow: hidden;
    }
    
    .author {
      display: block;
      font-size: 30rpx;
      padding-top: 15rpx;
      color: #666;
    }
  }
}

.chapter-section {
  background: #fff;
  padding: 30rpx;
  min-height: 400rpx;
  
  .section-title {
    display: block;
    font-size: 34rpx;
    line-height: 50rpx;
    margin-bottom: 20rpx;
    color: #333;
    font-weight: 500;
  }
  
  .chapter-list {
    .chapter-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 18rpx 0;
      border-bottom: 1rpx solid #dcdfe6;
      
      &.active .chapter-text {
        color: #54a966;
      }
      
      .chapter-text {
        flex: 1;
        font-size: 28rpx;
        line-height: 50rpx;
        color: #333;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        
        &.locked {
          color: #999;
        }
      }
      
      &:last-child {
        border-bottom: none;
      }
    }
  }
  
  .empty-text {
    display: block;
    text-align: center;
    padding: 100rpx 0;
    font-size: 28rpx;
    color: #999;
  }
}
</style>
