<template>
	<view class="">
		<view class="content">
			<u-navbar :leftText="topTitle" @leftClick="leftClick" titleStyle="color:#fff;" bgColor="#000"
				leftIconColor="#fff" :autoBack="false">
			</u-navbar>
			<swiper :style="'width: '+ windowWidth +'px; height:100vh; background-color: #000;'" class="swiper"
				:circular='false' @change="swiperChange" :current="swiperCurrent" :vertical="true" duration="200">
				<block v-for="content in swiperList" :key="content">
					<swiper-item>
						<view :style="'width: '+ windowWidth +'px; height:'+heightxw+'vh;'" v-if="isShowVideo(content)">
							<!-- @controlstoggle="controlstoggle" -->
							<video v-if="isShowVideo(content)" autoplay :key="content" id="myVideo" :controls="controls"
								:loop="!isplay" preload="auto" :enable-progress-gesture="true"
								:show-center-play-btn="false" :show-loading="false" :show-fullscreen-btn="false"
								:poster="videoInfo.cover_image" @ended="ended" @click="tapVides()"
								:style="'width: '+ windowWidth +'px; height:'+heightxw+'vh;'"
								:src="currentVideoInfo.video_url" class="tsvideo">
							</video>

							<view v-if="isqp" class="userInfo">
								<!-- 2.点赞 -->
								<view style="opacity: 0.9; margin-top: 17px;">
									<image v-if="currentVideoInfo.is_zan" src="@/static/img/video/aixinRed.png"
										@click="myLike(2)"
										style="width: 40px; height: 40px; position: absolute; right: 6px;"></image>
									<image v-else src="@/static/img/video/aixin.png" @click="myLike(1)"
										style="width: 40px; height: 40px; position: absolute; right: 6px;"></image>
									<text
										style="color: #FFFFFF; margin-top: 5px; font-size: 14px; text-align: center; margin-top: 40px; font-weight: bold;">{{currentVideoInfo.total_zan}}</text>
								</view>
								<!-- 3.分享 -->
								<!-- <view style="opacity: 0.9; margin-top: 17px;">
							<image src="@/static/img/video/share-fill.png"
								style="width: 40px; height: 40px; position: absolute; right: 5px;"></image>
							<text
								style="color: #FFFFFF; margin-top: 5px; font-size: 14px; text-align: center; font-weight: bold; margin-top: 40px;">分享</text>
							<button open-type="share"
								style="position: absolute; background: none; width: 100%; height: 100%;"
								@click.stop="share"></button>
						</view> -->
								<!-- 4.追剧 -->
								<view class="comment" style="opacity: 0.9; margin-top: 17px;">
									<view v-if="videoInfo.is_binge_watch" @click="unBingewatch">
										<image src="@/static/img/video/scRed.png"
											style="width: 40px; height: 40px; position: absolute; right: 6px;">
										</image>
										<text
											style="color: #ff0000; margin-top: 5px; font-size: 14px; font-weight: bold; text-align: center; margin-top: 40px;">已追</text>
									</view>
									<view v-else @click="bingewatch">
										<image src="@/static/img/video/sc.png"
											style="width: 40px; height: 40px; position: absolute; right: 6px;">
										</image>
										<text
											style="color: #FFFFFF; margin-top: 5px; font-size: 14px; font-weight: bold; text-align: center; margin-top: 40px;">追剧</text>
									</view>
								</view>

							</view>
							<!-- 最底下的文字部分 -->
							<view v-if="isqp" class="contentcd" @click.stop="sellxj()">
								<text class="userName">《{{videoInfo.name}}》</text>
								<text class="userName">更新到第{{videoInfo.updated_episode_num}}集</text>
								<text class="userName">|</text>
								<text class="userName">选集</text>
							</view>
						</view>
						<image v-if="shouldRender(content)"
							:style="'width: '+ windowWidth +'px; height:'+heightxw+'vh;'" :src="videoInfo.cover_image">
						</image>
					</swiper-item>
				</block>
			</swiper>
			<uni-popup type="bottom" ref="select" style="z-index: 100;" :mask-click="true">
				<view v-if="fenji==1" class="pop-my"
					style=" border-top-left-radius: 10px; border-top-right-radius: 10px;">
					<view class="ju-top">
						<view style="display: flex; flex-direction: column; ">
							<view style="display: flex; flex-direction: column;">
								<view style="display: flex; flex-direction: column;">
									<view class="utabs-top">
										<u-tabs v-if="fenji==1" :activeStyle="activeStyle" lineColor="none"
											:inactiveStyle="inactiveStyle" class="utabs-top" :list="list1"
											:current="current"></u-tabs>
									</view>
									<view class="ju-top-title">
										{{videoInfo.name}}
									</view>
									<view class="ju-top-update"> 已更新至{{videoInfo.updated_episode_num}}集 </view>
								</view>
								<u-tabs v-if="fenji==1" :activeStyle="activeStyle" lineColor="none"
									:inactiveStyle="inactiveStyle" :current="tabcurrent" :list="labelList"
									@click="labelListClick"></u-tabs>
							</view>
							<view class="down" @click="down">
								<text class="down-text">收起</text>
								<image class="down-img" src="@/static/img/video/down.png">
								</image>
							</view>
						</view>
					</view>
					<scroll-view class="scroll-my" :scroll-y="true" :scroll-top="scrollTop">
						<view class="ju-wrapper">
							<block v-for="content in labelList[tabcurrent].content" :key="content">
								<view class="ju-content" :class="activeIndex ==content?'active':'' "
									@click="playVideo(content)">
									<!-- <view :class="isShowUpdate(content)?'lock-wrapper-no':'lock-wrapper'" -->
									<view class="lock-wrapper" v-if="isShowUpdate(content)">
										<text class="update-title">待更新</text>
									</view>
									<text class="title">第{{content}}集 </text>
									<view class="lock-wrapper" v-if="isShowVip(content)">
										<image class="lock-img" src="@/static/img/video/vip.png"></image>
									</view>
								</view>
							</block>
						</view>
						<view style="width: 1px; height: 1px; margin-top: 30px;"></view>
					</scroll-view>
				</view>
				<view v-if="fenji==2"
					:style="'width: '+ windowWidth +'px;height:70vh;  background-color: #fff; border-top-left-radius: 10px; border-top-right-radius: 10px;'">
					<view class="charge-wrapper">
						<view class="top">
							<text class="charge-title">充值购买后可继续观看{{popUpTitle}} </text>
							<text class="charge-info">为保护创作者权益，当前内容需要付费观看。</text>
							<view class="charge-coin">
								<text class="ji">本集:</text>
								<text class="bi">{{videoInfo.charge_coin}}k币</text>
							</view>
						</view>
						<view class="ft14"
							style="display: flex;flex-direction: row;justify-content: flex-start;padding: 0 20px;">
							账户余额<text class="ft14" style="color: #FF9800;">{{user_info.total_coin}}</text>K币</view>
						<scroll-view class="scroll-charge" :scroll-y="true" :scroll-top="scrollTop">
							<view class="pay-box">
								<block v-for="(item,key) in payOptions" :key="key">
									<view v-if="item.type =='COIN'" @click="selectPayItem(item)"
										:class="item.id == pay_select_id ?'pay-select' :'' " class="box pay-box-items">
										<view style="height: 20px;align-self: flex-end;"><text class="ft12 top-lab"
												v-if="item.tip_text">{{item.tip_text}}</text></view>
										<text class="ft18 pay-box-items-txt"
											style="color: #FF9800;">{{item.price}}元</text>
										<view class="ft14 pay-box-items-txt" style="flex-direction: row;">
											{{item.price_text}} <text class="ft14"
												style="color: #FF9800;">+{{item.given}}K币</text>
										</view>
										<view class="ft14 pay-box-items-txt"
											style="flex-direction: row;justify-content: space-between;"
											:class=" item.id == pay_select_id ?'select-text' :'given-txt'">
											{{item.given_amount}} <text v-if="item.id == pay_select_id"
												class="ft14">&#10003;️</text>
										</view>
									</view>
									<view v-else @click="selectPayItem(item)"
										:class="item.id == pay_select_id ?'pay-select' :'' " class="box pay-box-items">
										<view style="height: 20px;align-self: flex-end;"><text class="ft12 top-lab"
												v-if="item.tip_text">{{item.tip_text}}</text></view>
										<view class="vip-center">
											<view class="">
												<text class="ft18 pay-box-items-txt"
													style="color: #FF9800;">{{item.price}}元</text>
												<view class="ft14 pay-box-items-txt">{{item.price_text}}</text></view>
											</view>
											<image class="vip-level-icon" src="/static/icon/vip.png"></image>
										</view>
										<view class="ft14 pay-box-items-txt"
											style="flex-direction: row;justify-content: space-between;"
											:class=" item.id == pay_select_id ?'select-text' :'given-txt'">
											{{item.given_amount}} <text v-if="item.id == pay_select_id"
												class="ft14">&#10003;️</text>
										</view>
									</view>
								</block>
							</view>
							<view class="ft14" style="margin: 10px 0; padding: 0 20px;">付费须知</view>
							<view class="ft14" style="padding: 0 20px;">
								<text class="ft12">1、虚拟商品，一经购买不得退换</text>
								<text class="ft12">2、充值后K币可能有延迟，1小时未到账请在“我的”页面联系客服</text>
								<text class="ft12">3、未满18岁的未成年需要在监护人陪同下购买并观看短剧剧</text>
								<text class="ft12">4、购买成功后，“K币”仅在本小程序中使用</text>
								<text class="ft12">5、购买成功后可在”我的”页面订单中心进行查看</text>
							</view>
						</scroll-view>
					</view>
				</view>
			</uni-popup>
		</view>
		<u-overlay :show="centerShow" :duration="400" closeOnClickOverlay :z-index="999" @click="closeOverlay">
			<view class="warp">
				<view class="rect" @tap.stop>
					<text class="rect-text">剧集暂未更新</text>
					<view class="rect-button" @tap.stop @click="closeOverlay"><text class="rect-button-text">确定</text>
					</view>
				</view>
			</view>
		</u-overlay>
	</view>
