<template>
	<view class="container">
		<web-view :src="src" @message="handlePostMessage"></web-view>
	</view>
</template>
<script>
	var wv;
	// #ifdef APP-PLUS
	import permision from '@/utils/wa-permission/permission.js'
	// #endif
	export default {
		data() {
			return {
				src: '',
			}
		},
		onLoad() {
			this.onReloadWebview()
		},
		onReady() {
			// #ifdef APP-PLUS
			var currentWebview = this.$scope.$getAppWebview()
			//此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
			//如果是页面初始化调用时，需要延时一下
			setTimeout(function() {
				wv = currentWebview.children()[0]
			}, 1000);
			// #endif
		},
		methods: {
			onReloadWebview() {
				this.src = 'http://10.89.114.11:9001/datang/meeting/client/'
			},
			// webview向外部发送消息
			handlePostMessage(e) {
				var data = e.detail.data || []
				if (data.length) {
					var bridgeParam = data[0]
					// 集中控制bridge
					this.onBridgeHandler(bridgeParam)
				}
			},
			onBridgeHandler({
				method,
				param,
				callback
			}) {
				var currentWebview = this.$scope.$getAppWebview()
				wv = currentWebview.children()[0]
				var onAuthHandlerFinished = (result) => {
					wv.evalJS(`${callback}(${result})`);
				}
				if (method === 'camera') {
					this.getCameraAuth(param, onAuthHandlerFinished)
				}
				if (method === 'record') {
					this.getAudioAuth(param, onAuthHandlerFinished)
				}
			},
			getCameraAuth(param, callback) {
				var result = uni.getAppAuthorizeSetting()
				if (result.cameraAuthorized === 'authorized') {
					// 已获取到权限了
					callback && callback(1)
				} else {
					permision.requestAndroidPermission('android.permission.CAMERA').then((e) => {
						// 已获取到权限了
						callback && callback(e)
					}).catch((err) => {
						// 没有获取到权限
						callback && callback(false)
						// 打开系统设置界面
						uni.openAppAuthorizeSetting({
							success(res) {
								console.log('openAppAuthorizeSetting::', res)
							}
						})
					})
				}
			},
			getAudioAuth(param, callback) {
				var result = uni.getAppAuthorizeSetting()
				if (result.microphoneAuthorized === 'authorized') {
					// 已获取到权限了
					callback && callback(1)
				} else {
					permision.requestAndroidPermission('android.permission.RECORD_AUDIO').then((e) => {
						// 已获取到权限了
						callback && callback(e)
					}).catch((err) => {
						// 没有获取到权限
						callback && callback(false)
						// 打开系统设置界面
						uni.openAppAuthorizeSetting({
							success(res) {
								console.log('openAppAuthorizeSetting::', res)
							}
						})
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
	}
</style>