<template>
  <view
    class="flex-1"
    style="background-color: #000000;"
  >
    <GLoading :back-color="'#000'" />
    <swiper
      :duration="500"
      vertical
      class="flex-1"
      :current="currentWatchIndex"
      :disable-touch="true"
      @change="videoChange"
    >
      <swiper-item
        v-for="(item, index) in videoList"
        :key="index"
        class="flex-1"
        @touchmove.stop="stopTouchMove"
      >
        <!-- 视频 -->
        <video
          v-if="Math.abs(currentWatchIndex - index) <= 1"
          :id="`video_${item.id}`"
          :ref="'item' + index"
          :poster="item.cover"
          :enable-progress-gesture="false"
          style="width: 750rpx;"
          class="flex-1"
          :controls="watchInfo.id === item.id"
          :src="item.video_url"
          :play-strategy="1"
          :show-fullscreen-btn="false"
          @play="videoPlay"
        />
      </swiper-item>
    </swiper>
    <view
      v-if="watchInfo.order"
      class="jishu1"
    >
      <text
        style="color: #fff;"
        class="fs-32"
      >
        第{{ watchInfo.order }}集
      </text>
    </view>
    <view class="ops">
      <view
        class="flex-center"
        @click="chaseKeep"
      >
        <view
          class="animation"
          :class="'animation-' + animation"
        >
          <u-icon
            v-if="watchInfo.iskeep === 0"
            name="/static/icon/keep-on.png"
            size="68rpx"
          />
          <u-icon
            v-else
            name="/static/icon/keep-off.png"
            size="68rpx"
          />
        </view>
        <text
          class="fs-28 mt-10"
          style="color: #FFF;"
        >
          追剧
        </text>
      </view>

      <view
        class="flex-center mt-32"
        @click="completeWorksShow"
      >
        <u-icon
          name="/static/icon/xuanji.png"
          size="68rpx"
        />
        <text
          class="fs-28 mt-10"
          style="color: #FFF;"
        >
          选集
        </text>
      </view>
    </view>
    <completeWorks
      ref="completeWorks"
      style="position: fixed;"
    />
    <Payment
      ref="Payment"
      style="position: fixed;"
      @success="paySuccess"
    />
  </view>
</template>

