<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<!-- <text class="search-icon"></text> -->
				<u-icon name="search" size="24" color="#C8C9CC"></u-icon>
				<input 
					class="search-input" 
					v-model="keyword" 
					placeholder="请输入关键字"
					@confirm="doSearch"
					placeholder-class="placeholder"
				/>
			</view>
		</view>
		
		<!-- 标签栏 -->
		<view class="tabs-bar">
			<view class="tab-item" 
				:class="{ active: currentTab == 0 }" 
				@click="switchTab(0)">
				未完结
			</view>
			<view class="tab-item" 
				:class="{ active: currentTab ==1}" 
				@click="switchTab(1)">
				已完结
			</view>
		</view>
		
		<!-- 讲座列表 -->
		<scroll-view class="content" scroll-y>
			<view class="lecture-card" v-for="(item, index) in lectureList" :key="index">
				<view class="card-thumbnail">
					<image class="thumbnail-img" :src="item.coverUrl" mode="aspectFill"></image>
					<!-- 直播状态角标: 0-待开播 1-直播中 2-已结束(可回放) 3-已下架 -->
					<view class="thumbnail-status" v-if="item.status === 0">
						<image mode="aspectFill" src="@/static/image/icon_tobestart.png"></image>
						<view class="status">待开播</view>
					</view>
					<view class="thumbnail-status" v-else-if="item.status === 1">
						<image mode="aspectFill" src="@/static/image/icon_goon.png"></image>
						<view class="status">直播中</view>
					</view>
					<view class="thumbnail-status status-end" v-else-if="item.status === 2">
						<view class="status">已结束</view>
					</view>
					<view class="thumbnail-status status-off" v-else-if="item.status === 3">
						<view class="status">已下架</view>
					</view>
					<view class="thumbnail-date" v-if="item.status === 0 && item.scheduledEndTime">
						<image mode="aspectFill" src="@/static/image/icon_tobestart.png"></image>
						<text class="date-text">{{ formatScheduleTime(item.scheduledEndTime) }}</text>
					</view>
				</view>
				
				<view class="card-content">
					<view class="card-title">{{ item.title }}</view>
					<!-- <view class="card-tags">
						<view class="tag-item">{{ item.category }}</view>
						<view class="tag-item">{{ item.type }}</view>
					</view> -->
					<view class="card-points">{{ item.taskLiveDto.taskIntegral||0 }} 积分</view>
					<view class="card-views" v-if="currentTab == 1">
						<text class="eye-icon"></text>
						<text>{{ item.viewCount }}</text>
					</view>
					<view class="card-action">
						<view class="action-btn" 
							v-if="item.status === 0"
							@click.stop="openChannelPicker(item)">
							去开播
						</view>
						<view class="action-btn" 
							v-else-if="item.status === 1"
							@click.stop="openChannelPicker(item)">
							继续开播
						</view>
						<view class="action-btn action-btn-replay"
							v-else-if="item.status === 2"
							@click.stop="openChannelPicker(item)">
							看回放
						</view>
						<view class="action-btn action-btn-disabled" v-else-if="item.status === 3">
							已下架
						</view>
					</view>
				</view>
			</view>
			
			<view class="no-more">没有更多了~</view>
		</scroll-view>
		
		<!-- 选择开播渠道弹窗 -->
		<view class="channel-picker-popup" v-if="showChannelPicker" @click="showChannelPicker = false">
			<view class="channel-picker-content" @click.stop>
				<view class="picker-header">
					<view class="picker-title">选择开播渠道</view>
					<view class="picker-close" @click="showChannelPicker = false">
						<image class="w32 h32" src="@/static/image/icon_cross.png" mode=""></image>
					</view>
				</view>
				
				<!-- 电脑浏览器开播 -->
				<view class="channel-option">
					
					<view class="option-content">
						<view class="x-f mb20">
							<image class="w32 h32" mode="aspectFill" src="@/static/image/icon_live_pc.png"></image>
							<view class="option-title">电脑浏览器开播</view>
						</view>
						
						<view class="option-url-wrapper">
							<text class="option-url">{{info.liveUrl}}</text>
							<view class="copy-btn" @click="copyUrl(info.liveUrl)">复制链接</view>
						</view>
						<view class="option-tips">复制至谷歌浏览器,登录账号即可开播</view>
					</view>
				</view>
				
				<!-- 微信小程序开播 -->
				<!-- <view class="channel-option">
					<view class="option-content">
						<view class="x-f mb20">
							<image class="w32 h32" mode="aspectFill" src="@/static/image/icon_live_phone.png"></image>
							<view class="option-title">微信小程序开播</view>
						</view>
						<view class="option-action">
							<view class="enter-btn" @click="enterMiniProgram">立即进入</view>
						</view>
					</view>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
