<template>
  <view class="audio-player-page">
    <!-- 导航栏 -->
    <nav-bar :title="currentChapter.chapter"></nav-bar>
    
    <view class="player-content" :style="{ height: contentHeight + 'px' }">
      <!-- 文字内容区域 -->
      <scroll-view 
        class="content-section" 
        scroll-y 
        :scroll-into-view="scrollIntoViewId"
      >
        <view id="content-top">
          <text class="content-text">{{ currentContent }}</text>
        </view>
      </scroll-view>
      
      <!-- 进度条 -->
      <view class="progress-section">
        <text class="time">{{ formatTime(currentTime) }}</text>
        <slider 
          :value="progress"
          :max="100"
          activeColor="#54a966"
          backgroundColor="#e0e0e0"
          block-color="#54a966"
          block-size="12"
          @change="onProgressChange"
          @changing="onProgressChanging"
        />
        <text class="time">{{ formatTime(duration) }}</text>
      </view>
      
      <!-- 播放控制 -->
      <view class="controls">
        <view class="control-btn" @click="prevChapter">
          <wd-icon name="previous" size="32px"></wd-icon>
        </view>
        <view class="control-btn play-btn" @click="togglePlay">
          <wd-icon 
            :name="isPlaying ? 'pause-circle' : 'play-circle'" 
            size="60px"
          />
        </view>
        <view class="control-btn" @click="nextChapter">
          <wd-icon name="next" size="32px"></wd-icon>
        </view>
        <view class="control-btn" style="position: absolute; right: 20px;" @click="changeChapter">
          <wd-icon name="menu-fold" size="32px"></wd-icon>
        </view>
      </view>
      
      <!-- 播放速度 -->
      <!-- <view class="speed-control">
        <text class="speed-label">{{ $t('listen.speed') }}</text>
        <view class="speed-options">
          <view 
            v-for="speed in speeds" 
            :key="speed"
            class="speed-btn"
            :class="{ active: playbackRate === speed }"
            @click="changeSpeed(speed)"
          >
            <text>{{ speed }}x</text>
          </view>
        </view>
      </view> -->
    </view>
    <!-- 章节选择弹窗 -->
    <wd-popup v-model="showChapterSelect" position="bottom" custom-style="height: 60vh;">
      <view class="chapter-select-modal">
        <view class="chapter-modal-header">
          <text class="chapter-modal-title">{{ t('listen.chapterList') }}</text>
        </view>
        <scroll-view scroll-y class="chapter-list">
          <view 
            v-for="(chapter, index) in chapterList" 
            :key="chapter.id" 
            class="chapter-item"
            :class="{ 'chapter-item-active': currentChapterIndex === index }"
            @click="selectChapter(index)"
          >
            <text class="chapter-title" :class="{ locked: isLocked(index) }">{{ chapter.chapter }}</text>
            <wd-icon v-if="isLocked(index)" name="lock-on" size="20px" />
          </view>
        </scroll-view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/stores/user'
import { bookApi } from '@/api/modules/book'
import type { IBookDetail, IChapter } from '@/types/book'

const { t } = useI18n()
const userStore = useUserStore()

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

// 路由参数
const bookId = ref(0)
const isBuy = ref('0')
const count = ref(0)
const startIndex = ref(0)

// 数据状态
const bookInfo = ref<IBookDetail>({
  id: 0,
  name: '',
  images: '',
  author: { authorName: '', introduction: '' },
  isBuy: false,
  freeChapterCount: 0
})
const chapterList = ref<IChapter[]>([])
const currentChapterIndex = ref(0)
const currentChapter = ref<IChapter>({
  id: 0,
  chapter: '',
  content: '',
  voices: ''
})

// 内容相关
const currentContent = ref('') // 当前显示的文字内容
const contentDataList = ref<any[]>([]) // 章节内容数据列表
const voicesTimeList = ref<number[]>([]) // 音频时间点数组
const scrollIntoViewId = ref('') // 滚动控制