<script>
import completeWorks from './components/completeWorks.vue';
import Payment from './components/payment.vue';
import { batchlist, videoread, addkeep, chasingdramadel } from '@/api/index.js';
export default {
	components: {
		completeWorks,
		Payment
	},
	data() {
		return {
			videoList: [],
			currentWatchIndex: 0,
			currenttimes: 0,
			touchNum: 0,
			ProgressBarOpacity: 0.7, //进度条不拖动时的默认值，就是透明的
			dotWidth: 0, //播放的小圆点，默认没有
			oldVideo: null,
			voice: '', //🌟用来阻止 setTimeout()方法
			timeout: '', //🌟用来阻止 setTimeout()方法
			videoTimes: '', //视频时长，用这个来获取时间值，例如：00:30这个时间值💗
			changeTime: '', //显示滑动进度条时变化的时间💗
			params: {},
			watchInfo: {},
			animation: '',
			pageStartY: 0,
			pageEndY: 0,
		};
	},
	onLoad(ops) {
		this.$showLoading(true);
		this.params = ops;
	},
	watch: {
		async currentWatchIndex(index, old_index) {
			this.$showLoading(true);
			const oldData = this.videoList[old_index];
			const currentData = this.videoList[index];
			const pData = this.videoList[index + 1];
			this.params.id = currentData.id;
			videoread(this.params).then(res => {
				uni.createVideoContext(`video_${oldData.id}`, this).pause();
				const result = res[0];
				this.watchInfo = result;
				if (result.isvip === 1 && result.chackpay === 3) {
					this.$refs.Payment.open(result);
				} else if (result.isvip === 1 && result.chackpay === 2) {
					// 余额不足
					uni.createVideoContext(`video_${oldData.id}`, this).pause();
					uni.createVideoContext(
						`video_${currentData.id}`,
						this
					).pause();
					const that = this;
					uni.navigateTo({
						url: '/pages/pay/pay?sid=' + result.sid,
						events: {
							paySuccess: () => {
								console.log(index);
								clearTimeout(that.timeout);
								that.timeout = setTimeout(() => {
									uni.createVideoContext(
										`video_${oldData.id}`,
										that
									).pause();
								}, 50);

								this.init(this.params);
							}
						}
					});
				} else if (
					result.isvip === 0 ||
					(result.isvip === 1 && result.chackpay === 1)
				) {
					currentData.isvip = 0; // 购买成功 或者本来就是免费
					oldData.state = 'pause'; //如果是被滑走的视频，就停止播放
					oldData.playIng = false; //如果视频暂停，就加载封面
					oldData.isplay = true;
					currentData.state = 'play';
					console.log(`video_${currentData.id}`);
					clearTimeout(this.timeout);
					this.timeout = setTimeout(() => {
						this.pageStartY = 0;
						this.pageEndY = 0;
						uni.createVideoContext(
							`video_${oldData.id}`,
							this
						).pause();
						uni.createVideoContext(
							`video_${currentData.id}`,
							this
						).play();
					}, 50);
					if (pData) {
						uni.createVideoContext(
							`video_${pData.id}`,
							this
						).pause();
					}
				}
				this.$showLoading(false);
			});
		}
	},
	onShow() {
		this.init(this.params);
	},
	methods: {
		init(ops) {
			const isPopup = uni.getStorageSync('isPopup');
			if (isPopup) {
				const currentData = this.videoList[this.currentWatchIndex];
				uni.createVideoContext(`video_${currentData.id}`, this).pause();
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/pay/pay'
					});
				}, 1000);
				return;
			}
			batchlist({ sid: ops.sid }).then(res => {
				res.forEach(r => {
					r.state = 'continues';
					r.playIng = false;
					r.isplay = false;
					r.isShowimage = false;
					r.isShowProgressBarTime = false;
				});
				this.videoList = res;
				videoread(ops).then(data => {
					const result = data[0];
					this.watchInfo = result;
					this.currentWatchIndex = 0;
					const index = this.videoList.findIndex(
						r => r.id === result.id
					);
					setTimeout(() => {
						if (result.isvip === 1 && result.chackpay === 3) {
							if (this.currentWatchIndex !== index) {
								this.currentWatchIndex = index;
							}
							this.$refs.Payment.open(result);
						} else if (
							result.isvip === 1 &&
							result.chackpay === 2
						) {
							// 余额不足
							this.currentWatchIndex = index;
						} else if (
							result.isvip === 0 ||
							(result.isvip === 1 && result.chackpay === 1)
						) {
							if (this.currentWatchIndex !== index) {
								this.currentWatchIndex = index;
							}
							setTimeout(() => {
								this.videoList[index].isvip = 0; // 购买成功 或者本来就是免费
								//这里的延迟是为了避免执行时间太快而直接跳过执行的 bug
								uni.createVideoContext(
									`video_${this.videoList[index].id}`,
									this
								).seek(0);
								uni.createVideoContext(
									`video_${this.videoList[index].id}`,
									this
								).play();
								this.videoList[index].state = 'play';
								this.videoList[index].playIng = true;
								this.videoList[index].isplay = true;
							}, 200);
						}
						this.$showLoading(false);
					}, 1000);
				});
			});
		},
		videoPlay() {},
		stopTouchMove() {
			return false;
		},
		// 截获竖向滑动
		stopChange(res) {
			// 根据你的条件来禁止左右滑动
			console.log(res);
			return false;
		},
		touchStart(res) {
			this.pageStartY = res.changedTouches[0].pageY;
			console.log('touchStart：' + this.pageStartY);
		},
		touchEnd(res) {
			this.pageEndY = res.changedTouches[0].pageY;
			console.log('touchEnd：' + this.pageEndY);
			let platform = uni.getSystemInfoSync().platform;
			if (platform == 'android') {
				if (this.pageStartY - this.pageEndY > 150) {
					console.log('向上滑动:');
					if (this.wrapIndex < this.videoList.length - 1) {
						this.wrapIndex = this.wrapIndex + 1;
					}
				} else if (this.pageStartY - this.pageEndY < -150) {
					console.log('向下滑动:');
					if (this.wrapIndex > 1) {
						this.wrapIndex = this.wrapIndex - 1;
					}
				}
			}
		},

		chaseKeep() {
			let fn = null;
			let params = {};
			if (this.watchInfo.iskeep === 0) {
				fn = addkeep;
				params = {
					id: this.watchInfo.id,
					sid: this.watchInfo.sid
				};
			} else {
				fn = chasingdramadel;
				params = {
					ids: this.watchInfo.sid
				};
			}
			fn(params).then(() => {
				this.watchInfo.iskeep = this.watchInfo.iskeep === 0 ? 1 : 0;
				if (this.watchInfo.iskeep === 1) {
					clearTimeout(this.voice);
					this.animation = 'shake';

					this.voice = setTimeout(() => {
						this.animation = '';
					}, 100);
				}
			});
		},

		videoChange(e) {
			const index = e.detail.current;
			if (index !== this.currentWatchIndex) {
				this.currentWatchIndex = index;
			}
		},
		completeWorksShow() {
			this.$refs.completeWorks
				.open(this.videoList, this.currentWatchIndex, this.watchInfo)
				.then(res => {
					const index = this.videoList.findIndex(r => r.id === res);
					this.currentWatchIndex = index;
				});
		},
		paySuccess() {
			const currentData = this.videoList[this.currentWatchIndex];
			this.videoList.forEach(r => {
				r.isvip = 0;
			});
			uni.createVideoContext(`video_${currentData.id}`, this).play();
		},
		back() {
			const data = uni.getStorageSync('videoBackRouter');
			if (data.type === 1) {
				uni.switchTab({
					url: data.url
				});
			} else if (data.type === 2) {
				uni.reLaunch({
					url: data.url
				});
			}
		}
	}
};
</script>

<style lang="scss">
.header {
	padding: 0 32rpx;
	height: 88rpx;
	background: #000000;
	justify-content: center;
	.header-text {
		font-size: 28rpx;

		font-weight: bold;
		color: #ffffff;
	}
}
.bottom {
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	height: 100rpx;
	padding: 0 30rpx;
	background-color: #232323;
	.bottom-text {
		font-size: 28rpx;
		font-weight: 500;
		color: #ffffff;
	}
}
.ops {
	position: fixed;
	right: 34rpx;
	bottom: 300rpx;
}
.animation-shake {
	animation: shake 0.3s !important;
}
@keyframes shake {
	0% {
		transform: scale(1);
	}
	20% {
		transform: scale(0.95);
	}
	40% {
		transform: scale(0.8);
	}
	60% {
		transform: scale(0.7);
	}
	80% {
		transform: scale(0.8);
	}
	100% {
		transform: scale(1);
	}
}
.stopTouchMove {
	position: fixed;
	width: 750rpx;
	height: 100%;
	top: 0;
	z-index: 999999;
}
.videoBack {
	position: fixed;
	top: 20rpx;
	left: 20rpx;
	width: 72rpx;
	height: 72rpx;
}
.jishu1 {
	position: fixed;
	top: 35rpx;
	left: 40rpx;
}
</style>
