<template>
	<view class="courseContent" v-if="loading">
		<view class="course-top">
		
			<video id="myVideo"
			  v-if="selectcourse.Type==1"
			  :src="selectcourse.FilePath"
			  @error="videoErrorCallback"  controls
			  enable-play-gesture='true'
			  show-center-play-btn='false'
			  :controls= "selectcourse.IsPay !=1 ? false:true"
			  :enable-progress-gesture="selectcourse.IsPay !=1 ? false:true"
			  @play='play'
			></video>
			<view class="studybg"  v-if="selectcourse.Type==1 && selectcourse.IsPay !=1 && studybg==true">
				<text style="font-size: 13px;color: #FFF;" v-if="studytext=='立即购买'">试看结束</text>
				<text style="font-size: 13px;color: #FFF;" v-if="studytext=='立即去支付'">已有订单信息</text>
				<view class="studybg-t" @click="trysee()" :style="{'background':mc}">
					<text>{{studytext}}</text>
				</view>
			</view>
		    <view  v-if="selectcourse && selectcourse.Type!=1" class="studyimg">
			   <image @click="previewImage(index)" 
			   v-if="selectcourse && selectcourse.ImageList.length>0 && selectcourse.ImageList[0].Path"  
			   style="width:100%;height:100%;" :src="selectcourse.ImageList[0].Path" mode=""></image>
			   <image style="width:100%;height:100%;" v-else src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/xuexibanner%20.png" mode=""></image>
			   
		    </view>
			   
		</view>
		<view class="course-t">
			<view   class="course-t-item">
				<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/fengx.png" class="share-icon" />
				<text>分享</text>
			</view>
			<view class="course-t-item" @click="setFavorite">
				<image v-if='favorite' src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/collect.png" class="share-icon" />
				<image v-else src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/nocollect.png" class="share-icon" />
				
				<text>收藏</text>
			</view>
			<!-- <view class="course-t-item">
				<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/huanc.png" class="share-icon" />
				<text>缓存</text>
			</view> -->
			<button style="width: 50%;height: 80%;position: absolute;left: 0,top:0;opacity: 0;" open-type="share"></button>
		</view>
		<view style="width: 100%;height: 15px;background: #FAF8F9;"></view>
		<view class="title">
			<view style=" overflow: hidden;
			  text-overflow: ellipsis;
			  display: -webkit-box;
			  -webkit-line-clamp: 1;
			  -webkit-box-orient: vertical;
			  color: #1C1E1F;
			  font-size: 16px;">{{name}}</view>
			<span style='font-size: 12px;color: #888888;'>共{{courseList.length}}课时</span>
		</view>
		<view style="width: 100%;height: 1px;background: #E2E2E2;"></view>
		<view v-if="courseList.length > 0" style="
		  
		  width: 100%;
		  overflow: hidden;
		">
					<!-- <scroll-view :scroll-y="true" :enable-back-to-top="true" :enable-flex="true" 
					 style="height: 100%;"> -->
						<view class="scrollitem" v-for="(cl, ci) in courseList" :key="ci" @click="gocourse(cl,ci)" >
							<view class="catalog-box-l" :style="{color:index==ci?'#00D6A6':(cl.IsRead==1&& cl.IsPay==1?'#999999':'#121212')}">
								<view style="min-width: 40px;display: flex;">
									<view class="cb-l-bt" :style="{border:index==ci?'0.5px solid #00D6A6':(cl.IsRead==1&& cl.IsPay==1?'0.5px solid #999999':'0.5px solid #121212')}">{{cl.TypeName}}</view>
								</view>
							  
							  {{cl.SortName}}：{{cl.Name}}
							</view>
							<!-- IsPay 0不可看    1已付款   2已下单 -->
							
							<view :style="{color:mc}" class="catalog-box-r" v-if="cl.IsPay!=1 && cl.IsTrySee==1">
								可试看
							</view>
							<view  class="catalog-box-r" v-if="cl.IsPay!=1 && cl.IsTrySee==2">
								<image  style="width:15px;height:15px;" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/suo.png" mode=""></image>
							</view>
						</view>
						<u-loadmore  :status="status" :load-text="loadText" :font-size="24" :margin-top="20"
						 :margin-bottom="20" bg-color="#FFF" />
						
					<!-- </scroll-view> -->
				</view>
		
		
		<coupon
		  v-if="showCoupons"
		  :coupon-message="couponMessage"
		  @goLook="goLook"
		  @closeBtn="closeBtn"
		></coupon>
	</view>
