<template>
	<view class="CoursePage">
		<custom-nav title="课程" :to-back="toBack"></custom-nav>
		<scroll-view :scroll-y="!detail.vis" class="CourseScrollBody">
			<view class="CourseBody">
				<view class="CourseHeader">
					<view class="HeaderSeason" @click="mockend">第{{ userServerInfo.season }}届培训课程表</view>
					<view class="HeaderPlayAll" @click="playAll">
						<image
							v-if="play.ing && play.all"
							src="../../static/icon/pause1.png"
							class="PlayIcon"
						/>
						<image
							v-else
							src="../../static/icon/play1.png"
							class="PlayIcon"
						>
						<view class="PlayText">全部播放</view>
					</view>
				</view>
				<view class="CourseDesc">
					快速精准提高销售能力
				</view>
				<view class="CourseWeek">
					<view
						v-for="item in weekList"
						:key="item.id"
						class="week"
						:class="params.week === item.id ? 'active' : ''"
						@click="params.week = item.id"
					>
						{{ item.name }}
					</view>
				</view>
				<view class="CourseList">
					<template v-if="courseList.length > 0">
						<view
							v-for="(item, i) in courseList"
							:key="item.id"
							class="CourseList-item"
							@click="toInfo(item, i)"
						>
							<view class="ItemTitle">
								<view>
									{{ item.course_time | dateFormatter('MM月dd日') }} 周{{ item.course_time | dateWeek }}
								</view>
								<view class="ItemTitle-status" :class="item.status ? 'active' : ''">
									{{ item.status ? '已授课' : '未授课' }}
								</view>
							</view>
							<view class="ItemInfo">
								<image :src="item.teacher_img" mode="aspectFill" class="ItemInfo-teamcher">
								<view class="Info-right">
									<view class="Right-title">{{ item.title }}</view>
									<view class="Right-teacher">{{ item.teacher_name }}</view>
									<!-- {{ item.teacher_levelname }}: -->
									<view
										class="Right-play"
										:class="item.status ? '' : 'no_open'"
									>
										<template v-if="item.status">
											<image
												v-if="play.ing && play.index === i"
												src="../../static/icon/pause2.png"
												class="Play-icon"
												@click.stop="playSelf($event,item, i)"
											/>
											<image
												v-else
												src="../../static/icon/play2.png"
												class="Play-icon"
												@click.stop="playSelf($event,item, i)"
											/>
										</template>
										<template v-else>
											<image
												src="../../static/icon/play1.png"
												class="Play-icon"
											/>
										</template>
										<view class="Play-Sound">
											<view class="SoundWave">
												<view
													v-for="ni in 20"
													:key="i + '_' + ni"
													class="Wave-line"
													:class="play.ing && play.index === i ? 'active' : ''"
												/>
											</view>
										</view>
										<view class="Play-time">{{ item.course_length | mediaTimeFormatter }}</view>
									</view>
								</view>
							</view>
						</view>
					</template>
					<template v-else>
						<view class="noTip">暂无相关课程</view>
					</template>
				</view>
			</view>
		</scroll-view>
		<view v-if="detail.vis" class="CourseAudioDetail">
			<view class="CoursePlay">
				<view class="PlayTitle">{{ detail.info.title }}</view>
				<view class="PlayTeacher">{{ detail.info.teacher_name }}</view>
				<view class="PlayCover">
					<image
						class="CoverImg"
						mode="aspectFill" 
						:src="detail.info.teacher_img"
						:class="play.ing ? 'start' : 'start paused'"
					/>
				</view>
				<view class="AudioProgress">
					<view class="Progress-left">
						<audio-slide
							class="Audio-slide"
							:allTime="Number(detail.info.course_length)"
							:playTime.sync="play.time"
							@update:progress="moveAudioPlay"
							@touchStart="audioTouch"
						/>
					</view>
					<!-- <view class="Progress-right">倍数</view> -->
				</view>
				<view class="AudioControl">
					<image src="../../static/play/prev_15.png" mode="widthFix" @click="prevTime"></image>
					<image src="../../static/play/prev.png" mode="widthFix" @click="toPrev"></image>
					<image
						v-if="!play.ing"
						src="../../static/play/play.png"
						mode="widthFix"
						@click="detailPlay"
					/>
					<image
						v-else
						src="../../static/play/pause.png"
						mode="widthFix"
						@click="detailPlay"
					/>
					<image src="../../static/play/next.png" mode="widthFix" @click="toNext"></image>
					<image src="../../static/play/next_15.png" mode="widthFix" @click="nextTime"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import AudioSlide from "../../components/audio-slide.vue"
	import { mapState } from "vuex"
	export default {
		components: {
			AudioSlide
		},
		data() {
			return {
				params: {
					page: 1,
					page_size: 15,
					week: 1,
					season: ''
				},
				courseList: [],
				weekList: [
					{ id: 0, name: '课前课'},
					{ id: 1, name: '第一周'},
					{ id: 2, name: '第二周'},
					{ id: 3, name: '第三周'},
				],
				play: {
					self: null,
					index: -1,
					all: false,
					ing: false,
					time: 0
				},
				detail: {
					vis: false,
					info: {}
				}
			}
		},
		computed: {
			...mapState(['userServerInfo'])
		},
		watch: {
			'params.week'(a) {
				this.toPause()
				this.play.ing = false
				this.play.index = -1
				this.params.page = 1
				this.getCourseList()
			},
			"play.all"(a) {
				if(a) {
					this.play.self.onEnded(() => {
						let len = this.courseList.length - 1
						if(this.play.index >= len) {
							this.play.index = 0
							this.play.all = false
							this.play.ing = false
							return false
						}
						let _i = this.play.index + 1
						if(!this.courseList[_i].status) {
							return false
						}
						this.toPlay(this.courseList[_i].course_link, () => {
							this.play.index = _i
						})
						if(this.detail.vis) {
							this.detail.info = this.courseList[_i]
						}
					})
				} else {
					this.play.self ? this.play.self.offEnded() : null
				}
			},
			"play.ing"(a) {
				if(a) {
					this.play.self.onTimeUpdate(() => {
						this.play.time = this.play.self.currentTime
					})
					this.play.self.onEnded(() => {
						if(!this.play.all) {
							this.toPause()
							this.play.time = 0
						}
					})
				} else {
					this.play.self.offTimeUpdate()
				}
			},
			"detail.info": {
				handler(a) {
					if(a.course_link) {
						this.play.self.onTimeUpdate(() => {
							this.play.time = this.play.self.currentTime
						})
						
					}
				},
				deep: true,
				immediate: true
			}
		},
		filters: {
			dateFormatter: (timestamp, fmt) => {
			    fmt = fmt || "yyyy-MM-dd";
				if(typeof timestamp === 'string') {
					timestamp = timestamp.replace(/-/g, '/')
				}
			    const $this = new Date(timestamp);
			    const o = {
			      "M+": $this.getMonth() + 1,
			      "d+": $this.getDate(),
			      "h+": $this.getHours(),
			      "m+": $this.getMinutes(),
			      "s+": $this.getSeconds(),
			      "q+": Math.floor(($this.getMonth() + 3) / 3),
			      S: $this.getMilliseconds()
			    };
			    if (/(y+)/.test(fmt)) {
			      fmt = fmt.replace(
			        RegExp.$1,
			        ($this.getFullYear() + "").substr(4 - RegExp.$1.length)
			      );
			    }
			    for (var k in o) {
			      if (new RegExp("(" + k + ")").test(fmt)) {
			        fmt = fmt.replace(
			          RegExp.$1,
			          RegExp.$1.length === 1
			            ? o[k]
			            : ("00" + o[k]).substr(("" + o[k]).length)
			        );
			      }
			    }
			    return fmt;
			},
			dateWeek(time) {
				if(typeof time === 'string') {
					time = time.replace(/-/g, '/')
				}
				let _d = new Date(time).getDay()
				let _a = ['日', '一', '二', '三', '四', '五', '六']
				return _a[_d]
			},
			mediaTimeFormatter: num => {
			    if (!num) return "00:00";
			    num = Math.floor(num);
			    let hour = Math.floor(num / 3600);
			    let minutes = Math.floor((num - hour * 3600) / 60);
			    let second = num - hour * 3600 - minutes * 60;
			    if (hour > 0) {
			      return `${hour > 9 ? hour : "0" + hour}:${
			        minutes > 9 ? minutes : "0" + minutes
			      }:${second > 9 ? second : "0" + second}`;
			    } else {
			      return `${minutes > 9 ? minutes : "0" + minutes}:${
			        second > 9 ? second : "0" + second
			      }`;
			    }
			}
		},
		onBackPress() {
			return false
		},
		destroyed() {
			this.toPause()
		},
		onLoad(e) {
			if(e.week) {
				this.params.week = Number(e.week)
			}
			uni.hideLoading()
			this.getCourseList()
			this.init()
		},
		methods: {
			audioTouch() {
				this.toPause()
			},
			mockend() {
				this.play.self.seek(212)
			},
			toBack() {
				if(this.detail.vis) {
					this.detail.time = 0
					this.detail.info = {}
					this.detail.vis = false
				} else {
					uni.navigateBack()
				}
			},
			init() {
				this.play.self = uni.createInnerAudioContext()
			},
			toPlay(src, cb) {
				this.play.ing ? this.play.self.pause() : null
				this.play.self.src = src;
				
				this.play.self.play()
				this.play.ing = true
				cb && cb()
			},
			toPause() {
				if(!this.play.ing) {
					return false
				}
				this.play.ing = false
				this.play.self.pause()
			},
			playAll() {
				if(this.courseList.length === 0) {
					uni.showModal({
						content: "没有可播放的课程",
						showCancel: false
					})
					return false
				}
				let _this = this
				if(this.play.ing) {
					if(this.play.all) {
						this.toPause()
					} else {
						if(this.play.index === -1){
							this.toPause()
						} else {
							this.play.all = true
						}
					}
					return false
				}
				if(this.play.index === -1) {
					this.toPlay(this.courseList[0].course_link, () => {
						this.play.all = true
						this.play.index = 0
					})
				} else {
					this.play.ing = true;
					this.play.self.play()
				}
			},
			playSelf(e, data, i) {
				e.stopPropagation()
				if(!data.status) {
					uni.showModal({
						content: '课程还未开始, 暂不能播放',
						showCancel: false
					})
					return false
				}
				if(this.play.ing && this.play.index === i) {
					this.toPause()
					return false
				}
				this.toPlay(data.course_link, () => {
					this.play.index = i
				})
			},
			getCourseList() {
				this.params.season = this.userServerInfo.season
				let { page, page_size, week, season } = this.params
				let params = []
				Object.keys(this.params).forEach(k => {
					params.push(`${k}=${this.params[k]}`)
				})
				let _s = params.join('&')
				this.$ajax.get(`/course/course_list?${_s}`).then(([, { data: res }]) => {
					if(res.code === 200) {
						this.courseList = res.data.list
						this.$store.commit('CHANGECOURSELIST', res.data.list)
					}
				})
			},
			toPrev() {
				if(this.play.index === 0) {
					uni.showModal({
						content: "前面没有课程了",
						showCancel: false
					})
					return false
				}
				let _i = this.play.index - 1
				if(!this.courseList[_i].status) {
					uni.showModal({
						content: "上一个课程还未开始",
						showCancel: false
					})
					return false
				}
				this.play.time = 0
				this.toPlay(this.courseList[_i].course_link, () => {
					this.play.index = _i
				})
				this.detail.info = Object.assign({}, this.courseList[_i])
			},
			toNext() {
				let max = this.courseList.length - 1
				if(this.play.index >= max) {
					uni.showModal({
						content: "后面没有课程了",
						showCancel: false
					})
					return false
				}
				let _i = this.play.index + 1
				if(!this.courseList[_i].status) {
					uni.showModal({
						content: "下一个课程还未开始",
						showCancel: false
					})
					return false
				}
				this.play.time = 0
				this.toPlay(this.courseList[_i].course_link, () => {
					this.play.index = _i
				})
				this.detail.info = Object.assign({}, this.courseList[_i])
			},
			toInfo(data, i) {
				if(!data.status) {
					uni.showModal({
						content: '课程还未开始',
						showCancel: false
					})
					return false
				}
				if(i !== this.play.index) {
					this.play.self.offTimeUpdate()
					this.play.ing ? this.toPause() : null
					this.play.index = i
					this.play.self.src = data.course_link
					this.play.time = 0
					this.play.self.seek(this.play.time)
				}
				this.detail.info = data
				this.detail.vis = true
			},
			moveAudioPlay({ value }) {
				this.play.time = value
				this.play.self.seek(value)
				this.toPlay()
			},
			prevTime() {
				this.play.time = this.play.time > 15 ? this.play.time - 15 : 0
				this.play.self.seek(this.play.time)
			},
			nextTime() {
				let max = Number(this.detail.info.course_length)
				this.play.time = this.play.time < max ? this.play.time + 15 : max
				this.play.self.seek(this.play.time)
			},
			detailPlay() {
				if(this.play.ing) {
					this.toPause()
				} else {
					this.play.self.play();
					this.play.ing = true;
				}
			}
		}
	}