import { getOnlineLectureList, getBroadcastUrl, enterMiniProgram ,getLectureDetail} from '@/api/onlineLecture'
// 直播状态 status: 0-待开播 1-直播中 2-已结束(可回放) 3-已下架
export default {
	data() {
		return {
			statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
			currentTab:0,
			showFilter: false,
            showChannelPicker: false,
			dateRange: {
				startDate: '',
				endDate: ''
			},
			tempDateRange: {
				startDate: '',
				endDate: ''
			},
			keyword:'',
			selectedTaskType: 'article', // 默认选中科普文章
			tempSelectedTaskType: 'article',
			// taskTypeOptions: [
			// 	{ label: '科普文章', value: 'article' },
			// 	{ label: '科普短视频', value: 'shortVideo' },
			// 	{ label: '科普长视频', value: 'longVideo' }
			// ],
			tabs: [
				// { label: '全部', value:''},
				{ label: '未完成', value: 0},
				// { label: '待审核', value: 0},
				{ label: '已完成', value: 1},
				// { label: '已驳回', value: 2}
			],
			lectureList: [], // 讲座列表，需在 data 中声明才能响应式更新视图
			taskList: [],
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			loading: false,
			broadcastUrl:'',
			info:{}
		}
	},
	watch: {
		showFilter(newVal) {
			if (newVal) {
				// 打开弹窗时，同步临时日期范围和任务类型为当前值
				this.tempDateRange = {
					startDate: this.dateRange.startDate,
					endDate: this.dateRange.endDate
				}
				this.tempSelectedTaskType = this.selectedTaskType
			}
		}
	},
	onLoad() {
		const doctorId=uni.getStorageSync('userInfo').doctorId
		if(doctorId){
			this.broadcastUrl='http://132.232.83.221:8083/#/live-pusher?doctorId='+doctorId
		}
	},
	onShow() {
		this.loadData()
	},
	onReachBottom() {
		this.loadMore()
	},
	methods: {
		// 将 scheduledEndTime 格式化为 03-13 16:30
		formatScheduleTime(val) {
			if (!val) return ''
			const d = new Date(val.replace(/-/g, '/'))
			if (isNaN(d.getTime())) return val
			const m = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			const h = String(d.getHours()).padStart(2, '0')
			const min = String(d.getMinutes()).padStart(2, '0')
			return `${m}-${day} ${h}:${min}`
		},
		goBack() {
			uni.navigateBack()
		},
		doSearch() {
			this.pageNum = 1
			this.hasMore = true
			this.loadData()
		},
		switchTab(value) {
			this.currentTab = value
			this.pageNum = 1
			this.hasMore = true
			this.loadData()
		},
        openChannelPicker(item) {
			this.getLectureDetail(item.id)
			this.currentLecture = item
			this.showChannelPicker = true
		},
		// 看回放：status=2 已结束(可回放) 时跳转
		goReplay(item) {
			if (item.videoUrl) {
				uni.navigateTo({
					url: `/pages_live/lessonDetail?groupId=${item.id}`
				})
			} else {
				getLectureDetail(item.id).then(res => {
					if (res.code === 200 && res.data && res.data.videoUrl) {
						uni.navigateTo({
							url: `/pages_live/lessonDetail?groupId=${item.id}`
						})
					} else {
						uni.showToast({ icon: 'none', title: '暂无回放' })
					}
				}).catch(() => {
					uni.showToast({ icon: 'none', title: '暂无回放' })
				})
			}
		},
        copyUrl(url) {
			uni.setClipboardData({
				data: url,
				success: () => {
					uni.showToast({
						icon: 'success',
						title: '链接已复制'
					})
				},fail: (err) => {
          // 复制失败提示
          uni.showToast({
            title: '复制失败，请重试',
            icon: 'none'
          })
         // console.error('复制链接失败：', err)
            }
			})
		},
		closeFilter() {
			// 关闭弹窗时，恢复临时日期范围和任务类型为当前值
			this.tempDateRange = {
				startDate: this.dateRange.startDate,
				endDate: this.dateRange.endDate
			}
			this.tempSelectedTaskType = this.selectedTaskType
			this.showFilter = false
		},
		selectTaskType(value) {
			// 如果点击的是已选中的，则取消选择
			if (this.tempSelectedTaskType === value) {
				this.tempSelectedTaskType = ''
			} else {
				this.tempSelectedTaskType = value
			}
		},
		onStartDateChange(e) {
			this.tempDateRange.startDate = e.detail.value
		},
		onEndDateChange(e) {
			this.tempDateRange.endDate = e.detail.value
		},
		resetFilters() {
			this.tempDateRange = {
				startDate: '',
				endDate: ''
			}
			this.tempSelectedTaskType = ''
		},
		getLectureDetail(id){
			getLectureDetail(id).then(
				res => {
					if(res.code==200){
						this.info=res.data;
					}else{
						uni.showToast({
							icon:'none',
							title: "请求失败",
						});
					}
				},
				rej => {}
			);
		},
		confirmFilters() {
			// 时间筛选时必须选择结束时间
			if (this.tempDateRange.startDate && !this.tempDateRange.endDate) {
				uni.showToast({
					icon: 'none',
					title: '请选择结束时间'
				})
				return
			}
			// 验证日期范围
			if (this.tempDateRange.startDate && this.tempDateRange.endDate) {
				if (new Date(this.tempDateRange.startDate) > new Date(this.tempDateRange.endDate)) {
					uni.showToast({
						icon: 'none',
						title: '开始时间不能大于结束时间'
					})
					return
				}
			}
			this.dateRange = {
				startDate: this.tempDateRange.startDate,
				endDate: this.tempDateRange.endDate
			}
			this.selectedTaskType = this.tempSelectedTaskType
			this.showFilter = false
			this.pageNum = 1
			this.hasMore = true
			this.loadData()
		},
		goComplete(item) {
			uni.navigateTo({
				url: `/pages_task/completeTask?id=${item.id}`
			})
		},
		goEdit(item) {
			uni.navigateTo({
				url: `/pages_task/completeTask?id=${item.id}&edit=true`
			})
		},
		// 查看详情
		showDetail(item) {
			uni.navigateTo({
				url: `/pages_task/taskDetail?id=${item.id}`
			})
		},
		async loadData() {
			try {
				this.pageNum = 1
				this.hasMore = true
				uni.showLoading({ title: '加载中...' })
				// 构建请求参数
				const params = {
					finishStatus:this.currentTab,
					title:this.keyword,
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}
				const res = await getOnlineLectureList(params)
				uni.hideLoading()
				if (res.code == 200) {
					this.lectureList = res.rows || []
					//.console.log('this.lectureList',this.lectureList)
					// 判断是否还有更多数据
					if (!res.rows || res.rows.length < this.pageSize) {
						this.hasMore = false
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				}
			} catch (e) {
				uni.hideLoading()
			}
		},
		async loadMore() {
			// 如果没有更多数据或正在加载，则不执行
			if (!this.hasMore || this.loading) {
				return
			}
			
			try {
				this.loading = true
				const nextPage = this.pageNum + 1
				// 构建请求参数
				const params = {
					finishStatus:this.currentTab,
					title:this.keyword,
					pageNum: nextPage,
					pageSize: this.pageSize
				}
				
				const res = await getOnlineLectureList(params)
				
				if (res.code === 200) {
					const newData = res.rows || []
					if (newData.length > 0) {
						// 追加新数据到列表
						this.lectureList = [...this.lectureList, ...newData]
						this.pageNum = nextPage
						// 如果返回的数据量小于 pageSize，说明没有更多数据了
						if (newData.length < this.pageSize) {
							this.hasMore = false
						}
					} else {
						// 没有新数据，说明已经加载完所有数据
						this.hasMore = false
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '加载失败'
					})
				}
			} catch (e) {
				console.error('加载更多数据失败', e)
				uni.showToast({
					icon: 'none',
					title: '加载失败'
				})
			} finally {
				this.loading = false
			}
		}
	}
}
</script>
<style lang="stylus">
	.placeholder{
				color: #C8C9CC !important;
			}