</template>

<script>
	import coupon from "@/components/coupons/coupons";
	export default {
		components: {
		  coupon,
		},
		data(){
			return{
				pageTitle:'学习',
				loading:false,
				mc:'',
				pricecolor:'',
				secondary:'',
				paddingHTop:0,
				id:0,
				courseList:[],
				index:0,
				name:'',
				selectcourse:{},
				favorite:false,//是否收藏
				timer:null,
				showCoupons: false,
				couponMessage: "",
				img:[],
				studybg:true,
				studytext:'立即试看',
				status: "nomore",
				loadText: {
					loadmore: "轻轻上拉，加载更多",
					loading: "努力加载中",
					nomore: "没有更多了",
				},
				cover_pic:'',
				count:0,
				learned:0,
				Up:0,
			}
		},
		onLoad(options) {
			console.log(options,'options')
			if(options && options.id){
				this.id = options.id
			}
			if(options && options.index){
				this.index = options.index
			}
			if(options && options.name){
				this.name = options.name
			}
			if(options && options.cover_pic){
				this.cover_pic = options.cover_pic
			}
				
				this.getGoodsCourseList()//获取课程目录
				this.getAppletCourseCollect()//获取课程是否收藏
				this.setMyStudyTime()//增加课程学习时间
				this.timer = setInterval(()=>{
					this.setMyStudyTime(10)
				},10000)
				
			
			// 多反了个字段  IsRead   是否已学习， 1是   2否
		},
		created() {
			this.mc = this.$uiConfig.mainColor;
			this.pricecolor = this.$uiConfig.pricecolor;
			this.secondary = this.$uiConfig.secondary;
			this.nav = uni.getMenuButtonBoundingClientRect().top;
			this.paddingHTop = this.nav +'px';
			uni.setNavigationBarTitle({
			  title: this.pageTitle,
			});
			this.Up = uni.getStorageSync("mall_UserInfo")?uni.getStorageSync("mall_UserInfo").UserPageType:0;//用于分享出去的参数
		},
		onUnload(){//监听页面卸载
			if(this.timer) {  
				clearInterval(this.timer);  
				this.timer = null;  
				console.log('清楚定时器')
			}  
		},
		onReady: function (res) {
		        this.videoContext = uni.createVideoContext('myVideo')
		},
		methods:{
			onShareAppMessage() {
				setTimeout(() => {
				  console.log("分享朋友调用");
				  this.getReceive();
				}, 2500);
				let u = uni.getStorageSync("mall_UserInfo");
				let uid = u.UserId ? u.UserId : 0;
				if(uid==0){
					uid = uni.getStorageSync("pid")?uni.getStorageSync("pid").pid:0
				}
				let SmallShopId = u.SmallShopId ? u.SmallShopId : 0;
				if(SmallShopId == 0){//如果微店id为0 去找所属微店id
					SmallShopId = u.UserSmallShopId? u.UserSmallShopId:0
				}
			    return {
				   title: this.name,
				   path: "/pages/index/index?id=" + this.id + "&user_id=" + uid+ "&SmallShopId=" + SmallShopId+ "&Up=" + this.Up+'&JumpType=5',
				   imageUrl: this.cover_pic,
			    };	
			},
			//图片预览和文档的打开
			previewImage(index=0) {
				
				if(this.selectcourse.IsPay!=1){
					if(this.img.length>0){
						uni.previewImage({
						 urls: this.img,
						 current: index,
						});
					}
				}else{
					uni.showLoading({
					    title: '下载中'
					});
					uni.downloadFile({
					  url: this.selectcourse.FilePath,
					  success: function (res) {
						uni.showLoading({
						    title: '正在打开'
						});
						var filePath = res.tempFilePath;
						uni.openDocument({
						  filePath: filePath,
						  success: function (res) {
							uni.hideLoading()
							console.log('打开文档成功');
						  },
						  fail:function(){
							uni.hideLoading()  
						  }
						});
					  },
					  fail:function(){
						uni.hideLoading()
					  }
					});
				}
				  
			},
			goback(){
				uni.navigateBack({})
			},
			getGoodsCourseList(){
				
				this.request2({
						url: '/api/AppletSchool/GetAppletGoodsCourseList',
						data: {GoodsId: this.id, pageIndex	:1,pageSize:10000}
					},
					res => {
						this.courseList = res.data.pageData;
						if(this.courseList.length>0){
							this.courseList.forEach(x=>{
								if(x.ImageList.length>0){
									x.ImageList.forEach(j=>{
										if(j.Path!='' && j.Path.indexOf('http://') ==-1){//对图片地址的不对做处理
											j.Path= j.Path.replace('http:/','http://')
										}
									})
								}
							})
							
							this.selectcourse=this.courseList[this.index];
							this.count =res.data.count;
							this.img=[];
							this.courseList[this.index].ImageList.forEach((x) => {
							  this.img.push(x.Path);	
							});
							this.loading=true;
							
							this.learned=0;
							this.courseList.forEach(x=>{
								if(x.IsRead==1){
									this.learned++;
								}
							})
							if(this.selectcourse.IsRead==0){
								this.learned++;
							}
							let obj = {
								id:this.id,
								name:this.name,
								cover_pic:this.cover_pic,
								Sort:this.selectcourse.Sort,
								learned:this.learned,
								count:this.count,
							}
							uni.setStorageSync("laststudy", obj);
							this.setMyCourseStudyOK()//课程已阅读
						}
					}
				);
			},
			getAppletCourseCollect(){
				this.request2({
						url: '/api/AppletSchool/GetAppletCourseCollect',
						data: {GoodsId: this.id,}
					},
					res => {
						this.favorite =res.data.Favorite
					}
				);
			},
			setFavorite(){//设置喜欢
				this.request2(
					{
						url: '/api/AppletUser/SetUserCollectionInfo',
						data: {
							GoodsId: this.id
						}
					},
					res => {
						this.favorite = !this.favorite;
					}
				);
			},
			 videoErrorCallback: function(e) {
				uni.showModal({
					content: e.target.errMsg,
					showCancel: false
				})
			},
			gocourse(item,index){
				
				if(item.IsPay!=1){//判断是否购买
					if(item.IsTrySee==1){//试看的情况
						this.index = index;
						this.selectcourse=item;
						this.img=[];
						item.ImageList.forEach((x) => {
						  this.img.push(x.Path);	
						});
						this.studybg = true;
						this.studytext='立即试看'
						if(this.selectcourse.IsRead==0){
							this.learned++;
						}
						let obj = {
							id:this.id,
							name:this.name,
							cover_pic:this.cover_pic,
							Sort:this.selectcourse.Sort,
							learned:this.learned,
							count:this.count,
						}
						uni.setStorageSync("laststudy", obj);
						this.setMyCourseStudyOK()//在换章节的时候标记 
					}else{
						let that =this
						if(item.IsPay==2){//判断是否下单
							uni.showModal({
							    title: '提示',
							    content: '已下单,去订单列表付款?',
							    success: function (res) {
							        if (res.confirm) {
							            uni.navigateTo({
							            	url:'/pages/school/personal/orderList?status=1'
							            })
							        } else if (res.cancel) { }
							    }
							});
						}else{
							
							uni.showModal({
							    title: '提示',
							    content: '购买后观看，是否去购买?',
							    success: function (res) {
							        if (res.confirm) {
							            let DetailList = [];
							            let obj={
							            	GoodsId:that.id,
							            	Number:1,
							            }
							            DetailList.push(obj)
							            uni.navigateTo({
							            	url:'/pages/school/course-submit?DetailList='+encodeURIComponent(JSON.stringify(DetailList))
							            })
							        } else if (res.cancel) { }
							    }
							});
						}
						
					}
				} else{
					this.index = index;
					this.selectcourse=item
					this.img=[];
					item.ImageList.forEach((x) => {
					  this.img.push(x.Path);	
					});
					if(this.selectcourse.IsRead==0){
						this.learned++;
					}
					let obj = {
						id:this.id,
						name:this.name,
						cover_pic:this.cover_pic,
						Sort:this.selectcourse.Sort,
						learned:this.learned,
						count:this.count,
					}
					uni.setStorageSync("laststudy", obj);
					
					this.setMyCourseStudyOK()//在换章节的时候标记 
				}
				
			},
			setMyStudyTime(time=1){
				this.request2({
						url: '/api/AppletEducation/SetMyStudyTime',
						data: {GoodsId: this.id,Time:time}
					},
					res => { }
				);
			},
			setMyCourseStudyOK(){
				this.request2({
						url: '/api/AppletEducation/SetMyCourseStudyOK',
						data: {GoodsId: this.id,CourseId:this.selectcourse.Id}
					},
					res => { }
				);
			},
			getReceive() {
			  //分享进入调取领券接口
			  // 1-分享，2-购买并付款
			  this.request2(
			    {
			      url: "/api/AppletUser/ShareCoupon",
			      data: {
			        TriggerType: 1,
			      },
			    },
			    (res) => {
			      if (res.couponResultCode == 1) {
			        this.couponMessage = res.couponMessage;
			        this.showCoupons = true;
			      }
			    }
			  );
			},
			goLook() {
			  this.showCoupons = true;
			  uni.navigateTo({
			    url: "/pages/coupon/index/index",
			  });
			},
			closeBtn() {
			  this.showCoupons = false;
			},
			play(){
				if(this.selectcourse.IsPay!=1){//没有购买试看的时候处理
					setTimeout(()=>{
						 this.videoContext.pause();
						 this.studybg = true;
						 if(this.selectcourse.IsPay==2){
							 this.studytext='立即去支付'
						 }else{
							 this.studytext='立即购买'
						 }
						 
					},this.selectcourse.Number*1000)
				}
				
			},
			trysee(){
				if(this.studytext=='立即试看'){
					this.videoContext.play();
					this.studybg = false;
				}else if(this.studytext=='立即购买'){
					let DetailList = [];
					let obj={
						GoodsId:this.id,
						Number:1,
					}
					DetailList.push(obj)
					uni.navigateTo({
						url:'/pages/school/course-submit?DetailList='+encodeURIComponent(JSON.stringify(DetailList))
					})
				}else if(this.studytext=='立即去支付'){
					uni.navigateTo({
						url:'/pages/school/personal/orderList?status=1'
					})
				}
			}
		}
	}
