<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="share-btn" @click="handleShare">
				<text class="share-icon">↗</text>
			</view>
		</view>
		
		<scroll-view class="scroll-content" scroll-y>
			<!-- 书籍信息 -->
			<view class="book-info-section" v-if="!isLoading">
				<image class="book-cover" :src="bookInfo.image || bookInfo.cover" mode="aspectFill"></image>
				<view class="book-details">
					<text class="book-title">{{ bookInfo.title }}</text>
					<text class="book-desc" v-if="bookInfo.desc || bookInfo.brief || bookInfo.introduction">{{ bookInfo.desc || bookInfo.brief || bookInfo.introduction }}</text>
					<text class="book-author" v-if="bookInfo.author">{{ bookInfo.author }}</text>
					<text class="book-narrator" v-if="bookInfo.narrator">主播：{{ bookInfo.narrator }}</text>
					<view class="action-buttons">
						<button class="play-all-btn" @click="playAll">播放全部</button>
						<button class="add-to-shelf-btn" :class="{ 'in-bookshelf': isInBookshelf }" @click="addToShelf">
							{{ isInBookshelf ? '已在书架' : '加入书架' }}
						</button>
					</view>
				</view>
			</view>
			
			<!-- 加载中 -->
			<view class="loading-section" v-if="isLoading">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 标签页 -->
			<view class="tabs">
				<view 
					class="tab-item" 
					:class="{ active: currentTab === 'catalog' }"
					@click="switchTab('catalog')"
				>
					<text class="tab-text">目录</text>
				</view>
				<view 
					class="tab-item" 
					:class="{ active: currentTab === 'comments' }"
					@click="switchTab('comments')"
				>
					<text class="tab-text">评论</text>
				</view>
			</view>
			
			<!-- 目录内容 -->
			<view class="content-section" v-if="currentTab === 'catalog'">
				<view 
					class="chapter-item" 
					v-for="(chapter, index) in chapters" 
					:key="chapter.id || index"
					@click="playChapter(chapter, index)"
				>
					<text class="chapter-number">{{ index + 1 }}.</text>
					<view class="chapter-info">
						<text class="chapter-title">{{ chapter.title }}</text>
						<view class="chapter-meta">
							<view class="chapter-status" v-if="chapter.isFree">
								<text class="status-text">免费</text>
							</view>
							<text class="chapter-lock" v-else>🔒</text>
							<text class="chapter-duration">{{ chapter.duration }}</text>
						</view>
					</view>
				</view>
				<view class="empty-chapters" v-if="!isLoading && chapters.length === 0">
					<text class="empty-text">暂无章节</text>
				</view>
			</view>
			
			<!-- 评论内容 -->
			<view class="content-section" v-if="currentTab === 'comments'">
				<view class="comment-list">
					<view class="comment-item" v-for="(comment, index) in comments" :key="index">
						<image class="comment-avatar" :src="comment.avatar" mode="aspectFill"></image>
						<view class="comment-content">
							<view class="comment-header">
								<text class="comment-name">{{ comment.name }}</text>
								<text class="comment-date">{{ comment.date }}</text>
							</view>
							<text class="comment-text">{{ comment.content }}</text>
						</view>
					</view>
				</view>
				<view class="no-comments" v-if="comments.length === 0">
					<text class="no-comments-text">暂无评论</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { getAudiobookDetail, recordListeningHistory, addAudiobookToBookshelf, checkAudiobookInBookshelf, removeAudiobookFromBookshelf } from '../../utils/api.js'
	
	export default {
		data() {
			return {
				currentTab: 'catalog',
				audiobookId: null,
				bookInfo: {
					id: null,
					title: '',
					desc: '',
					brief: '',
					introduction: '',
					author: '',
					image: '',
					cover: '',
					narrator: ''
				},
				chapters: [],
				comments: [],
				isLoading: false,
				userInfo: null,
				isInBookshelf: false,
				checkingBookshelf: false
			}
		},
		onLoad(options) {
			// 从路由参数获取audiobookId
			if (options.audiobookId) {
				this.audiobookId = parseInt(options.audiobookId)
			} else if (options.bookId) {
				// 兼容旧的bookId参数
				this.audiobookId = parseInt(options.bookId)
			}
			
			// 加载用户信息
			this.loadUserInfo()
			
			// 加载听书详情（从数据库获取完整数据）
			if (this.audiobookId) {
				this.loadAudiobookDetail()
			} else {
				uni.showToast({
					title: '听书ID不能为空',
					icon: 'none'
				})
			}
		},
		onShow() {
			// 页面显示时重新加载用户信息和书架状态
			this.loadUserInfo()
			if (this.audiobookId && this.userInfo && this.userInfo.id) {
				this.checkBookshelfStatus()
			}
		},
		methods: {
			loadUserInfo() {
				try {
					const userInfo = uni.getStorageSync('userInfo')
					const isLogin = uni.getStorageSync('isLogin')
					if (userInfo && userInfo.id && isLogin) {
						this.userInfo = userInfo
					}
				} catch (e) {
					console.error('获取用户信息失败:', e)
				}
			},
			async loadAudiobookDetail() {
				try {
					this.isLoading = true
					const userId = this.userInfo ? this.userInfo.id : null
					const res = await getAudiobookDetail(this.audiobookId, userId)
					
					if (res && res.code === 200 && res.data) {
						const data = res.data
						// 更新听书信息
						if (data.audiobook) {
							const audiobook = data.audiobook
							this.bookInfo = {
								id: audiobook.id,
								title: audiobook.title || '',
								desc: audiobook.desc || audiobook.brief || '',
								brief: audiobook.brief || audiobook.desc || '',
								introduction: audiobook.introduction || audiobook.desc || audiobook.brief || '',
								author: audiobook.author || '',
								image: audiobook.image || audiobook.cover || '',
								cover: audiobook.cover || audiobook.image || '',
								narrator: audiobook.narrator || ''
							}
							
							// 如果描述为空，使用简介作为描述
							if (!this.bookInfo.desc && this.bookInfo.brief) {
								this.bookInfo.desc = this.bookInfo.brief
							}
							
							// 如果简介为空，使用描述作为简介
							if (!this.bookInfo.brief && this.bookInfo.desc) {
								this.bookInfo.brief = this.bookInfo.desc
							}
						}
						
						// 更新章节列表
						if (data.chapters && Array.isArray(data.chapters)) {
							this.chapters = data.chapters.map(ch => ({
								id: ch.id,
								title: ch.title,
								isFree: ch.isFree || false,
								duration: ch.durationText || ch.duration || '00:00',
								durationSeconds: ch.duration || 0,
								audioUrl: ch.audioUrl || ''
							}))
						}
						
						// 加载完成后检查书架状态
						if (this.userInfo && this.userInfo.id) {
							this.checkBookshelfStatus()
						}
					}
				} catch (e) {
					console.error('加载听书详情失败:', e)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			async checkBookshelfStatus() {
				if (!this.userInfo || !this.userInfo.id || !this.audiobookId) {
					this.isInBookshelf = false
					return
				}
				
				if (this.checkingBookshelf) {
					return
				}
				
				try {
					this.checkingBookshelf = true
					const res = await checkAudiobookInBookshelf(this.userInfo.id, this.audiobookId)
					if (res && res.code === 200) {
						this.isInBookshelf = res.data === true
					}
				} catch (e) {
					console.error('检查书架状态失败:', e)
					this.isInBookshelf = false
				} finally {
					this.checkingBookshelf = false
				}
			},
			goBack() {
				uni.navigateBack()
			},
			handleShare() {
				uni.showToast({
					title: '分享功能',
					icon: 'none'
				})
			},
			switchTab(tab) {
				this.currentTab = tab
			},
			playAll() {
				const firstFreeChapter = this.chapters.find(ch => ch.isFree)
				if (firstFreeChapter) {
					const index = this.chapters.indexOf(firstFreeChapter)
					this.playChapter(firstFreeChapter, index)
				} else {
					uni.showModal({
						title: '提示',
						content: '该书籍需要VIP会员才能播放',
						showCancel: true,
						cancelText: '取消',
						confirmText: '开通VIP',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/vip/vip'
								})
							}
						}
					})
				}
			},
			async addToShelf() {
				// 检查用户是否登录
				if (!this.userInfo || !this.userInfo.id) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						showCancel: true,
						cancelText: '取消',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
						}
					})
					return
				}
				
				// 如果已在书架中，则移除
				if (this.isInBookshelf) {
					try {
						const res = await removeAudiobookFromBookshelf(this.userInfo.id, this.audiobookId)
						if (res && res.code === 200) {
							this.isInBookshelf = false
							uni.showToast({
								title: '已从书架移除',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: res.msg || '移除失败',
								icon: 'none'
							})
						}
					} catch (e) {
						console.error('移除书架失败:', e)
						uni.showToast({
							title: '移除失败，请重试',
							icon: 'none'
						})
					}
					return
				}
				
				// 添加到书架
				try {
					const res = await addAudiobookToBookshelf(this.userInfo.id, this.audiobookId)
					if (res && res.code === 200) {
						this.isInBookshelf = true
						uni.showToast({
							title: '已加入书架',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: res.msg || '加入失败',
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('加入书架失败:', e)
					if (e.message && e.message.includes('已在书架中')) {
						this.isInBookshelf = true
						uni.showToast({
							title: '已在书架中',
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: '加入失败，请重试',
							icon: 'none'
						})
					}
				}
			},
			async playChapter(chapter, index) {
				if (!chapter.isFree) {
					// 检查用户VIP状态
					if (!this.userInfo || !this.userInfo.isVip) {
						uni.showModal({
							title: '提示',
							content: '该章节需要VIP会员才能播放',
							showCancel: true,
							cancelText: '取消',
							confirmText: '开通VIP',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/vip/vip'
									})
								}
							}
						})
						return
					}
				}
				
				// 记录听书历史
				if (this.userInfo && this.userInfo.id) {
					try {
						await recordListeningHistory(this.userInfo.id, this.audiobookId, chapter.id)
					} catch (e) {
						console.error('记录听书历史失败:', e)
					}
				}
				
				// 跳转到播放页面
				uni.navigateTo({
					url: `/pages/player/player?audiobookId=${this.audiobookId}&title=${encodeURIComponent(this.bookInfo.title)}&image=${encodeURIComponent(this.bookInfo.image)}&author=${encodeURIComponent(this.bookInfo.author)}&chapterId=${chapter.id}&chapterTitle=${encodeURIComponent(chapter.title)}&audioUrl=${encodeURIComponent(chapter.audioUrl || '')}`
				})
			}
		}
	}
