<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,
				config: null,
				Elevideo: false,
				needSeek: false, // 是否有记录需要跳转播放
				playTime: 0,
				PlayStart: 0, // 是否初次播放（因为腾讯视频没有初次播放事件）
			};
		},
		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.autoplay)
				console.log("腾讯视频是否允许拖拽进度条", this.progressControl) 
				this.$api.tcVideoSign(this.fileId).then(async (res) => {
							console.log("请求腾讯视频参数", res)
								let option = {
									preload: "auto",
									fakeFullscreen: true,
									// licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1323759362_1/v_cube.license',
									plugins: {
										SafeCheck: true // 安全检查
									},
									autoplay: this.autoplay, // 自动播放
									playbackRates: playbackRate,
									controlBar: {
										progressControl: this.progressControl, // 是否禁止拖拽(隐藏)进度条
										playbackRateMenuButton: playbackRateIndex // 是否显示倍速切换的按钮。
									},
									// sources: [{
									// 	src: 'https://1500005692.vod2.myqcloud.com/43843706vodtranscq1500005692/62656d94387702300542496289/v.f100240.m3u8',
									// }],

									fileID: this.fileId,
									appID: res.data.data.appID,
									psign: res.data.data.psign,
									licenseUrl: res.data.data.licenseUrl,
								};
								if (tcPlayerContext) {
									tcPlayerContext.loadVideoByID({
										fileID: this.fileId,
										appID: res.data.data.appID,
										psign: res.data.data.psign
									});
									tcPlayerContext.currentTime(
										this.currentTime || 0);
								} else {
									// 获取当前设备的信息
									uni.getSystemInfo({
										success: (res) => {
											// 高度宽度的单位都是px 
											// console.log(res.screenHeight); // 屏幕高度，包含导航栏
											// console.log(res.windowHeight); // 能够使用的窗口高度，不包含导航栏
											// console.log(res.screenWidth); // 屏幕宽度
											// console.log(res.windowWidth); // 能够使用的窗口宽度
											// 能够使用的窗口高度，将px转换rpx
											// let windowHeight = (res.windowHeight * (750 / res.windowWidth));
											option = {
												width: res.windowWidth,
												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() {
						console.log("腾讯视频恢复播放");
						if (!this.PlayStart) {
							this.onPlayStart();
						}
						// 设置播放时间会重复触发
						if (this.needSeek) {
							this.videoToastShow = true;
							setTimeout(() => {
								this.closeToast();
							}, 3000);
							this.$emit("studyLog");
							this.needSeek = false;
						}
						if (!this.Elevideo) {
							this.Elevideo = true;
							tcPlayerContext.on("timeupdate", this.timeupdate);
						}
					},
					// 视频恢复播放
					resumeVideo() {
						tcPlayerContext.play();
					},
					// 视频播放错误
					playerError(err) {
						console.log("腾讯视频播放err", err);
					},
					// 视频计时器
					timeupdate(e) {
						let time = 0;
						if (!this.PlayStart) return
						time = this.PlayStart == 1 ? (this.currentTime || 0) : this.playCurrentTime();
						this.PlayStart++
						this.$emit("timeupdate", time);
					},
					// 绑定事件
					h5StateChange() {
						let states = {
							loadstart: "onPlayerInitOver", // 播放器初始化完毕时触发
							pause: "pause", // 视频暂停时触发
							playing: "playing", // 视频初次播放或由暂停恢复播放时触发
							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]);
							});
						}
					},
					// 新增用户视频学习日志
					studyLog() {},
					// 选定时间播放
					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();
				}
				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>