</style>
<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.status-bar {
	width: 100%;
	background: #fff;
}

.header {
	position: relative;
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.back-btn {
		position: absolute;
		left: 24rpx;
		width: 40rpx;
		height: 40rpx;
		
		image {
			width: 100%;
			height: 100%;
		}
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.header-right {
		position: absolute;
		right: 24rpx;
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.more-icon {
			font-size: 32rpx;
			color: #333;
		}
	}
}

.search-bar {
	padding: 24rpx;
	background: #fff;
	//border-bottom: 1rpx solid #f0f0f0;
	
	.search-input-wrapper {
		display: flex;
		align-items: center;
		height: 72rpx;
		background: #F7F8FA;
		border-radius: 36rpx;
		padding: 0 24rpx;
		
		.search-icon {
			font-size: 32rpx;
			margin-right: 16rpx;
			color: #999;
		}
		.search-input {
			flex: 1;
			font-size: 28rpx;
			color: #333;
		}
	}
}

.tabs-bar {
	display: flex;
	background: #fff;
	//border-bottom: 1rpx solid #f0f0f0;
	
	.tab-item {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		position: relative;
		
		&.active {
			color: #388BFF;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 4rpx;
				background: #388BFF;
			}
		}
	}
}

.content {
	flex: 1;
	padding: 24rpx;
	box-sizing:border-box;
}