</script>

<style scoped>
	.container {
		width: 100%;
		height: 100vh;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		padding-top: 30px;
		box-sizing: border-box;
	}
	
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #E0E0E0;
	}
	
	.back-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.back-icon {
		font-size: 40rpx;
		color: #333333;
		font-weight: bold;
	}
	
	.share-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.share-icon {
		font-size: 36rpx;
		color: #333333;
	}
	
	.scroll-content {
		flex: 1;
		width: 100%;
	}
	
	.book-info-section {
		display: flex;
		padding: 40rpx 30rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #F0F0F0;
	}
	
	.book-cover {
		width: 200rpx;
		height: 280rpx;
		border-radius: 8rpx;
		margin-right: 30rpx;
		flex-shrink: 0;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.15);
		background-color: #F5F5F5;
	}
	
	.book-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		min-width: 0;
	}
	
	.book-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
		line-height: 1.4;
	}
	
	.book-desc {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.6;
		margin-bottom: 20rpx;
	}
	
	.book-author {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 15rpx;
	}
	
	.book-narrator {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 30rpx;
	}
	
	.loading-section {
		padding: 100rpx 30rpx;
		text-align: center;
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	.empty-chapters {
		padding: 100rpx 30rpx;
		text-align: center;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
	}
	
	.play-all-btn {
		flex: 1;
		height: 80rpx;
		background-color: #4FC3F7;
		color: #FFFFFF;
		font-size: 30rpx;
		border: none;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.play-all-btn::after {
		border: none;
	}
	
	.add-to-shelf-btn {
		flex: 1;
		height: 80rpx;
		background-color: #FFFFFF;
		color: #666666;
		font-size: 30rpx;
		border: 1rpx solid #E0E0E0;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.add-to-shelf-btn::after {
		border: none;
	}
	
	.add-to-shelf-btn.in-bookshelf {
		background-color: #F5F5F5;
		color: #999999;
		border-color: #E0E0E0;
	}
	
	.tabs {
		display: flex;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #E0E0E0;
		padding: 0 30rpx;
	}
	
	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 0;
		position: relative;
	}
	
	.tab-item.active .tab-text {
		color: #4FC3F7;
		font-weight: bold;
	}
	
	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #4FC3F7;
		border-radius: 2rpx;
	}
	
	.tab-text {
		font-size: 32rpx;
		color: #999999;
	}
	
	.content-section {
		background-color: #FFFFFF;
		padding: 0 30rpx;
	}
	
	.chapter-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #F0F0F0;
	}
	
	.chapter-item:last-child {
		border-bottom: none;
	}
	
	.chapter-number {
		font-size: 28rpx;
		color: #999999;
		margin-right: 20rpx;
		width: 40rpx;
		flex-shrink: 0;
	}
	
	.chapter-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		min-width: 0;
	}
	
	.chapter-title {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 15rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.chapter-meta {
		display: flex;
		align-items: center;
		gap: 15rpx;
	}
	
	.chapter-status {
		background-color: #4FC3F7;
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
	}
	
	.status-text {
		font-size: 20rpx;
		color: #FFFFFF;
	}
	
	.chapter-lock {
		font-size: 24rpx;
		color: #999999;
	}
	
	.chapter-duration {
		font-size: 24rpx;
		color: #999999;
	}
	
	.comment-list {
		display: flex;
		flex-direction: column;
		padding: 30rpx 0;
	}
	
	.comment-item {
		display: flex;
		margin-bottom: 40rpx;
		padding-bottom: 40rpx;
		border-bottom: 1rpx solid #F0F0F0;
	}
	
	.comment-item:last-child {
		border-bottom: none;
		padding-bottom: 0;
		margin-bottom: 0;
	}
	
	.comment-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
		flex-shrink: 0;
		background-color: #F5F5F5;
	}
	
	.comment-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		min-width: 0;
	}
	
	.comment-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
	}
	
	.comment-name {
		font-size: 28rpx;
		color: #333333;
		font-weight: bold;
	}
	
	.comment-date {
		font-size: 24rpx;
		color: #999999;
	}
	
	.comment-text {
		font-size: 28rpx;
		color: #666666;
		line-height: 1.6;
	}
	
	.no-comments {
		padding: 100rpx 0;
		text-align: center;
	}
	
	.no-comments-text {
		font-size: 28rpx;
		color: #999999;
	}
</style>


