<template>
	<view class="detail-page">
		<view class="header-wrap" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-bar" :style="{ height: navBarHeight + 'px' }">
				<text class="back-btn" @click="goBack">&#8592;</text>
				<text class="nav-title">课程详情</text>
			</view>
		</view>

		<!-- 封面区 -->
		<view class="cover-area">
			<image v-if="course.coverImage && !loading" class="cover-img" :src="course.coverImage" mode="aspectFill"
				@error="course.coverError = true" />
			<view v-if="!course.coverImage || course.coverError || loading" class="cover-bg">
				<text class="cover-text">{{ (course.typeName ? course.typeName.slice(0, 2) : '团课') }}</text>
			</view>
			<view class="cover-status" :class="courseStatusClass" v-if="!loading">
				<text>{{ courseStatusText }}</text>
			</view>
		</view>

		<scroll-view class="content" scroll-y :style="{ height: 'calc(100vh - ' + totalHeaderHeight + 'px - 200px)' }">
			<view class="content-inner" v-if="!loading">

				<!-- 课程名称 -->
				<view class="title-row">
					<text class="detail-title">{{ course.courseName }}</text>
				</view>

				<!-- 信息卡片 -->
				<view class="info-card">
					<view class="info-item">
						<text class="info-label">时间</text>
						<text class="info-value">{{ formatDate(course.startTime) }} {{ formatTime(course.startTime) }} - {{ formatTime(course.endTime) }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">时长</text>
						<text class="info-value">{{ duration }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">地点</text>
						<text class="info-value">{{ course.location || '未设置' }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">人数</text>
						<text class="info-value">{{ realMemberCount }} / {{ course.maxMembers || 0 }}人</text>
					</view>
					<view class="info-item" v-if="course.storedValueAmount">
						<text class="info-label">消耗</text>
						<text class="info-value price-text">¥{{ course.storedValueAmount }}</text>
					</view>
				</view>

				<!-- 课程介绍 -->
				<view class="desc-card" v-if="course.description">
					<text class="desc-title">课程介绍</text>
					<text class="desc-content">{{ course.description }}</text>
				</view>

				<!-- 操作区 -->
				<view class="action-area">
					<button
						v-if="course.status == 0"
						class="action-btn start-btn"
						:class="{ disabled: !canStartCourse }"
						:loading="actionLoading"
						:disabled="actionLoading || !canStartCourse"
						@click="handleStartCourse"
					>
						{{ actionLoading ? '开课中...' : (canStartCourse ? '开 课' : '尚未到开课时间') }}
					</button>
					<button
						v-if="course.status == 3 || course.status == 7"
						class="action-btn end-btn"
						:class="{ disabled: !canEndCourse }"
						:loading="actionLoading"
						:disabled="actionLoading || !canEndCourse"
						@click="handleEndCourse"
					>
						{{ actionLoading ? '结课中...' : (canEndCourse ? '结 课' : '尚未到结课时间') }}
					</button>
					<button
						v-if="course.status != 0 && course.status != 3 && course.status != 7"
						class="action-btn disabled-btn"
						disabled
					>
						不可操作
					</button>
				</view>

				<view class="bottom-safe"></view>
			</view>
			<view v-else class="loading-wrap">
				<text class="loading-text">加载中...</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	const coachApi = require('../../api/coach')
	const store = require('../../store/index')
	const { resolveCoverUrl } = require('../../utils/request')

	export default {
		data() {
				return {
					statusBarHeight: 0,
					navBarHeight: 44,
					totalHeaderHeight: 44,
					courseId: '',
					loading: true,
					actionLoading: false,
					course: {},
					now: Date.now(),
					realMemberCount: 0
				}
			},
			computed: {
				duration() {
					if (!this.course.startTime || !this.course.endTime) return '--'
					const start = new Date(this.course.startTime).getTime()
					const end = new Date(this.course.endTime).getTime()
					const mins = Math.round((end - start) / 60000)
					if (mins < 60) return mins + '分钟'
					return Math.floor(mins / 60) + '小时' + (mins % 60 > 0 ? mins % 60 + '分钟' : '')
				},
				canStartCourse() {
					return (this.course.status == 0) && this.now >= new Date(this.course.startTime || 0).getTime()
				},
				canEndCourse() {
					return (this.course.status == 3 || this.course.status == 7) && this.now >= new Date(this.course.endTime || 0).getTime()
				},
				courseStatusClass() {
					const map = { 0: 'normal', 1: 'cancelled', 2: 'ended', 3: 'in-progress', 4: 'timeout', 5: 'absent', 6: 'auto-ended', 7: 'late' }
					return map[this.course.status] || ''
				},
				courseStatusText() {
					const labels = { 0: '正常', 1: '已取消', 2: '已结束', 3: '进行中', 4: '超时', 5: '教练缺席', 6: '自动结束', 7: '教练迟到' }
					return labels[this.course.status] || '未知'
				}
			},
		onLoad(options) {
			const systemInfo = uni.getSystemInfoSync()
			const statusBarHeight = systemInfo.statusBarHeight || 20
			let navBarHeight = 44
			// #ifdef MP-WEIXIN
			const menuButton = uni.getMenuButtonBoundingClientRect()
			if (menuButton) {
				navBarHeight = (menuButton.top - statusBarHeight) * 2 + menuButton.height
			}
			// #endif
			this.statusBarHeight = statusBarHeight
			this.navBarHeight = navBarHeight
			this.totalHeaderHeight = statusBarHeight + navBarHeight

			if (options && options.id) {
				this.courseId = options.id
				this.loadDetail()
			}
		},
		onShow() {
			if (!store.isLoggedIn) {
				uni.reLaunch({ url: '/pages/login/login' })
			}
		},
		methods: {
			goBack() { uni.navigateBack() },

			async loadDetail() {
				this.loading = true
				try {
					// 并行加载课程详情和实时预约列表
					const [data, bookings] = await Promise.all([
						coachApi.getCourseDetail(this.courseId),
						coachApi.getCourseBookings(this.courseId).catch(() => [])
					])
					this.course = {
						...(data || {}),
						coverImage: resolveCoverUrl((data || {}).coverImage),
						coverError: false
					}
					// 实时预约人数 = booking表中 status='0'(已预约) + status='2'(已出席) 的记录数
					const bookingsArr = Array.isArray(bookings) ? bookings : []
					this.realMemberCount = bookingsArr.filter(b => b.status === '0' || b.status === '2').length
					this.now = Date.now()
				} catch (e) {
					console.error('加载课程详情失败:', e)
					uni.showToast({ title: '加载失败', icon: 'none' })
				} finally {
					this.loading = false
				}
			},

			async handleStartCourse() {
				if (this.actionLoading) return
				this.now = Date.now()
				if (!this.canStartCourse) {
					uni.showToast({ title: '尚未到课程预计开始时间，无法开课', icon: 'none', duration: 3000 })
					return
				}
				this.actionLoading = true
				try {
					await coachApi.startCourse(this.courseId)
					uni.showToast({ title: '开课成功', icon: 'success' })
					// 刷新课程详情
					await this.loadDetail()
				} catch (err) {
					console.error('开课失败:', err)
					let msg = '开课失败'
					if (err && err.data && err.data.message) {
						msg = err.data.message
					} else if (err && err.message) {
						msg = err.message
					}
					uni.showToast({ title: msg, icon: 'none', duration: 3000 })
				} finally {
					this.actionLoading = false
				}
			},

			async handleEndCourse() {
				if (this.actionLoading) return
				this.now = Date.now()
				if (!this.canEndCourse) {
					uni.showToast({ title: '尚未到课程预计结束时间，无法结课', icon: 'none', duration: 3000 })
					return
				}
				this.actionLoading = true
				try {
					await coachApi.endCourse(this.courseId)
					uni.showToast({ title: '结课成功', icon: 'success' })
					await this.loadDetail()
				} catch (err) {
					console.error('结课失败:', err)
					let msg = '结课失败'
					if (err && err.data && err.data.message) {
						msg = err.data.message
					} else if (err && err.message) {
						msg = err.message
					}
					uni.showToast({ title: msg, icon: 'none', duration: 3000 })
				} finally {
					this.actionLoading = false
				}
			},
			formatDate(timeStr) {
				if (!timeStr) return '--'
				return timeStr.substring(0, 10)
			},
			formatTime(timeStr) {
				if (!timeStr) return '--'
				return timeStr.substring(11, 16)
			}
		}
	}
</script>

<style scoped>
	.detail-page {
		min-height: 100vh;
		background: #F5F7FA;
		overflow-x: hidden;
	}
	.header-wrap {
		background: #1A1A1A;
	}
	.nav-bar {
		padding: 0 16px;
		display: flex;
		align-items: center;
	}
	.back-btn {
		font-size: 20px;
		color: #FFFFFF;
		margin-right: 12px;
	}
	.nav-title {
		font-size: 18px;
		font-weight: 700;
		color: #FFFFFF;
	}

	.content-inner {
		padding: 0 14px;
	}
	.loading-wrap {
		display: flex;
		justify-content: center;
		padding: 60px 0;
	}
	.loading-text {
		font-size: 14px;
		color: #7A7E84;
	}

	/* 封面区 */
	.cover-area { height: 200px; position: relative; overflow: hidden; }
	.cover-img { width: 100%; height: 100%; }
	.cover-bg { width: 100%; height: 100%; background: linear-gradient(135deg, #00C853, #00BFA5); display: flex; align-items: center; justify-content: center; }
	.cover-text { font-size: 56px; font-weight: 700; color: rgba(255,255,255,0.9); }
	.cover-status {
		position: absolute;
		top: 14px;
		right: 14px;
		padding: 4px 12px;
		border-radius: 12px;
		font-size: 12px;
		font-weight: 600;
	}
	.cover-status.normal, .cover-status.in-progress, .cover-status.late {
		background: rgba(255,255,255,0.25);
		color: #FFFFFF;
	}
	.cover-status.ended, .cover-status.auto-ended {
		background: rgba(255,255,255,0.2);
		color: rgba(255,255,255,0.8);
	}
	.cover-status.cancelled, .cover-status.timeout, .cover-status.absent {
		background: rgba(244,67,54,0.2);
		color: #FFCDD2;
	}

	/* 课程名称 */
	.title-row {
		padding: 0 4px;
		margin-bottom: 12px;
	}
	.detail-title {
		font-size: 20px;
		font-weight: 700;
		color: #1E1E1E;
	}

	/* 信息卡片 */
	.info-card {
		background: #FFFFFF;
		border-radius: 16px;
		padding: 16px;
		margin-bottom: 14px;
		box-shadow: 0 4px 12px rgba(0,0,0,0.06);
	}
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 0;
		border-bottom: 1px solid #F0F0F0;
	}
	.info-item:last-child {
		border-bottom: none;
	}
	.info-label {
		font-size: 14px;
		color: #7A7E84;
	}
	.info-value {
		font-size: 14px;
		color: #1E1E1E;
		font-weight: 500;
		text-align: right;
		flex: 1;
		margin-left: 12px;
	}
	.price-text {
		color: #00C853;
		font-weight: 700;
		font-size: 16px;
	}

	/* 课程介绍 */
	.desc-card {
		background: #FFFFFF;
		border-radius: 16px;
		padding: 16px;
		margin-bottom: 14px;
		box-shadow: 0 4px 12px rgba(0,0,0,0.06);
	}
	.desc-title {
		font-size: 16px;
		font-weight: 700;
		color: #1E1E1E;
		display: block;
		margin-bottom: 8px;
	}
	.desc-content {
		font-size: 14px;
		color: #7A7E84;
		line-height: 1.6;
	}

	/* 操作区 */
	.action-area {
		padding: 10px 0 20px;
	}
	.action-btn {
		width: 100%;
		height: 50px;
		border-radius: 40px;
		font-size: 17px;
		font-weight: 700;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;
	}
	.action-btn::after { border: none; }
	.start-btn {
		background: #00E676;
		color: #1A1A1A;
		box-shadow: 0 4px 16px rgba(0,230,118,0.35);
	}
	.start-btn.disabled {
		background: #E0E0E0;
		color: #9E9E9E;
		box-shadow: none;
	}
	.end-btn {
		background: #FF9800;
		color: #FFFFFF;
		box-shadow: 0 4px 16px rgba(255,152,0,0.35);
	}
	.end-btn.disabled {
		background: #E0E0E0;
		color: #9E9E9E;
		box-shadow: none;
	}
	.disabled-btn {
		background: #E0E0E0;
		color: #9E9E9E;
	}

	.bottom-safe {
		height: 30px;
	}
</style>
