<template>
	<view>
		<view class="player_box" style="width: 100%; height: 421rpx">
			<view id="player2"></view>
			<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(ct) }}，正在自动续播</cover-view>
					<cover-view class="video-toast__btn" @click="restart()">从头播放</cover-view>
				</cover-view>
			</template>
		</view>
	</view>
</template>

<script>
	var tcPlayerContext = null;
	export default {
		name: "SaasMiniprogramTcPlayer",
		props: {
			playFileId: {
				type: String,
				default: "",
			},
			autoplay: {
				type: Boolean,
				default: false,
			},
			progressControl: {
				type: Boolean,
				default: () => {
					return false //是否禁止拖拽进度条，取值：{true,false}。
				}
			},
			currentTime: {
				type: Number,
				default: 0,
			},
			playbackRate: {
				type: Array,
				default: () => {
					return [1];
				},
			},
		},
		data() {
			return {
				vodPlayerJs: 'https://web.sdk.qcloud.com/player/tcplayer/release/v5.1.0/tcplayer.v5.1.0.min.js',
				videoToastShow: false,
				hasStart: false,
				config: null,
				Elevideo: false,
				isInitSeek: false,
				needSeek: false, // 是否有记录需要跳转播放
				playTime: 0,
				PlayStart: 0,
				isSeeking: false
			};
		},
		created() {
			tcPlayerContext = null;
		},
		mounted() {
			if (this.fileId) {
				this.changeFileId(this.fileId);
			}
		},
		methods: {
			loadPlayerScript(callback) {
				if (!window.TCPlayer) {
					const myScript = document.createElement("script");
					myScript.setAttribute("src", this.vodPlayerJs);
					myScript.onload = callback;
					document.body.appendChild(myScript);
				} else {
					callback();
				}
			},
			// 播放视频
			loadPlayer() {
				let playbackRateIndex = true;
				let playbackRate = [1];
				if (this.playbackRate.length <= 1) {
					playbackRateIndex = false;
				} else {
					playbackRateIndex = true;
					playbackRate = JSON.parse(JSON.stringify(this.playbackRate));
				}
				const TCPlayer = window.TCPlayer;
				console.log("是否显示进度条", this.progressControl);
				this.$api.tcVideoSign(this.fileId).then(async (res) => {
					console.log('腾讯视频res', res)
					let option = {
						plugins: {
							ContinuePlay: {
								auto: true, // 是否禁用续播功能，取值：{true,false}。
								SafeCheck: true // 安全检查
							},
						},
						fakeFullscreen: true,
						licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1323759362_1/v_cube.license',
						controlBar: {
							progressControl: this.progressControl, // 是否禁止拖拽(隐藏)进度条
							playbackRateMenuButton: playbackRateIndex // 是否显示倍速切换的按钮。
						},
						autoplay: this.autoplay, // 自动播放
						playbackRates: playbackRate,
						sources: [{
							src: 'https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8',
						}],

						// fileID: res.data.data.fileID,
						// appID: res.data.data.appID,
						// psign: res.data.data.psign,
						// licenseUrl: res.data.data.licenseUrl,
					};
					if (tcPlayerContext) {
						tcPlayerContext.loadVideoByID({
							fileID: res.data.data.fileID,
							appID: res.data.data.appID,
							psign: res.data.data.psign
						});
					} else {
						option = {
							height: 218,
							...option,
						};
						let player_tencent = document.createElement("video");
						player_tencent.style.width = "100%";
						player_tencent.id = "player-tencent";
						player_tencent.setAttribute("playsinline", true);
						player_tencent.setAttribute("webkit-playsinline", true);
						document
							.getElementById("player2")
							.insertAdjacentElement("afterend", player_tencent);
						tcPlayerContext = TCPlayer("player-tencent", option);
						tcPlayerContext.currentTime(
							this.currentTime || 0);
						this.h5StateChange();
					}
				});
			},
			playing() {
				// if (this.isSeeking) return;
				console.log("腾讯视频恢复播放");
				if (!this.PlayStart) {
					this.onPlayStart();
					return;
				}
				// 设置播放时间会重复触发
				if (this.needSeek) {
					this.videoToastShow = true;
					setTimeout(() => {
						this.closeToast();
					}, 3000);
					this.$emit("studyLog");
					this.needSeek = false;
				}
				// if (!this.Elevideo) {
				// 	this.Elevideo = document.querySelector("video.plv-player-video");
				// 	this.Elevideo &&
				// 		this.Elevideo.addEventListener("timeupdate", this.timeupdate);
				// }
				if (!this.Elevideo) {
					this.Elevideo = true;
					tcPlayerContext.on("timeupdate", this.timeupdate);
				}
			},
			// onSeeking() {
			// 	if (!this.needSeek) {
			// 		console.log("触发拖拽");
			// 		this.isSeeking = true;
			// 		this.$emit('isSeeking', this.isSeeking);
			// 	}
			// },
			onSeeked() {
				console.log("触发拖拽结束");
				this.isSeeking = false;
				this.$emit('isSeeking', this.isSeeking);
			},

			resumeVideo() {
				tcPlayerContext.play();
			},
			playerError(err) {
				console.log("腾讯视频播放err", err);
			},
			timeupdate(e) {
				// if (this.isSeeking) return;
				let time = 0;
				if (!this.PlayStart) return
				time = this.PlayStart == 1 ? (this.currentTime || 0) : this.playCurrentTime();

				if (!this.isInitSeek) {
					if (time >= this.ct) {
						this.isInitSeek = true;
					} else {
						return;
					}
				}
				this.onVideoSeek1(time);

				this.PlayStart++
				this.$emit("timeupdate", time);
			},
			h5StateChange() {
				let states = {
					loadstart: "onPlayerInitOver", // 播放器初始化完毕时触发
					pause: "pause", // 视频暂停时触发
					playing: "playing", // 视频初次播放或由暂停恢复播放时触发
					// seeking: "onSeeking",
					// seeked: "onSeeked",
					ended: "ended", // 当前视频播放完毕时触发
					error: "playerError", // 播放出现错误时触发
				};
				let that = this;
				for (const key in states) {
					tcPlayerContext.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.progressControl) {
					if (Math.abs(time - this.playTime) > 5) {
						console.log("进度条回拉", this.playTime, this.ct);
						this.seekVideo(this.playTime);
					} else {
						this.playTime = time;
					}
				}
			},
			seekVideo(time) {
				time = time || 0;
				tcPlayerContext.currentTime(time);
			},
			restart() {
				this.seekVideo(0);
				this.closeToast();
			},
			// 播放时刻
			playCurrentTime() {
				if (!tcPlayerContext) {
					return 0;
				}
				return tcPlayerContext.currentTime();
			},
			getDuration() {
				return tcPlayerContext.duration();
			},
			// 本次看的时长
			playVideoTime() {
				if (!tcPlayerContext) {
					return 0;
				}
				return tcPlayerContext.currentTime();
			},
			// 暂停播放
			playPause() {
				if (!tcPlayerContext) {
					return;
				}
				tcPlayerContext.pause();
			},
			// 退出全屏
			exitFullScreen() {
				if (!tcPlayerContext) {
					return;
				}
				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) {}
				}
			},
			onPlayerInitOver() {
				console.log("腾讯视频加载完毕");
				uni.$on("playPause", this.playPause);
				this.$emit("loadedmetadata", tcPlayerContext);
			},
			onPlayStart() {
				console.log("腾讯视频初次播放");
				this.PlayStart = 1;
			},
			changeFileId(data) {
				console.log('调用腾讯视频changeFileId')
				if (!data) {
					return;
				}
				this.config = this.$method.isObject(data) ?
					data : {
						fileId: data,
						currentTime: this.currentTime
					};
				if (!this.fileId) {
					return;
				}
				this.PlayStart = 0;
				this.loadPlayerScript(this.loadPlayer);
			},
			closeToast() {
				this.videoToastShow = false;
			},
		},
		destroyed() {
			if (tcPlayerContext) {
				tcPlayerContext.off();
				tcPlayerContext.dispose();
			}
			// // #ifdef H5
			// this.Elevideo &&
			// 	this.Elevideo.removeEventListener("timeupdate", this.timeupdate, false);
			// // #endif
			tcPlayerContext = null;
		},
		computed: {
			fileId() {
				return this.config ? this.config.fileId : this.playFileId;
			},
			ct() {
				return (
					(this.config ? this.config.currentTime : this.currentTime) ||
					0
				);
			},
		},
		watch: {
			ct: {
				handler(time) {
					if (time > 0) {
						this.needSeek = true;
						this.playTime = time;
					}
				},
				immediate: true,
			},
		},
	};
</script>

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

		.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>