<template>
	<view class="page-container" >
		<view class="status-bar"></view>
		<view class="video">
			<view class="video-box">
				<!-- <Artplayer ref="artplayer" @get-instance="getInstance" :option="option" :playing.sync="playing" :style="style" :vodid="id" /> -->
				<dplayer ref="dplayer" :url="lookedUrl" :thumbnails="vod_thumbnails" @controller="controller"  @setting="setting"  @timeupdate="timeUpdate" />
			</view>
			<u-loading-icon v-if="lookLoading"></u-loading-icon>
		
			<view v-if="playAdvShow" class="play-adv" @click="openAD(playAdv.adv_link)">
				<vod-image :src="playAdv.adv_image"></vod-image>
				<u-count-down ref="advTime" :time="playAdv.adv_show_time * 1000" format="ss" autoStart
					@change="advTimeChange" @finish="closePlayAdv">
					<text class="time">{{ playAdvTime.seconds }}s后关闭广告</text>
				</u-count-down>
			</view>
		</view>
		<view class="video-info" @touchmove.stop>
			<view v-if="advList.banner_adv1" class="ad-banner" @click="openAD(advList.banner_adv1.adv_link)">
				<vodImage :src="advList.banner_adv1.adv_image" mode="widthFix"></vodImage>
			</view>
			<view class="video-info-header">
				<view class="header-bg">
					<view class="header-bg-upper"></view>
				</view>
				
				<view class="video-tabs justify-between">
						<view class="video-tabs-title">
							<text :class="videoTabsIndex == 0 && 'selected'" @click="tabsClick(0)">视频{{playerUrl}}</text>
							<text :class="videoTabsIndex == 1 && 'selected'" @click="tabsClick(1)">评论</text>
						</view>
					<view class="video-msg" @click="openUrl('/pages/video/video-guide')">
						无法全屏？
					</view>
					
				</view>
			</view>
		
			<view class="video-info-swiper">
				<scroll-view  ref="scrollView" class="swiper-container" :scroll-top="scrollTop"  scroll-y="true" @scrolltolower="commentData" @scroll="handleScroll" >
						<video-info :intro-show.sync="introShow" :video-tabs-index.sync="videoTabsIndex" :play-index.sync="playIndex"
							:video-episodes.sync="videoEpisodes" @episodes="triggerEpisodes" :data="data" :adv="advList" @Share="openShare" @download="download" @favVod="favVod" :is_fav="data.is_fav"
							@dig="digVod"></video-info>
						<video-comment ref="comment" :id="id" @reward="toReward" :showinput="videoTabsIndex" ></video-comment>
				</scroll-view>
			</view>
		</view>
		<u-popup :show="episodesShow" :round="10" @close="triggerEpisodes(false)">
			<view class="video-episodes-popup">
				<scroll-view :scroll-top="episodesScroll" scroll-y>
					<view v-if="data.vod_play_url.length > 0" class="episodes-popup-grid">
						<view v-for="(item, index) in data.vod_play_url[playIndex].list" :key="index" class="grid-item"
							:class="index == videoEpisodes && 'selected'" @click="selectEpisodes(index)">
							<text class="grid-text">{{item.name}}</text>
							<u-badge v-if="item.badge" :value="item.badge.value"></u-badge>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<share ref="share" />
		<u-loading-page :loading="loading" bgColor="none" fontSize="16"></u-loading-page>
		<reward ref="reward" />
		<full-adv ref="fullAdv" @close="closeFullAdv" />
	</view>
</template>