</script>

<style>
	.courseContent .course-top{
		width: 100%;
		height: 230px;
		position: relative;
	}
	.courseContent .goback{
		margin-left: 15px;
		position: fixed;
		top: 0;
		left: 0;
	}
	#myVideo{
		width: 100%;
		height: 100%;
	}
	.courseContent .course-t{
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 80px;
		position: relative;
	}
	.courseContent .course-t-item{
		width: 50%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.courseContent .share-icon {
	  width: 22px;
	  height: 22px;
	  margin-bottom: 12rpx;
	}
	.courseContent .title{
		width: 100%;
		height: 79px;
		padding: 18px 15px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	.courseContent .scrollitem{
		width: 100%;
		padding: 15px;
		display: flex;flex-direction: row;
		align-items: center;
	}
	.courseContent .catalog-box-l{
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.courseContent .catalog-box-r{
		width: 40px;
		font-size: 10px;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
	}
	.courseContent .cb-l-bt{
		font-size: 9px;
		border-radius: 2px;
		border: 1px solid #9A9A9A;
		padding: 1px;
		margin-right: 5px;
	}
	.courseContent .studyimg{
		width: 100%;
		height: 100%;
	}
	.courseContent .studybg{
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		background-image: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/gmbanner%20.png');
		background-repeat: no-repeat;
		background-size: cover;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.courseContent .studybg-t{
		width: 115px;
		height: 30px;
		border-radius: 6px;
		font-size: 14px;
		margin-top: 10px;
		color:#FFF;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>
