<template>
	<view>
		<view class="player_box" style="width: 100%; height: 421rpx">
			<!-- #ifdef MP-WEIXIN -->
			<polyv-player id="playerVideo" playerId="playerVideo" height="421rpx" :vid="vid" :showSettingBtn="true"
				:enablePlayGesture="true" :custom-cache="false" :object-fit="'contain'" @statechange="wxStatechange"
				@timeupdate="timeupdate" :autoplay="autoplay" :page-gesture="true" :vslide-gesture="true"
				:vslide-gesture-in-fullscreen="true" :isAllowSeek="allowSeek" :playbackRate="playbackRate"
				:enableAutoRotation="enableAutoRotation" @loadedmetadata="loadedmetadata"></polyv-player>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view id="player"></view>
			<!-- #endif -->
			<template v-if="videoToastShow">
				<cover-view class="video-toast__close" @click="closeToast()">X</cover-view>
				<cover-view class="video-toast">
					<cover-view class="video-toast__text">您上次看到
						{{ $method.secondToDate(vct) }}，正在自动续播</cover-view>
					<cover-view class="video-toast__btn" @click="restart()">从头播放</cover-view>
				</cover-view>
			</template>
		</view>
	</view>
</template>

<script>
	var polyvPlayerContext = null;
	export default {
		name: "SaasMiniprogramPolyvPlayer",
		props: {
			playVid: {
				type: String,
				defaule: "",
			},
			autoplay: {
				type: Boolean,
				defaule: false,
			},
			allowSeek: {
				type: String,
				defaule: () => {
					// #ifdef MP-WEIXIN
					return "no";
					// #endif
					// #ifdef H5
					return "on";
					// #endif
				},
			},
			videoCurrentTime: {
				type: Number,
				defaule: 0,
			},
			playbackRate: {
				type: Array,
				defaule: () => {
					return [1];
				},
			},
		},
		data() {
			return {
				barTimer: null,
				vodPlayerJs: "https://player.polyv.net/resp/vod-player/latest/player.js",
				videoToastShow: false,
				enableAutoRotation: true,
				hasStart: false,
				config: null,
				Elevideo: null,
				isInitSeek: false,
				needSeek: false, // 是由有记录需要跳转播放
				playTime: 0,
				PlayStart: 0,
			};
		},
		created() {
			polyvPlayerContext = null;
		},

		mounted() {
			if (this.vid) {
				this.changeVid(this.vid);
			}
		},
		methods: {
			loadPlayerScript(callback) {
				if (!window.polyvPlayer) {
					const myScript = document.createElement("script");
					myScript.setAttribute("src", this.vodPlayerJs);
					myScript.onload = callback;
					document.body.appendChild(myScript);
				} else {
					callback();
				}
			},
			// 播放视频
			loadPlayer() {
				if (this.playbackRate.length <= 1) {
					var playbackRate = false
				} else {
					var playbackRate = JSON.parse(JSON.stringify(this.playbackRate))
				}
				const polyvPlayer = window.polyvPlayer;
				console.log("this.allowSeek", this.allowSeek)
				this.$api.polyvVideoSign(this.vid).then(async (res) => {
					let option = {
						showLine: "off",
						ban_history_time: "on",
						vid: this.vid,
						forceH5: true,
						autoplay: this.autoplay, // 自动播放
						ban_seek: this.allowSeek, // 是否禁止拖拽进度条
						ban_skin_progress: this.allowSeek == 'on' ? true : false,
						speed: playbackRate, // 倍数
						banSeekDeviation: 7, // 做兼容
						teaser_show: 0,
						tail_show: 1,
						hideSwitchPlayer: true,
						watchStartTime: this.videoCurrentTime, // 播放开始时间，表示视频从第几秒开始播放，参数值需小于视频时长
						ts: res.data.data.ts, // 移动播放加密视频需传入的时间戳。
						sign: res.data.data.sign, // 移动端播放加密视频所需的签名
					};
					if (polyvPlayerContext) {
						polyvPlayerContext.changeVid(option);
					} else {
						option = {
							wrap: "#player",
							width: "100%",
							height: 218,
							...option,
						};
						polyvPlayerContext = polyvPlayer(option);
						this.h5StateChange();
					}
				});
			},
			wxStatechange(newstate) {
				polyvPlayerContext = this.selectComponent("#playerVideo");
				// ["playing", "pause", "ended","error"]
				let state = newstate.detail.newstate;
				if (state == "error") {
					state = "playerError";
				}
				this[state] && this[state]();
				this.$emit(state);
			},
			playing() {
				// 设置播放时间会重复触发
				if (this.needSeek) {
					// #ifdef H5
					this.videoToastShow = true;
					// #endif
					// #ifdef MP-WEIXIN
					this.videoToastShow = true;
					// #endif
					setTimeout(() => {
						this.closeToast();
					}, 3000);
					// #ifdef MP-WEIXIN
					this.seekVideo(this.videoCurrentTime);
					// #endif
					this.$emit("studyLog");
					this.needSeek = false;
				}

				// #ifdef H5
				if (!this.Elevideo) {
					this.Elevideo = document.querySelector("video.plv-player-video");
					this.Elevideo &&
						this.Elevideo.addEventListener("timeupdate", this.timeupdate);
				}
				// #endif
			},
			resumeVideo() {
				// #ifdef MP-WEIXIN
				polyvPlayerContext.play();
				// #endif
				// #ifdef H5
				polyvPlayerContext.j2s_resumeVideo();
				// #endif
			},
			playerError(err) {
				console.log("播放err", err);
			},
			timeupdate(e) {
				let time = 0;
				// #ifdef MP-WEIXIN
				time = e.detail.currentTime;
				// #endif
				// #ifdef H5
				if (!this.PlayStart) return
				time = this.PlayStart == 1 ? (this.videoCurrentTime || 0) : this.playCurrentTime();
				// if (!this.isInitSeek) {
				//   if (time >= this.vct) {
				//     this.isInitSeek = true;
				//   } else {
				//     return;
				//   }
				// }
				// this.onVideoSeek1(time);
				this.PlayStart++
				// #endif
				this.$emit("timeupdate", time);
			},
			h5StateChange() {
				let states = {
					s2j_onPlayerInitOver: "onPlayerInitOver", // 播放器初始化完毕时触发
					s2j_onPlayStart: "onPlayStart", // 视频初次播放时触发
					s2j_onVideoPause: "pause", // 视频暂停时触发
					s2j_onVideoPlay: "playing", // 视频初次播放或由暂停恢复播放时触发
					s2j_onPlayOver: "ended", // 当前视频播放完毕时触发
					s2j_onVideoSeek: "onVideoSeek", // 视频拖拽进度时触发
					s2j_onPlayerError: "playerError", // 播放出现错误时触发
					serverError: "playerError", // 逻辑错误
				};
				let that = this;
				for (const key in states) {
					polyvPlayerContext.on(key, function() {
						that[states[key]] && that[states[key]](...arguments);
						that.$emit(states[key]);
					});
				}
			},
			onVideoSeek(start, end, vid) {
				// if (this.allowSeek == "off") {
				//   return;
				// }
				// if (end - this.playTime > 10) {
				//   this.seekVideo(start);
				// }
			},
			// 新增用户视频学习日志
			studyLog() {
				this.$http({
					url: "/user/study/log",
					method: "post",
					data: {
						goodsId: this.goodsId,
						courseId: this.courseId,
						moduleId: this.moduleId || 0,
						chapterId: this.chapterId || 0,
						sectionId: this.playSectionId || 0,
						fromPlat: 1, //来源平台 1小程序 2PC网站
						goodsType: 1, // 商品类型 1视频2题库 3补考 4前培 5虚拟赠送题库 6直播
						orderGoodsId: this.orderGoodsId,
					},
				}).then((res) => {});
			},
			onVideoSeek1(time) {
				if (this.allowSeek == "off") {
					return;
				}

				if (Math.abs(time - this.playTime) > 5) {
					console.log("进度条回拉", this.playTime, this.vct);
					this.seekVideo(this.playTime);
				} else {
					this.playTime = time;
				}
			},
			seekVideo(time) {
				time = time || 0;
				// #ifdef MP-WEIXIN
				polyvPlayerContext.seek(time);
				// #endif
				// #ifdef H5
				polyvPlayerContext.j2s_seekVideo(time);
				// #endif
			},
			restart() {
				this.seekVideo(0);
				this.closeToast();
			},
			// 播放时刻
			playCurrentTime() {
				if (!polyvPlayerContext) {
					return 0;
				}
				// #ifdef MP-WEIXIN
				return polyvPlayerContext.getCurrentTime(); //播放时刻
				// #endif
				// #ifdef H5
				return polyvPlayerContext.j2s_getCurrentTime();
				// #endif
			},
			getDuration() {
				// #ifdef MP-WEIXIN
				return polyvPlayerContext.getDuration();
				// #endif
				// #ifdef H5
				return polyvPlayerContext.j2s_getDuration();
				// #endif
			},
			// 本次看的时长
			playVideoTime() {
				if (!polyvPlayerContext) {
					return 0;
				}
				// #ifdef MP-WEIXIN
				return polyvPlayerContext.getVideoPlayDuration();
				// #endif
				// #ifdef H5
				return polyvPlayerContext.j2s_realPlayVideoTime();
				// #endif
			},
			// 暂停播放
			playPause() {
				if (!polyvPlayerContext) {
					return;
				}
				// #ifdef MP-WEIXIN
				polyvPlayerContext.pause();
				// #endif
				// #ifdef H5
				polyvPlayerContext.j2s_pauseVideo();
				// #endif
			},
			// 退出全屏
			exitFullScreen() {
				if (!polyvPlayerContext) {
					return;
				}
				// #ifdef MP-WEIXIN
				polyvPlayerContext.exitFullScreen();
				// #endif
				// #ifdef H5
				if (
					!!(
						document.webkitIsFullScreen ||
						document.mozFullScreen ||
						document.msFullscreenElement ||
						document.fullscreenElement
					)
				) {
					try {
						var de = document;
						if (de.exitFullscreen) {
							de.exitFullscreen();
						} else if (de.mozCancelFullScreen) {
							de.mozCancelFullScreen();
						} else if (de.webkitCancelFullScreen) {
							de.webkitCancelFullScreen();
						}
					} catch (err) {}
				}
				// #endif
			},
			onPlayerInitOver() {
				uni.$on("playPause", this.playPause);
				this.$emit("loadedmetadata", polyvPlayerContext);
			},
			onPlayStart() {
				console.log("初始化")
				this.PlayStart = 1
			},
			loadedmetadata() {
				if (this.hasStart) {
					// 防止loadedmetadata事件第二次触发
					return;
				}
				this.hasStart = true;
				setTimeout(() => {
					this.hasStart = false;
				}, 3000);
				// #ifdef MP-WEIXIN
				polyvPlayerContext = this.selectComponent("#playerVideo");
				// #endif
				this.onPlayerInitOver();
			},
			changeVid(data) {
				if (!data) {
					return;
				}
				this.config = this.$method.isObject(data) ?
					data : {
						vid: data,
						videoCurrentTime: this.videoCurrentTime
					};
				if (!this.vid) {
					return;
				}
				this.PlayStart = 0
				// #ifdef H5
				this.loadPlayerScript(this.loadPlayer);
				// #endif
				// #ifdef MP-WEIXIN
				if (polyvPlayerContext) {
					polyvPlayerContext.changeVid(this.vid);
					this.seekVideo(this.videoCurrentTime);
				}
				// #endif
			},
			closeToast() {
				this.videoToastShow = false;
			},
		},
		destroyed() {
			if (polyvPlayerContext) {
				polyvPlayerContext.destroy();
			}
			// #ifdef H5
			this.Elevideo &&
				this.Elevideo.removeEventListener("timeupdate", this.timeupdate, false);
			// #endif
			polyvPlayerContext = null;
		},
		computed: {
			vid() {
				return this.config ? this.config.vid : this.playVid;
			},
			vct() {
				return (
					(this.config ? this.config.videoCurrentTime : this.videoCurrentTime) ||
					0
				);
			},
		},
		watch: {
			vct: {
				handler(time) {
					if (time > 0) {
						this.needSeek = true;
						this.playTime = time;
					}
				},
				immediate: true,
			},
		},
	};
</script>

<style lang="scss" scoped>
	.player_box {
		position: relative;

		#playerVideo {
			position: relative;
			z-index: 99;
			width: 200rpx;
			height: 200rpx;
		}

		.video-toast {
			position: absolute;
			width: 686rpx;
			height: 80rpx;
			background: rgba(0, 0, 0, 0.6);
			border-radius: 24rpx;
			bottom: 100rpx;
			left: 50%;
			transform: translateX(-50%);
			color: #fff;
			display: flex;
			font-size: 26rpx;
			align-items: center;
			overflow: visible;
			z-index: 999;

			&__text {
				flex: 1;
				margin-left: 40rpx;
			}

			&__btn {
				width: 180rpx;
				text-align: center;
				border-left: 1rpx solid #fff;
			}
		}

		.video-toast__close {
			position: absolute;
			right: 32rpx;
			bottom: 184rpx;
			width: 40rpx;
			height: 40rpx;
			line-height: 40rpx;
			text-align: center;
			background: rgba(0, 0, 0, 0.6);
			border-radius: 50%;
			color: rgba(255, 255, 255, 0.3);
		}
	}
</style>