// 音频状态
const audioContext = ref<UniApp.InnerAudioContext | null>(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const progress = ref(0)
const playbackRate = ref(1)
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 2]
const contentHeight = ref(0)
const isChanging = ref(false)
const showChapterSelect = ref(false)

// 生命周期
onLoad((options: any) => {
  if (options.bookId) bookId.value = Number(options.bookId)
  if (options.isBuy) isBuy.value = options.isBuy
  if (options.count) count.value = Number(options.count)
  if (options.index !== undefined) {
    startIndex.value = Number(options.index)
    currentChapterIndex.value = startIndex.value
  }
  
  initContentHeight()
  loadBookInfo()
  loadChapterList()
})

onMounted(() => {
  initAudioContext()
})

onHide(() => {
  if (audioContext.value) {
    audioContext.value.pause()
  }
})

onUnload(() => {
  if (audioContext.value) {
    audioContext.value.destroy()
  }
})

// 初始化内容高度
function initContentHeight() {
  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
  contentHeight.value = systemInfo.windowHeight - totalNavHeight
}

// 初始化音频上下文
function initAudioContext() {
  audioContext.value = uni.createInnerAudioContext()
  
  audioContext.value.onPlay(() => {
    isPlaying.value = true
  })
  
  audioContext.value.onPause(() => {
    isPlaying.value = false
  })
  
  audioContext.value.onStop(() => {
    isPlaying.value = false
  })
  
  let lastUpdateTime = -1
  let lastContentIndex = -1
  
  audioContext.value.onTimeUpdate(() => {
    if (!isChanging.value && audioContext.value) {
      currentTime.value = audioContext.value.currentTime
      duration.value = audioContext.value.duration
      if (duration.value > 0) {
        progress.value = (currentTime.value / duration.value) * 100
      }
      
      // 根据音频时间更新文字内容
      const currentTimeFloor = Math.floor(currentTime.value)
      if (currentTimeFloor !== lastUpdateTime) {
        lastUpdateTime = currentTimeFloor
        
        // 查找当前时间对应的内容索引
        const contentIndex = voicesTimeList.value.indexOf(currentTimeFloor)
        if (contentIndex !== -1 && contentIndex !== lastContentIndex) {
          lastContentIndex = contentIndex
          if (contentDataList.value[contentIndex]) {
            currentContent.value = contentDataList.value[contentIndex].content || ''
          }
        }
      }
    }
  })
  
  audioContext.value.onEnded(() => {
    // 自动播放下一章
    nextChapter()
  })
  
  audioContext.value.onError((err) => {
    console.error('Audio error:', err)
    uni.showToast({
      title: '播放失败',
      icon: 'none'
    })
  })
}

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