.lecture-card {
	display: flex;
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 24rpx;
	
	.card-thumbnail {
		position: relative;
		width: 240rpx;
		height: 180rpx;
		border-radius: 12rpx;
		overflow: hidden;
		margin-right: 24rpx;
		flex-shrink: 0;
		
		.thumbnail-img {
			width: 100%;
			height: 100%;
		}
		
		.thumbnail-status {
			position: absolute;
			top: 0rpx;
			left: 0rpx;
			width: 112rpx;
			height: 32rpx;
			display: flex;
			align-items: center;
			background: rgba(0, 0, 0, 0.4);
			border-radius: 16rpx 0rpx 16rpx 0rpx;
			font-weight: 500;
			font-size: 20rpx;
			color: #FFFFFF;
			font-family: PingFang SC-Bold, PingFang SC;
			
			image {
				width: 36rpx;
				height: 32rpx;
				margin-right: 8rpx;
			};
			
			.status-text {
				font-size: 20rpx;
				color: #fff;
			}
			
			&.status-end {
				background: rgba(0, 0, 0, 0.5);
			}
			
			&.status-off {
				background: rgba(0, 0, 0, 0.6);
				color: rgba(255, 255, 255, 0.9);
			}
		}
		
		.thumbnail-date {
			position: absolute;
			top: 0rpx;
			left: 0rpx;
			width: 166rpx;
			height: 32rpx;
			display: flex;
			align-items: center;
			background: rgba(0, 0, 0, 0.4);
			border-radius: 16rpx 0rpx 16rpx 0rpx;
			font-weight: 500;
			font-size: 20rpx;
			color: #FFFFFF;
			font-family: PingFang SC-Bold, PingFang SC;
			
			image {
				width: 36rpx;
				height: 32rpx;
				margin-right: 8rpx;
			};
			
			.date-text {
				font-size: 20rpx;
				color: #fff;
			}
		}
	}
	
	.card-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		
		.card-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 12rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		
		.card-tags {
			display: flex;
			align-items: center;
			gap: 12rpx;
			margin-bottom: 12rpx;
			
			.tag-item {
				padding: 4rpx 12rpx;
				background: #f5f5f5;
				border-radius: 4rpx;
				font-size: 22rpx;
				color: #666;
			}
		}
		
		.card-points {
			font-size: 26rpx;
			color: #999;
			margin-bottom: 12rpx;
		}
		
		.card-views {
			display: flex;
			align-items: center;
			gap: 4rpx;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 12rpx;
			
			.eye-icon {
				font-size: 24rpx;
			}
		}
		
		.card-action {
			display: flex;
			justify-content: flex-end;
			
			.action-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 144rpx;
				height: 56rpx;
				background: #388BFF;
				border-radius: 34rpx 34rpx 34rpx 34rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #FFFFFF;
				
				&.action-btn-replay {
					background: #07C160;
				}
				
				&.action-btn-disabled {
					background: #C8C9CC;
					color: #fff;
				}
			}
		}
	}
}

.no-more {
	text-align: center;
	padding: 48rpx 0;
	font-size: 24rpx;
	color: #999;
}

.channel-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.channel-picker-content {
	width: 90%;
	max-width: 600rpx;
	background: #fff;
	border-radius: 24rpx;
	padding: 24rpx;
	
	.picker-header {
		display: flex;
		align-items: center;
		justify-content: center;
		// padding: 32rpx 24rpx;
		position: relative;
		margin-bottom: 32rpx;
		
		.picker-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.picker-close {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 48rpx;
			height: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			color: #999;
		}
	}
	
	.channel-option {
		display: flex;
		align-items: flex-start;
		margin-bottom: 32rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.option-icon {
			width: 64rpx;
			height: 64rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 48rpx;
			margin-right: 24rpx;
			flex-shrink: 0;
			
			&.wechat {
				background: #07C160;
				border-radius: 8rpx;
			}
		}
		
		.option-content {
			flex: 1;
			width: 100%;
			.option-title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-left:16rpx ;
				// margin-bottom: 16rpx;
			}
			
			.option-url-wrapper {
				display: flex;
				align-items: center;
				gap: 16rpx;
				margin-bottom: 16rpx;
				
				.option-url {
					flex: 1;
					padding: 16rpx 24rpx;
					background: #f5f5f5;
					border-radius: 8rpx;
					font-size: 24rpx;
					color: #666;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				
				.copy-btn {
					padding: 12rpx 24rpx;
					background: #388BFF;
					border-radius: 8rpx;
					font-size: 24rpx;
					color: #fff;
					white-space: nowrap;
				}
			}
			
			.option-tips {
				font-size: 22rpx;
				color: #999;
			}
			
			.option-action {
				display: flex;
				justify-content: flex-end;
				
				.enter-btn {
					padding: 12rpx 24rpx;
					background: #388BFF;
					border-radius: 34rpx 34rpx 34rpx 34rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}
		}
	}
}
</style>

