<template>
	<view>
		<web-view :webview-styles="webviewStyles" src="/static/html/index.html" @message="handleWebViewMessage"></web-view>
	</view>
</template>
<script>
var wv;
export default {
	data() {
		return {
			playing: false,
			isScreen: false,
			jsReady: false,
			isiOS: false,
			webviewStyles: {
				top: uni.getSystemInfoSync().statusBarHeight,
				width: uni.getSystemInfoSync().screenWidth,
				height: (uni.getSystemInfoSync().screenWidth / 16) * 9 + 50
			},
			prompt: true
		};
	},
	mounted() {
		setTimeout(() => {
			// #ifdef APP-PLUS
			wv = this.$parent.$scope.$getAppWebview().children()[0];
			wv.setStyle(this.webviewStyles);
			// #endif
		}, 100);
		this.isiOS = uni.getSystemInfoSync().platform == 'ios';
	},
	beforeDestroy() {
		plus.screen.lockOrientation('portrait-primary');
	},
	methods: {
		playerhide() {
			wv.hide();
		},
		playershow() {
			wv.show();
		},
		fullScreen(isFullscreen) {
			this.isScreen = isFullscreen;
			// #ifdef APP-PLUS
			if (isFullscreen) {
				let page = this.$mp.page.$getAppWebview();
				page.setStyle({ popGesture: 'none' });
				plus.screen.lockOrientation('landscape-primary');
				//安卓需要延时执行 来屏蔽宽高变化的动画
				setTimeout(
					() => {
						wv.setStyle({ top: 0, width: '100%', height: '100%' });
						this.sendMessageToWebView('callFullScreen', true);
					},
					this.isiOS ? 0 : 50
				);
				plus.navigator.setFullscreen(true);
				if (!this.isiOS) {
					plus.navigator.hideSystemNavigation();
				}
				this.sendNoticeToNative({ action: 'HomeIndicatorAutoHidden', value: true });
			} else {
				let page = this.$mp.page.$getAppWebview();
				page.setStyle({ popGesture: 'close' });
				plus.screen.lockOrientation('portrait-primary');
				setTimeout(
					() => {
						wv.setStyle(this.webviewStyles);
						this.sendMessageToWebView('callFullScreen', false);
					},
					this.isiOS ? 0 : 50
				);
				if (!this.isiOS) {
					plus.navigator.showSystemNavigation();
				}
				plus.navigator.setFullscreen(false);
				this.sendNoticeToNative({ action: 'HomeIndicatorAutoHidden', value: false });
			}
			// #endif
		},
		sendNoticeToNative(object) {
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == 'ios') {
				//向iOS发送通知
				var notiClass = plus.ios.importClass('NSNotificationCenter');
				notiClass.defaultCenter().postNotificationNameobject('uniCallBackMessage', object);
			}
			// #endif
		},
		sendMessageToWebView(funName, parms) {
			if (wv) {
				wv.evalJS(`${funName}(${JSON.stringify(parms)})`);
			} else {
				console.log('js not ready');
			}
		},
		async handleWebViewMessage(evt) {
			// console.log("接收到的消息：" + JSON.stringify(evt.detail.data));
			let parms = evt.detail.data[0];
			let action = parms['action'];
			if (action == 'bridgeReady') {
				this.jsReady = true;
			} else if (action == 'fullscreen') {
				this.fullScreen(parms['fullscreen']);
			} else if (action == 'share') {
				this.$emit('openShare');
			} else if (action == 'back') {
				this.$emit('toBack');
			} else if (action == 'adsClick') {
				this.$emit('openAD', parms['url']);
			} else if (action == 'airplay') {
				// uni.getNetworkType({
				//   success: function (res) {
				//     if (res.networkType !== "wifi") {
				//       uni.showToast({
				//         icon: "none",
				//         title:
				//           "暂无投屏设备, 请确认您的移动设备和电视链接到了同一个WIFI网络",
				//         duration: 3000,
				//       });
				//     }
				//   },
				// });
				if (uni.getSystemInfoSync().platform == 'android') {
					this.$emit('openairplay');
				}
			} else if (action == 'playpip') {
				this.$emit('playpip', parms['pipstate']);
			} else if (action == 'switchPlayIndex') {
				this.$emit('changePlay', parms['index']);
			} else if (action == 'updatePlaying') {
				this.playing = parms['playing'];
			} else if (action == 'videoNext') {
				this.$emit('playNext');
			} else if (action == 'console') {
				console.log(parms['log']);
			} else if (action == 'currentTime') {
				let time = parms['time'];
				this.$emit('update:currentTime', time);
			} else if (action == 'volumeChange') {
				let type = parms['type'];
				let rate = parms['rate'];
				if (type == 'light') {
					await this.setScreenBrightness(rate);
				} else {
					//安卓免打扰权限（需云打包或自定义基座） 如果未开启免打扰权限 设置音量无效
					if (!this.isiOS) {
						let ctx = plus.android.runtimeMainActivity();
						let Context = plus.android.importClass('android.content.Context');
						let NotificationManager = plus.android.importClass('android.app.NotificationManager');
						let notificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE);
						let Build = plus.android.importClass('android.os.Build');
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !notificationManager.isNotificationPolicyAccessGranted()) {
							//弹窗提示
							this.sendMessageToWebView('showAlert', {
								type: 'NOTIFICATION_SERVICE',
								title: '当前设备处于免打扰状态，需要开启免打扰权限，是否开启？',
								cancel: '取消',
								confirm: '去开启'
							});
						} else {
							plus.device.setVolume(rate);
						}
					} else {
						plus.device.setVolume(rate);
					}
				}
			} else if (action == 'getVolumeInfo') {
				let volume = plus.device.getVolume();
				let light = await this.getScreenBrightness();
				this.sendMessageToWebView('updateVolumeInfo', {
					volume: volume,
					light: light
				});
			} else if (action == 'alertClick') {
				let type = parms['type'];
				if (type == 'NOTIFICATION_SERVICE') {
					let isCancel = parms['isCancel'];
					if (isCancel) {
						this.sendMessageToWebView('hideAlert');
					} else {
						this.sendMessageToWebView('hideAlert');
						this.fullScreen(false);
						// 打开免打扰权限
						setTimeout(() => {
							let ctx = plus.android.runtimeMainActivity();
							let Intent = plus.android.importClass('android.content.Intent');
							let intent = new Intent('android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS');
							ctx.startActivity(intent);
						}, 300);
					}
				}
			} else if (action == 'addDanmu') {
				this.$emit('addDanmu', parms['danmu']);
			} else if (action == 'err') {
				if (this.prompt) {
					this.prompt = false;
					setTimeout(() => {
						uni.showToast({
							icon: 'none',
							title: '当前源播放失败，请换个播放源试试吧～',
							duration: 3000
						});
						this.prompt = true;
					}, 3000);
				}
			}
		},
		loadData(parms) {
			if (this.jsReady) {
				parms = { ...parms, isScreen: this.isScreen };
				this.sendMessageToWebView('loadData', parms);
			} else {
				setTimeout(() => {
					this.loadData(parms);
				}, 100);
			}
		},
		playStatus() {
			return this.playing;
		},
		destroy() {
			this.sendMessageToWebView('destroy', {});
		},
		pause() {
			this.sendMessageToWebView('pause', {});
		},
		currentTime() {
			this.sendMessageToWebView('currentTime', {});
		},
		setScreenBrightness(rate) {
			return new Promise(function (resolve, reject) {
				uni.setScreenBrightness({
					value: rate,
					success: function () {
						resolve(rate);
					},
					fail: function (err) {
						reject(rate);
					}
				});
			});
		},
		getScreenBrightness() {
			return new Promise(function (resolve, reject) {
				uni.getScreenBrightness({
					success: function (res) {
						resolve(res.value);
					},
					fail: function (err) {
						reject(0.5);
					}
				});
			});
		}
	}
};
</script>