// 加载章节列表
async function loadChapterList() {
  try {
    const res = await bookApi.getBookChapter({
      bookId: bookId.value
    })
    
    console.log('章节列表响应:', res)
    
    if (res.chapterList && res.chapterList.length > 0) {
      chapterList.value = res.chapterList
      
      // 加载当前章节内容
      if (currentChapterIndex.value < chapterList.value.length) {
        const currentChapter = chapterList.value[currentChapterIndex.value]
        console.log('当前章节:', currentChapter)
        
        await loadChapterContent(currentChapter.id)
        playChapter(currentChapter)
      }
    } else {
      uni.showToast({
        title: '章节列表为空',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('Failed to load chapter list:', error)
    uni.showToast({
      title: '加载章节失败',
      icon: 'none'
    })
  }
}

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

// 加载章节内容（带音频时间点）
async function loadChapterContent(chapterId: number) {
  try {    
    console.log('加载章节内容, chapterId:', chapterId)
    const res = await bookApi.getChapterContentListen(chapterId)
    console.log('章节内容响应:', res)
    
    if (res.bookChapterContents && res.bookChapterContents.length > 0) {
      contentDataList.value = res.bookChapterContents
      
      // 提取音频时间点数组
      voicesTimeList.value = res.bookChapterContents.map((item: any) => 
        Number(item.voicesStart || 0)
      )
      
      console.log('音频时间点数组:', voicesTimeList.value)
      
      // 显示第一段内容
      if (res.bookChapterContents[0]) {
        currentContent.value = res.bookChapterContents[0].content || ''
        console.log('第一段内容:', currentContent.value.substring(0, 50))
      }
      
      // 滚动到顶部
      scrollToTop()
    } else {
      console.log('章节内容为空')
      currentContent.value = '暂无内容'
    }
  } catch (error) {
    console.error('Failed to load chapter content:', error)
    uni.showToast({
      title: '加载内容失败',
      icon: 'none'
    })
  }
}

// 滚动到顶部
function scrollToTop() {
  scrollIntoViewId.value = 'content-top'
  setTimeout(() => {
    scrollIntoViewId.value = ''
  }, 300)
}

// 播放章节
function playChapter(chapter: IChapter) {
  console.log('播放章节:', chapter)
  
  if (!chapter.voices) {
    console.log('章节没有音频文件')
    uni.showToast({
      title: t('book.voices_null'),
      icon: 'none'
    })
    return
  }
  
  currentChapter.value = chapter
  
  if (audioContext.value) {
    console.log('设置音频源:', chapter.voices)
    
    audioContext.value.src = chapter.voices
    audioContext.value.playbackRate = playbackRate.value
    
    // 监听音频准备就绪
    audioContext.value.onCanplay(() => {
      console.log('音频准备就绪')
    })
    
    audioContext.value.play()
  } else {
    console.log('音频上下文未初始化')
  }
}

// 切换播放/暂停
function togglePlay() {
  if (!audioContext.value) return
  
  if (isPlaying.value) {
    audioContext.value.pause()
  } else {
    audioContext.value.play()
  }
}

// 上一章
async function prevChapter() {
  if (currentChapterIndex.value > 0 && !isLocked(currentChapterIndex.value - 1)) {
    currentChapterIndex.value--
    await loadChapterContent(chapterList.value[currentChapterIndex.value].id)
    playChapter(chapterList.value[currentChapterIndex.value])
  } else {
    uni.showToast({
      title: t('listen.isFirst'),
      icon: 'none'
    })
  }
}

// 下一章
async function nextChapter() {
  // 检查是否锁定
  if (isLocked(currentChapterIndex.value + 1)) {
    uni.showToast({
      title: t('book.afterPurchase'),
      icon: 'none'
    })
    // uni.showModal({
    //   title: t('common.limit_title'),
    //   content: t('book.afterPurchase'),
    //   confirmText: t('common.confirm_text'),
    //   success: (res) => {
    //     if (res.confirm) {
    //       uni.navigateTo({
    //         url: `/pages/book/order?id=${bookId.value}`
    //       })
    //     }
    //   }
    // })
    return
  }
  
  if (currentChapterIndex.value < chapterList.value.length - 1) {
    currentChapterIndex.value++
    await loadChapterContent(chapterList.value[currentChapterIndex.value].id)
    playChapter(chapterList.value[currentChapterIndex.value])
  } else {
    uni.showToast({
      title: t('listen.isLast'),
      icon: 'none'
    })
  }
}

// 快退
function rewind() {
  if (audioContext.value) {
    const newTime = Math.max(0, currentTime.value - 15)
    audioContext.value.seek(newTime)
  }
}

// 快进
function fastForward() {
  if (audioContext.value) {
    const newTime = Math.min(duration.value, currentTime.value + 15)
    audioContext.value.seek(newTime)
  }
}

// 进度条改变中
function onProgressChanging(e: any) {
  isChanging.value = true
  const value = e.detail.value
  progress.value = value
  if (duration.value > 0) {
    currentTime.value = (value / 100) * duration.value
  }
}

// 进度条改变完成
function onProgressChange(e: any) {
  const value = e.detail.value
  if (audioContext.value && duration.value > 0) {
    const newTime = (value / 100) * duration.value
    audioContext.value.seek(newTime)
    
    // 更新文字内容
    const seekTimeFloor = Math.floor(newTime)
    for (let i = voicesTimeList.value.length - 1; i >= 0; i--) {
      if (seekTimeFloor >= voicesTimeList.value[i]) {
        if (contentDataList.value[i]) {
          currentContent.value = contentDataList.value[i].content || ''
        }
        break
      }
    }
    
    // 滚动到顶部
    scrollToTop()
  }
  setTimeout(() => {
    isChanging.value = false
  }, 100)
}

// 改变播放速度
function changeSpeed(speed: number) {
  playbackRate.value = speed
  if (audioContext.value) {
    audioContext.value.playbackRate = speed
  }
}

// 切换章节
function changeChapter() {
  showChapterSelect.value = true
}

// 选择章节
async function selectChapter(index: number) {
  if (index === currentChapterIndex.value) {
    showChapterSelect.value = false
    return
  }
  
  // 检查是否锁定
  if (isLocked(index)) {
    uni.showToast({
      title: t('book.afterPurchase'),
      icon: 'none'
    })
    return
  }
  
  // 更新当前章节索引
  currentChapterIndex.value = index
  
  // 关闭弹窗
  showChapterSelect.value = false
  
  // 加载章节内容
  await loadChapterContent(chapterList.value[index].id)
  
  // 播放选中的章节
  playChapter(chapterList.value[index])
}

// 格式化时间
function formatTime(seconds: number): string {
  if (!seconds || isNaN(seconds)) return '00:00'
  
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
</script>

<style lang="scss" scoped>
.audio-player-page {
  background: linear-gradient(180deg, #fdfcfb 30%, #eef0cf 100%);
  min-height: 100vh;
  
  .player-content {
    display: flex;
    flex-direction: column;
    padding: 40rpx 40rpx;
    
    .content-section {
      flex: 1;
      height: 600rpx;
      margin-bottom: 60rpx;
      padding: 30rpx;
      border-radius: 20rpx;
      
      .content-text {
        display: block;
        font-size: 36rpx;
        line-height: 60rpx;
        color: #333;
        letter-spacing: 0.1rem;
        text-align: justify;
      }
    }
    
    .progress-section {
      display: flex;
      align-items: center;
      gap: 20rpx;
      margin-bottom: 60rpx;
      
      .time {
        font-size: 24rpx;
        color: #999;
        width: 80rpx;
        text-align: center;
      }
      
      slider {
        flex: 1;
      }
    }
    
    .controls {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 40rpx;
      margin-bottom: 60rpx;
      
      .control-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #54a966;
        
        &.play-btn {
          width: 120rpx;
          height: 120rpx;
          border-radius: 50%;
          background: #54a966;
          box-shadow: 0 8rpx 20rpx rgba(84, 169, 102, 0.3);
          
          ::v-deep .wd-icon {
            color: #fff !important;
          }
        }
      }
    }
    
    .speed-control {
      text-align: center;
      
      .speed-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
      }
      
      .speed-options {
        display: flex;
        justify-content: center;
        gap: 20rpx;
        flex-wrap: wrap;
        
        .speed-btn {
          padding: 10rpx 30rpx;
          border: 1rpx solid #ddd;
          border-radius: 50rpx;
          
          &.active {
            background: #54a966;
            border-color: #54a966;
            
            text {
              color: #fff;
            }
          }
          
          text {
            font-size: 26rpx;
            color: #666;
          }
        }
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 章节选择弹窗样式
.chapter-select-modal {
  height: 100%;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chapter-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.chapter-modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.chapter-modal-close {
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chapter-list {
  flex: 1;
  padding: 0 20px;
}

.chapter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.chapter-item:last-child {
  border-bottom: none;
}

.chapter-title {
  flex: 1;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &.locked {
    color: #999;
  }
}

.chapter-item-active .chapter-title {
  color: #54a966;
  font-weight: 500;
}
</style>