</template>
<script>
	import {
		getVideoInfo,
		videoEpisodePlay,
		videoEpisodeZan,
	} from '@/common/apis/video.js';
	import {
		delShelf,
		storeshelf
	} from '@/common/apis/zju.js'
	import {
		getUserInfo
	} from "@/common/apis/my.js";
	import {
		userRanse
	} from "@/common/apis/common.js"
	import {
		getOptions,
		getPayInfo
	} from "@/common/apis/recharge.js"
	import configs from "@/common/config.js"
	export default {
		data() {
			return {
				centerShow: false, //暂未更新弹窗
				limitPage: 15,
				top_height: 0,
				episode: 1,
				ranse_id: 0,
				swiperCurrent: 0,
				videoContext: '',
				currentVideoInfo: {},
				activeStyle: {
					color: '#f95d27',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				},
				inactiveStyle: {
					color: '#606266',
					transform: 'scale(1)'
				},
				activeIndex: 1,
				tabcurrent: 0,
				videoInfo: {},
				labelList: [],
				list1: [{
					name: '当前剧集',
				}],
				sharedata: {
					type: 2,
					strShareUrl: "",
					strShareTitle: "分享标题",
					strShareSummary: "分享总结",
					strShareImageUrl: ""
				},
				isShow: true,
				fenji: 2,
				pay_select_id: 0,
				controls: true,
				windowWidth: 0,
				windowHeight: 0,
				current: 0,
				isplay: true, //是否自动播放下一个视频
				duration: 500,
				isqp: true,
				urls: configs.webUrl,
				scrollTop: 0,
				video_id: 0,
				safeArea: 0,
				ttuop: 0,
				heightxw: 100,
				user_info: {},
				payVideoInfo: {},
				payOptions: []
			};
		},
		computed: {
			shouldRender(index) {
				return (index) => {
					// 判断是否应该渲染当前索引的前后各一个索引的swiper item
					return Math.abs(index - this.swiperCurrent) <= 1;
				}
			},
			swiperList() {
				return Number(this.videoInfo.updated_episode_num) + 1
			},
			isShowVideo(item) {
				return (item) => {
					return this.swiperCurrent == item && this.isShow
				}
			},
			isShowVip(item) {
				return (item) => {
					return item >= this.videoInfo.charge_sequence && item <= this.videoInfo.updated_episode_num
				}
			},
			isShowUpdate(item) {
				return (item) => {
					return item > this.videoInfo.updated_episode_num
				}
			},
			popUpTitle() {
				return `《${this.videoInfo.name}》 第${this.episode}集`
			},
			topTitle() {
				return `第${this.episode}集`
			}
		},
		onReady: function(res) {
			this.videoContext = uni.createVideoContext('myVideo')
		},
		mounted() {
			getVideoInfo({
				video_id: this.video_id
			}).then(res => {
				// console.log(res, 'getVideoInfogetVideoInfogetVideoInfo')
				this.videoInfo = res.data
				this.initTabs();
				this.initSwiperData(this.swiperCurrent + 1)
			})
		},
		async onLoad(e) {
			// console.log('11111111111111111111',e)
			let that = this;
			uni.getSystemInfo({
				success(res) {
					that.top_height = res.statusBarHeight; //data中 声明 top_height:0 
				}
			});


			if (e.video_id) {
				this.video_id = Number(e.video_id)
			}
			if (e.sequence && Number(e.sequence) > 0) {
				this.swiperCurrent = Number(e.sequence) - 1;
			}
			// 染色参数接收
			if (e.ranse_id && Number(e.ranse_id) > 0) {
				try {
					this.ranse_id = Number(e.ranse_id);
					let res = await userRanse(this.ranse_id);

				} catch (e) {
					console.log("player-errr:", e)
				}
			}
			uni.getSystemInfo({
				success: res => {
					this.safeArea = res.safeAreaInsets.bottom;
					if (this.safeArea > 0) {
						this.heightxw = 97
					}
				}
			})
			// #ifdef MP-TOUTIAO
			this.ttuop = 64
			// #endif
			this.windowWidth = uni.getSystemInfoSync().windowWidth
			this.windowHeight = uni.getSystemInfoSync().windowHeight - this.safeArea - this.ttuop
			console.log(this.windowHeight)
		},
		onShow() {

		},
		onShareAppMessage: function(res) {
			// #ifdef MP-WEIXIN
			var href = '/pages/video/index?video_id=' + this.video_id + "&"
			console.log(res)
			let that = this;
			const obj = {
				title: "发送给好友",
				imageUrl: '',
				path: href,
				success: function(res) {
					console.log(res, "转发成功")
				},
				fail: function(res) {
					wx.showToast({
						title: '发送失败',
						icon: 'none'
					})
				}
			}
			return obj
			// #endif
		},
		watch: {
			activeIndex: {
				handler(newVal, oldVal) {
					this.initTabs()
					let index = this.labelList.findIndex(el => el.content.includes(newVal))
					console.log(index, 'newValnewVal', this.labelList, newVal)
					this.tabcurrent = index
				},
			}
		},
		onBackPress() {},
		methods: {
			closeOverlay() {
				this.centerShow = false
				// console.log('open');
			},
			bingewatch() {
				storeshelf(this.video_id).then(res => {
					this.videoInfo.is_binge_watch = !Boolean(this.videoInfo.is_binge_watch)
					uni.showToast({
						title: '追剧成功',
						duration: 1000,
						icon: 'none'
					});
				})
			},
			unBingewatch() {
				delShelf(this.video_id).then(res => {
					this.videoInfo.is_binge_watch = !Boolean(this.videoInfo.is_binge_watch)
				})
			},
			leftClick(e) {
				if (!this.videoInfo?.is_binge_watch) {
					uni.showModal({
						title: '加入追剧',
						content: '喜欢就加入追剧吧',
						confirmText: '加入追剧',
						confirmColor: '#FFA500',
						cancelText: '不用了',
						success: (res) => {
							if (res.confirm) {
								this.bingewatch()
								uni.switchTab({
									url: '/pages/index/index'
								});
								// 用户点击了确定按钮
								// 执行加入追剧的逻辑
							} else if (res.cancel) {
								// 用户点击了取消按钮
								// 执行取消逻辑
								uni.switchTab({
									url: '/pages/index/index'
								});
							}
						}
					});
				} else {
					uni.switchTab({
						url: '/pages/index/index'
					});
					// uni.navigateBack()
				}
			},
			myLike(like) {
				videoEpisodeZan({
					episode_id: this.currentVideoInfo.id,
					zan: like
				}).then(res => {
					this.$nextTick(() => {
						this.currentVideoInfo.is_zan = !Boolean(this.currentVideoInfo.is_zan)
						if (this.currentVideoInfo.is_zan) {
							this.currentVideoInfo.total_zan++
						} else {
							this.currentVideoInfo.total_zan--
						}
					})

				})
			},
			initTabs() {
				function innit(i, num) {
					let arr = [];
					for (i; i <= num; i++) {
						arr.push(i)
					}
					return arr
				}
				const pageSize = this.limitPage;
				const total = this.videoInfo.total_episode_num;
				const pageCount = Math.ceil(total / pageSize);
				for (let i = 0; i < pageCount; i++) {
					const start = i * pageSize + 1;
					const end = i === pageCount - 1 ? total : (i + 1) * pageSize;
					let label;
					if (i === pageCount - 1) {
						if (start === total) {
							label = `${total}`
						} else {
							label = `${start}-${total}`
						}
					} else {
						label = `${start}-${end}`
					}
					let index;
					if (label.split('-')[1]) {
						index = label.split('-')[1]
					} else {
						index = total
					}
					this.labelList.push({
						name: label,
						page: pageCount,
						content: innit(start, index)
					})
				}
				// let index = this.labelList.findIndex(el => el.content.includes(this.activeIndex))
				// this.tabcurrent = index
			},
			async getPayInfo(originIndex) {
				let userInfores = await getUserInfo();
				this.user_info = userInfores.data
				let res = await getOptions();
				this.payOptions = res.data;
				this.payOptions.forEach((item, index) => {
					if (item.is_default == 1) {
						this.pay_select_id = item.id;
					}
				})
				this.payVideoInfo = {
					video_id: this.video_id,
					video_series_sequence: originIndex
				};


			},
			async selectPayItem(item) {
				this.pay_select_id = item.id;
				let params = {
					video_id: this.payVideoInfo.video_id,
					video_series_sequence: this.payVideoInfo.video_series_sequence,
					pay_proudct_id: item.id,
					is_first_pay: item.is_first_pay,
				}
				let res = await getPayInfo(params);
				if (res.data) {
					// #ifdef MP-WEIXIN
					this.wxMinPay(res.data);
					// #endif
				}

			},
			wxMinPay(param) {
				wx.requestPayment({
					timeStamp: param.timeStamp,
					nonceStr: param.nonceStr,
					package: param.package,
					signType: param.signType,
					paySign: param.paySign,
					success(res) {
						this.pay_success = true;
						uni.showToast({
							title: '支付成功',
							icon: "none"
						});
						// console.log('success:' + JSON.stringify(res));
					},
					fail(e) {
						if (e.errMsg == "requestPayment:fail cancel") {
							uni.showToast({
								title: '取消支付',
								icon: "none"
							});
						} else {
							uni.showToast({
								title: '支付失败',
								icon: "none"
							});
						}
					}
				})
			},
			playVideo(item) {
				if (this.isShowVip(item)) {
					// this.fenji = 2
					this.swiperCurrent = item - 1;
					this.getPayInfo(item);
					// this.activeIndex = ''
				} else if (this.isShowUpdate(item)) {
					// this.activeIndex = ''
					this.centerShow = true
					// this.swiperCurrent = this.videoInfo.updated_episode_num + 1;
					// uni.showToast({
					// 	title: '剧集暂未更新',
					// 	duration: 500,
					// 	icon: 'none'
					// });
				} else {
					this.activeIndex = item;
					this.swiperCurrent = item - 1;
					this.episode = this.swiperCurrent
					// this.initSwiperData(item)
					this.down();
				}
			},
			labelListClick(item) {
				this.tabcurrent = item.index
			},
			share() {
				var href = '/pages/video/index?video_id=' + this.video_id
				// #ifdef H5
				uni.setClipboardData({
					data: this.urls + '/h5/#' + href,
					complete() {
						uni.showToast({
							title: "分享连接已复制到剪贴板"
						})
					}
				})
				// #endif
				// #ifndef H5
				uni.share({
					provider: "weixin",
					scene: "WXSenceTimeline",
					type: 0,
					href: href,
					title: '分享标题',
					summary: '分享总结',
					imageUrl: '',
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				})
				// #endif
			},
			down() {
				this.$refs.select.close();
			},
			sellxj() {
				this.fenji = 1
				this.$refs.select.open('bottom');
				this.$nextTick(() => {
					let num1 = (this.windowHeight / 1.6) * 0.85;
					let num2 = num1 / 4.78;
					this.scrollTop = num2 * Number(this.k);
				})
			},
			tapVideoHover(index, pays) {
				this.videoContext.play()
				// this.$refs.select.open('bottom');
			},
			tapVides() {
				this.isqp = !this.isqp
			},
			ended() {
				//console.log('isplay----',this.isplay)
				// 1.播放当前视频结束时触发，自动切换下一个视频
				if (this.isplay) {
					if (this.displayIndex < 2) {
						this.current = this.displayIndex + 1
					} else {
						this.current = 0
					}
					this.isqp = true
					// console.log('显示swiper Index:', this.displayIndex)
				}
			},
			initSwiperData(originIndex) {
				this.episode = originIndex;
				this.isqp = true
				console.log(this.videoInfo.updated_episode_num, 'this.swiperCurrent', this.swiperCurrent)
				if (this.swiperList != this.swiperCurrent + 1) {
					videoEpisodePlay({
						video_id: this.video_id,
						sequence: originIndex,
					}).then(res => {
						if (res.code == 0) {
							this.currentVideoInfo = res.data
							this.activeIndex = this.episode;
							this.isShow = true
							this.down();
						} else if (res.code == 500101) {
							// console.log(this.currentVideoInfo, 'res.code == 500101res.code == 500101')
							this.currentVideoInfo.video_url = ""
							this.isShow = false
							this.isqp = false
							this.fenji = 2
							this.getPayInfo(originIndex);
							this.$refs.select.open('bottom');
							// this.currentVideoInfo = {}
						} else {
							this.isqp = false
							this.currentVideoInfo.video_url = ""
							this.isShow = false
						}
						// console.log(res, 'getVideoEpisodePlaygetVideoEpisodePlay')
					})
				} else {
					this.isqp = false
					this.centerShow = true
					this.currentVideoInfo.video_url = ""
					this.isShow = false
				}

			},
			/**
			 * swiper滑动时候
			 */
			swiperChange(event) {
				const {
					current
				} = event.detail;
				this.swiperCurrent = current
				// console.log(this.swiperCurrent, 'this.swiperCurrentthis.swiperCurrent')
				this.initSwiperData(current + 1)
			},
			controlstoggle(e) {
				// console.log(e.detail.show);
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "./style/index.scss"
</style>