</script>

<style lang="scss">
	.noTip {
		padding: 20rpx;
		text-align: center;
		width: 100%;
		color: #999999;
	}
	$rotate: 0deg;
	.CoursePage {
		@include page();
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		.CourseAudioDetail {
			@include page();
			position: fixed;
			height: 100%;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #FFFFFF;
			overflow: hidden;
			.CoursePlay {
				padding: 30px;
				width: 100%;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: flex-start;
				flex-direction: column;
				.PlayTitle {
					width: 100%;
					color: #333333;
					font-size: 40rpx;
					line-height: 60rpx;
					text-align: center;
					margin-bottom: 40rpx;
				}
				.PlayTeacher {
					color: #999999;
					font-size: 32rpx;
					line-height: 60rpx;
					text-align: center;
					margin-bottom: 40rpx;
				}
				.PlayCover {
					width: 496rpx;
					height: 496rpx;
					border-radius: 50%;
					background-color: #333333;
					padding: 26rpx;
					box-sizing: border-box;
					.CoverImg {
						display: block;
						width: 100%;
						height: 100%;
						border-radius: 50%;
						&.start {
							animation: rotate 10s 0s infinite linear;
						}
						&.paused{
							animation-play-state: paused;
						}
					}
					margin-bottom: 150rpx;
				}
				.AudioProgress {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 50rpx;
					.Progress-right {
						color: #EA4A41;
						font-size: 24rpx;
						margin-left: 30px;
					}
					.Progress-left {
						flex: 1;
						min-width: 0;
						.Audio-slide {
							margin: 0;
						}
					}
				}
				.AudioControl {
					display: flex;
					align-items: center;
					justify-content: space-between;
					width: 100%;
					image {
						&:nth-of-type(1), &:nth-last-of-type(1) {
							width: 43rpx;
							height: 38rpx;
						}
						&:nth-of-type(2), &:nth-last-of-type(2) {
							width: 38rpx;
							height: 46rpx;
						}
						&:nth-of-type(3) {
							width: 124rpx;
							height: 124rpx;
						}
					}
				}
			}
		}
		.CourseScrollBody {
			width: 100%;
			flex: 1;
			overflow: hidden;
			position: relative;
		}
	}
	.CourseBody {
		width: 100%;
		padding: 30rpx;
		box-sizing: border-box;
		.CourseHeader {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 22rpx;
			.HeaderSeason {
				flex: 1;
				overflow: hidden;
				text-overflow: hidden;
				color: #333333;
				font-size: 44rpx;
				margin-right: 20rpx;
			}
			.HeaderPlayAll {
				width: 208rpx;
				height: 68rpx;
				background-color: #F8F8F8;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 8rpx;
				.PlayIcon {
					width: 36rpx;
					height: 36rpx;
				}
				.PlayText {
					font-size: 28rpx;
					color: #999999;
					margin-left: 16rpx;
					line-height: 40rpx;
				}
			}
		}
		.CourseDesc {
			color: #999999;
			font-size: 28rpx;
			line-height: 40rpx;
			margin-bottom: 32rpx;
		}
		.CourseWeek {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 60rpx;
			.week {
				// width: 192rpx;
				padding: 0 30rpx;
				height: 68rpx;
				border-radius: 68rpx;
				text-align: center;
				line-height: 68rpx;
				background: #F8F8F8;
				color: #999999;
				font-size: 28rpx;
				&.active {
					color: #FFFFFF !important;
					background: linear-gradient(to right, #F97C55, #F44545) !important;
				}
			}
		}
		.CourseList {
			&-item {
				margin-bottom: 40rpx;
				&:nth-last-of-type(1) {
					margin-bottom: 0;
				}
				.ItemTitle {
					color: #333333;
					font-size: 32rpx;
					line-height: 44rpx;
					margin-bottom: 30rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					&-status {
						height: 44rpx;
						line-height: 44rpx;
						width: 118rpx;
						border: 2rpx solid #999999;
						color: #999999;
						text-align: center;
						font-size: 28rpx;
						box-sizing: border-box;
						&.active {
							border-color: #EA4A41 !important;
							color: #EA4A41 !important;
						}
					}
				}
				.ItemInfo {
					width: 100%;
					display: flex;
					align-items: stretch;
					justify-content: space-between;
					.ItemInfo-teamcher {
						display: block;
						width: 180rpx;
						height: 234rpx;
					}
					.Info-right {
						flex: 1;
						overflow: hidden;
						margin-left: 16rpx;
						display: flex;
						justify-content: space-between;
						flex-direction: column;
						align-items: flex-start;
						.Right-title {
							color: #333333;
							font-size: 32rpx;
							line-height: 44rpx;
						}
						.Right-teacher {
							color: #999999;
							font-size: 28rpx;
							line-height: 40rpx;
						}
						.Right-play {
							width: 422rpx;
							height: 60rpx;
							padding: 12rpx 14rpx;
							box-sizing: border-box;
							display: flex;
							align-items: center;
							background: linear-gradient(to right, #F97C55, #F44545);
							border-radius: 60rpx;
							margin-bottom: 22rpx;
							display: flex;
							align-items: center;
							justify-content: space-between;
							&.no_open {
								background: #F8F8F8 !important;
								.Play-time  {
									color: #999999 !important;
								}
								/deep/ .Wave-line {
									background: #999999 !important;
								}
							}
							.Play-icon {
								display: block;
								width: 36rpx;
								height: 36rpx;
							}
							.Play-time {
								color: #FFFFFF;
								font-size: 28rpx;
							}
							.Play-Sound {
								flex: 1;
								height: 100%;
								overflow: hidden;
								margin: 0 20rpx;
							}
						}
					}
				}
			}
		}
	}
	.SoundWave {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.Wave-line {
			width: 4rpx;
			background: #FFFFFF;
			border-radius: 4rpx;
			@for $i from 1 through 20 {
				&:nth-of-type(#{$i}) {
					height: #{random(40)}rpx;
				}
			}
			&.active {
				@for $i from 1 through 20 {
					&:nth-of-type(#{$i}) {
						animation: load 2.5s #{(random(10)*0.2)+ 1}s infinite linear;
					}
				}
			}
		}
	}
	@keyframes load {
		0% {
			height: 100%;
		}
		30% {
			height: 20%;
		}
		60% {
			height: 60%;
		}
		100% {
			height: 10%;
		}
	}
	@keyframes rotate {
		100% {
			transform: rotate(360deg);
		}
	}
</style>