<script>
	import dplayer from '@/components/dplayer'
	import videoInfo from './video-info'
	import videoComment from './video-comment'
	import vodImage from '@/components/vod-image.vue'
	import share from '@/components/share'
	import reward from '@/components/reward'
	import fullAdv from '@/components/full-adv'
	import Artplayer from '@/components/artplayer.vue'
	import {
		vodDig,
		vodHistory,
		vodFav
	} from '@/utils/dexie'
	import {
		app,
		user
	} from '@/utils/api'

	export default {
		components: {
			dplayer,
			videoInfo,
			vodImage,
			videoComment,
			share,
			reward,
			fullAdv,
			Artplayer
		},
		data() {
			return {
				id: 0,
				data: {
					vod_play_url: [],
					is_fav: 0
				},
				advList: {},
				playerUrl: '',
				controllerShow: true,
				panelShow: false,
				introShow: false,
				episodesShow: false,
				videoTabsIndex: 0,
				videoEpisodes: 0,
				episodesScroll: 0,
				loading: true,
				lookLoading: false,
				playIndex: 0,
				adLookNum: 0,
				playAdv: null,
				playAdvShow: false,
				playAdvTime: {},
				looked: [],
				playTime: 0,
				timer: null,
				faved: false,
				trySee: false,
				option: {
					url: "",
					danmuku:[],
					id:''
				},
				style: {
					width: "750rpx",
					height: "234px",
					margin: "0px auto 0",
				},
				playing:false,
				art:null,
				downloadurl:{},
				scrollTop:0,
				showinput:false,
				lookedUrl:'',
				vod_thumbnails:''
			}
		},
		watch: {
			playIndex: {
				handler(val) {
					this.playerUrl = this.data.vod_play_url[val]['list'][this.videoEpisodes].url
				
				}
			},
			videoEpisodes: {
				handler(val) {
					if (this.loading === false) {
						if (this.$refs.dplayer.player) {
							this.$refs.dplayer.player.destroy()
						}
						this.playerUrl = ''
						this.lookVod()
					}
				}
			}
		},
		onLoad(options) {
			if (options.id) {
				this.id = parseInt(options.id)
				this.option.vodid= this.id
			}
			if (options.play_index) {
				this.videoEpisodes = parseInt(options.play_index)
			}
			this.getData()
			this.$nextTick(() => {
				this.commentData()
			})
		},
		onShow() {
			
			this.$nextTick(() => {
				this.timer = setInterval(() => {
					const player = this.playing
					if (player) {
						this.playTime++
					}
					if (this.playTime == 1800) {
						this.toTask()
					}
					if (this.playTime > 1800) {
						clearInterval(this.timer)
					}
				}, 1000)
			})
		},
		onHide() {
			
			if (this.timer) {
				clearInterval(this.timer)
			}
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
			}
		},
		methods: {
			
			gotoguide(){
			  uni.navigateTo({
			  	url:"pages/video/video-guide"
			  })	
			},
			async getData() {
				this.loading = true
				await app.vodDetails(this.id).then(res => {
					if (res.code == 1) {
						this.data = res.data
						this.vod_thumbnails=this.data.vod_thumbnails
						console.log(this.data);
						vodDig.get(this.id).then(res => {
							if (res) {
								this.data.is_up=res.up == 1 ? 1 : 0
								this.data.is_down=res.down == 1 ? 1 : 0
								if (this.data.is_up) {
									this.data.vod_up+= 1;
								}
								if (this.data.is_down) {
									this.data.vod_down+= 1;
								}
							}
						});
						vodFav.get(this.id).then(res=>{
							if(res){
								console.log(res);
								this.data.is_fav=res.status
							}
						})
						
						try{
							if (this.data.adv_list.full_adv.length > 0) {
							this.advList.full_adv = this.data.adv_list.full_adv
							}
						}catch(err) {
						   
						}
						
						
						if (this.data.adv_list.play_adv.length > 0) {
							this.advList.play_adv = this.data.adv_list.play_adv
						}
						if (this.data.adv_list.banner_adv1.length > 0) {
							this.advList.banner_adv1 = this.data.adv_list.banner_adv1[Math.floor(Math.random() * this
								.data.adv_list.banner_adv1.length)]
						}
						if (this.data.adv_list.banner_adv2.length > 0) {
							this.advList.banner_adv2 = this.data.adv_list.banner_adv2[Math.floor(Math.random() * this
								.data.adv_list.banner_adv2.length)]
						}
						this.lookVod()
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 3000
						})
						setTimeout(() => {
							this.toBack()
						}, 1500)
					}
				}).catch(e => {
					console.log(e,'视频');
					setTimeout(() => {
						this.toBack()
					}, 1500)
				})
				
			},
			async lookVod() {
				if (this.looked.indexOf(this.videoEpisodes) === -1) {
					this.lookLoading = true
					const playUrl=this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url;
					const res = await app.lookVod(this.id + '_' + this.videoEpisodes,playUrl).then(res)
					this.lookLoading = false
					this.loading = false
					if(res.data.url){
						this.lookedUrl=res.data.url.h264
					}
					
					if (res.code == 0) {
						if (this.$refs.dplayer.player) {
						  this.$refs.dplayer.player.destroy()
						}
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 3000
						})
						setTimeout(() => {
							this.toBack()
						}, 1500)
						return
					} else if (res.code == 2) {
						this.trySee = true
						if (this.data.vod_trysee <= 0) {
							if (this.$refs.dplayer.player) {
							  this.$refs.dplayer.player.destroy()
							}
							this.toVip()
							return
						}
					} else if (res.code == 3) {
						if (this.$refs.dplayer.player) {
						  this.$refs.dplayer.player.destroy()
						}
						
						try {
						    this.adLookNum = res.data.adv_look_num
						}
						catch(err) {
						   this.adLookNum = 0
						}
						this.toAdv()
						return
					} else {
						this.trySee = false
						this.looked.push(this.videoEpisodes)
						app.updateHits(this.id, 1)
						this.addHistory()
					}
					// this.showPlayAdv()
					console.log(12321);
					this.playerUrl = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
					if (this.$refs.dplayer.player) {
					  this.$refs.dplayer.player.play()
					}
				}
				
				
			},
			toTask() {
				const token = getApp().globalData.userToken
				if (token) {
					user.task(2).then(res => {
						if (res.code == 1 && res.data) {
							this.toReward(res.data.task_coin)
						}
					})
				}
			},
			addHistory() {
				const record = {
					id: this.id,
					// index: this.videoEpisodes,
					// episodes: this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].name,
					time: Math.round(new Date() / 1000)
				}
				
				vodHistory.get(this.id).then(res => {
					let history = res
					if (history) {
						console.log(history);
						const i = history.findIndex(d => d.id === record.id)
						if (i >= 0) {
							history.splice(i, 1)
						} else if (history.length >= 1000) {
							history.pop()
						}
						console.log(record);
						
						vodHistory.update(this.id, record)
					} else {
						vodHistory.put(record)
					}
				});
				
			},
			async favVod() {
				const token = getApp().globalData.userToken
				if (token) {
					if (this.faved) {
						return
					}
					this.faved = true
					// await app.favVod(this.id, this.data.is_fav === 1 ? 0 : 1).then(res => {
						
							this.data.is_fav = this.data.is_fav === 1 ? 0 : 1
							vodFav.get(this.id).then(res=>{
								let data={
									id:this.id,
									status:this.data.is_fav,
									time: Math.round(new Date() / 1000)
								}
								if(res){
									if(data.status){
										vodFav.update(this.id,data)
									}else{
										vodFav.delete(this.id)
									}
									
								}else{
									vodFav.put(data)
								}
							})
					// }).catch(e => {})
					this.faved = false
				} else {
					uni.navigateTo({
						url: '/pages/user/login'
					})
				}
			},
			digVod(e) {
				app.updateDig(this.id, 1, e).then(res => {
					const status = this.data['is_' + e] ? 0 : 1
					if (res.code == 1) {
						if (this.data['is_' + e] === 1) {
							this.data['is_' + e] = 0
						} else {
							this.data['is_' + e] = 1
						}
						let data = {}
						data[e] = this.data['is_' + e]
						
						if (status === 1) {
							this.data['vod_' + e] += 1;
						} else if (this.data['vod_' + e] > 0) {
							this.data['vod_' + e] -= 1
						}
						
						vodDig.get(this.id).then(res => {
							if (res) {
								vodDig.update(this.id, data)
							} else {
								data.id = this.id
								vodDig.add(data)
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
					
				})
			},
			timeUpdate(time) {
				if (this.trySee && this.data.vod_trysee > 0 && time >= this.data.vod_trysee) {
					if (this.$refs.dplayer.player) {
						this.$refs.dplayer.player.destroy()
					}
					
					this.trySee = false
					this.toVip()
				}
			},
			controller(status) {
				this.controllerShow = status
			},
			setting(status) {
				if (status) {
					this.controllerShow = false
				} else {
					this.controllerShow = true
				}
			},
			switchLine(status) {
				if (status) {
					this.controllerShow = false
					this.panelShow = true
				} else {
					this.controllerShow = true
					this.panelShow = false
				}
			},
			changePlay(index) {
				this.playIndex = index
			},
			swiperChange(e) {
				this.videoTabsIndex = e.detail.current
				if (this.videoTabsIndex === 1 && this.loading === false) {
					this.$refs.comment.init()
				}
			},
			tabsClick(index) {
				if (this.videoTabsIndex != index) {
					this.videoTabsIndex = index
				}
				if(index==1){
					this.scrollTop = 710
				}else{
					this.scrollTop = 0
				}
			},
			closeIntro() {
				this.introShow = false
			},
			triggerEpisodes(status) {
				this.episodesShow = status
				if (status) {
					this.$nextTick(async () => {
						const grid = await new Promise(resolve => {
							uni.createSelectorQuery().in(this).select('.episodes-popup-grid').boundingClientRect(
								data => {
									resolve(data)
								}).exec()
						})
						const item = await new Promise(resolve => {
							uni.createSelectorQuery().in(this).select('.episodes-popup-grid .selected')
								.boundingClientRect(data => {
									resolve(data)
								}).exec()
						})
						let scrollTop = item.top - grid.top - 90
						scrollTop = Math.min(scrollTop, grid.height)
						this.episodesScroll = Math.max(0, scrollTop)
					})
				}
			},
			selectEpisodes(index) {
				this.videoEpisodes = index
				this.triggerEpisodes(false)
			},
			openShare() {
				this.$refs.share.showSharePopup = true
			},
			advTimeChange(e) {
				this.playAdvTime = e
			},
			download() {
				 const filePath = this.data.vod_down_url[this.playIndex]['list'][this.videoEpisodes].url;
				  const tempLink = document.createElement("a");
				  tempLink.style.display = "none";
				  tempLink.href = filePath;
				  tempLink.setAttribute("download", 'res.fileName');
				  tempLink.setAttribute("target", "_blank");
				  document.body.appendChild(tempLink);
				  tempLink.click();
				  document.body.removeChild(tempLink);
			},
			toReward(value) {
				this.$refs.reward.onshow(value)
			},
			toVip() {
				uni.showModal({
					title: '观影提示',
					confirmText: '购买VIP特权',
					confirmColor: '#fd6202',
					content: '该影片是VIP专属，请先升级VIP再进行观看~!',
					success: (res) => {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/user/recharge'
							})
						} else {
							this.toBack()
						}
					}
				})
			},
			toBack() {
				const pages = getCurrentPages()
				const pagesLength = pages.length
				if (pagesLength === 1) {
					uni.switchTab({
						url: '/pages/home/index'
					})
				} else {
					for (let delta = 1; delta < pagesLength; delta++) {
						if (pages[pagesLength - delta - 1].route == 'pages/video/video') {
							continue
						}
						uni.navigateBack({
							delta: delta
						})
						break
					}
				}
			},
			toAdv() {
				let text = '取消'
				
				if (this.advList.full_adv) {
					text = this.adLookNum > 0 ? '看广告解锁视频' : '今日解锁次数已满'
				}
				uni.showModal({
					title: '观影提示',
					confirmText: '购买VIP特权',
					confirmColor: '#fd6202',
					cancelText: text,
					content: '您的今日免费观影次数已用尽~!',
					success: (res) => {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/user/recharge'
							})
						} else {
							if (this.adLookNum > 0 && this.advList.full_adv) {
								this.showFullAdv('video')
							} else {
								this.toBack()
							}
						}
					}
				})
			},
			showPlayAdv() {
				if (this.playAdvShow) {
					this.$refs.advTime.reset()
				}
				// if (this.advList.play_adv.length > 0) {
					
				// 	this.playAdv = this.advList.play_adv[Math.floor(Math.random() * this.advList.play_adv.length)]
				// 	this.playAdvShow = true
				// }
			},
			closePlayAdv() {
				this.playAdvShow = false
				if (this.$refs.dplayer.player) {
					console.log(this.playerUrl);
					console.log(this.lookedUrl);
				  this.$refs.dplayer.player.play()
				}
			},
			showFullAdv(type) {
				if (type) {
					this.$refs.fullAdv.type = type
					this.$refs.fullAdv.toast = null
				} else {
					this.$refs.fullAdv.type = 'default'
					this.$refs.fullAdv.toast = '视频极速加载中'
				}
				this.$refs.fullAdv.adv = this.advList.full_adv[Math.floor(Math.random() * this.advList.full_adv.length)]
				this.$refs.fullAdv.showPopup = true
			},
			async closeFullAdv(type) {
				if (type == 'video') {
					this.lookLoading = true
					const playerUrl = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
					const res = await app.advUnlockVod(this.id + '_' + this.videoEpisodes,playerUrl).then(res)
					if(res.data.url){
						this.lookedUrl=res.data.url.h264
					}
					this.lookLoading = false
					if (res.code == 1) {
						this.looked.push(this.videoEpisodes)
						app.updateHits(this.id, 1)
						this.addHistory()
						this.playerUrl = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
						this.$nextTick(() => {
							if (this.$refs.dplayer.player) {
							  this.$refs.dplayer.player.play()
							}
						})
					}
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 3000
					})
				}
			},
			commentData(){
				this.$refs.comment.getData()
			},
			handleScroll(event) {
			      const scrollTop = event.detail.scrollTop;
				  if(scrollTop > 400){
					  this.videoTabsIndex = 1
				  }else{
					  this.videoTabsIndex = 0
				  }
			    },
			openComment(){
				this.videoTabsIndex=1
				this.scrollTop = 510
			},
		}
	}
</script>

<style lang="scss">
	page{
		background-color: $uni-bg-color;
	}
	.page-container {
		height: 100%;
		background-color: $uni-bg-color;

		.status-bar {
			background-color: #000;
		}

		.video {
			width: 100%;
			height: 275px;
			background-color: #000;
			position: relative;

			.video-box {
				width: 100%;
				height: 100%;
			}

			.u-loading-icon {
				background-color: #000;
				z-index: 999;
				pointer-events: none;
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;
			}

			.play-adv {
				z-index: 1000;
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;

				uni-image {
					width: 100%;
					height: 100%;
				}

				.u-count-down {
					padding: 5px 10px;
					text-align: center;
					background-color: rgba(0, 0, 0, 0.6);
					color: #fff;
					font-size: 12px;
					border-radius: 15px;
					position: absolute;
					top: 15px;
					right: 15px;
				}
			}

			.controller-full-adv {
				z-index: 90;
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
			}

			.controller {
				z-index: 999;
				pointer-events: none;
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;

				.controller-header {
					pointer-events: auto;
					padding: 10px 8px 0;
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					align-items: center;
					position: absolute;
					top: 0;
					left: 0;
					right: 0;

					.uni-icons {
						text-shadow: 0 0 4px rgba(0, 0, 0, 0.75);
					}

					.switch-line {
						margin: 0 11px;
						font-size: 14px;
						color: #fff;
						text-shadow: 0 0 4px rgba(0, 0, 0, 0.75);
					}
				}
			}

			.panel {
				z-index: 98;
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: 0;

				.line-panel {
					position: absolute;
					top: 0;
					right: 0;
					bottom: 0;
					width: 90px;
					background-image: linear-gradient(90deg, transparent, rgba(0, 0, 0, .8));

					uni-scroll-view {
						position: absolute;
						top: 0;
						bottom: 0;
					}

					.line-panel-content {
						padding: 5px 0;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						position: relative;
						z-index: 999;

						.line-panel-item {
							margin: 10px 0;
							padding: 0 10px;
							height: 17px;
							line-height: 17px;
							font-size: 14px;
							color: #fff;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;

							&.selected {
								color: #09a96a;
							}
						}
					}
				}
			}
		}

		.video-info {
			height: calc(100% - var(--safe-top) - 264px);
			display: flex;
			flex-direction: column;

			.ad-banner {
				width: 100%;
				padding: 5px;
				min-height: 20px;
				uni-image {
					width: 100%;
					border-radius: 8px;
					min-height: 20px;
				}
			}

			.video-info-header {
				height: 40px;
				position: relative;

				.header-bg {
					height: 100%;
					position: absolute;
					background: linear-gradient(111deg, #d2fee1, #ecfafa 53%, #e9fde5);
				}
				.video-msg{
					position: relative;
					color: #787bdc;
					font-size: 12px;
				}
				.video-tabs {
					height: 100%;
					align-items: center;

					.video-tabs-title {
						margin: 0 5px;
						position: relative;
						
						uni-text {
							margin: 0 10px;
							font-size: 16px;
							color: #fff;

							&.selected {
								font-weight: 700;
							}
						}
					}

					.video-bar {
						margin: 0 5px;
						position: relative;

						.uni-icons {
							margin: 0 8px;
						}
					}
				}
			}

			.video-info-swiper {
				flex: 1 1 0%;
				height: calc(100% - var(--safe-top) - 434px);
				.swiper-container {
					height: 100%;
				}
			}
		}

		.video-episodes-popup {
			uni-scroll-view {
				max-height: 240px;

				.episodes-popup-grid {
					padding: 10px;
					display: grid;
					grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));

					.grid-item {
						padding: 5px;
						position: relative;

						.grid-text {
							width: 100%;
							padding: 0 15px;
							height: 48px;
							line-height: 48px;
							text-align: center;
							font-size: 14px;
							color: #1a1a2a;
							background: #f2f5fa;
							border-radius: 4px;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							display: block;
						}

						.u-badge {
							border-radius: 0 7px 0 7px;
							position: absolute;
							right: 5px;
							top: 5px;
						}

						&.selected {
							.grid-text {
								font-weight: 700;
								background: #ecfcf1;
								color: $uni-color-primary;
							}
						}
					}
				}
			}
		}
	}
</style>