<template>
	<view>
		<web-view :src="src"  :update-title="false" @message="getData"></web-view>
	</view>
</template>

<script>
	import store from '@/store'
	import setting from '@/setting.js'
	export default {
		data() {
			return {
				src:"",
				title:"",
				params:{}
			};
		},
		onLoad(option) {
			const token = store.state.user.token
			uni.setNavigationBarTitle({
			  title: option.deviceName,
			});
			this.src=setting.videoPlayUrl+"/video/index.html?token="+token+"&deviceId="+option.deviceId+"&fetchUrl="+setting.fetchUrl
		},
		methods:{
			getData(event){
				if(event.detail.data[0].img){
					this.saveImg(event.detail.data[0].img)
				}else if(event.detail.data[0].code){
					this.onCode(event.detail.data[0].code)
				}else if(event.detail.data[0].msg){
					this.onMessage(event.detail.data[0].msg)
				}else{
					console.log(event.detail.data[0].file);
				}
			},
			saveImg(qrImgUrl){
				uni.showLoading({
					title: '图片保存中...'
				})
				const bitmap = new plus.nativeObj.Bitmap("test");
				bitmap.loadBase64Data(qrImgUrl, function() {
					const url = "_doc/" + new Date().getTime() + ".png";  // url为时间戳命名方式
					bitmap.save(url, {
						overwrite: true,  // 是否覆盖
						quality: 'quality'  // 图片清晰度
					}, (i) => {
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: function() {
								uni.hideLoading();
								uni.showToast({
									title: '图片保存成功',
									icon: 'none'
								})
								bitmap.clear()
							}
						});
					}, (e) => {
						uni.hideLoading();
						uni.showToast({
							title: '图片保存失败',
							icon: 'none'
						})
						bitmap.clear()
					});
				}, (e) => {
					uni.showToast({
						title: '图片保存失败',
						icon: 'none'
					})
					bitmap.clear()
				});
			},
			saveVideo(video){},
			async onMessage(msg){
				uni.showToast({
					icon: 'none',
					title: msg,
				})
			},
			async onCode(code){
				if (code === 401) {					// token 失效
					uni.showToast({
						icon: 'none',
						title: '用户信息已失效，请重新登录',
					})
					await store.dispatch('userFadeOut')
					uni.$u.route({
						type: 'reLaunch',
						url: 'pages/login/index'
					})
				}else if(code === 403) {
					const errMsg = '无授权，请联系管理员'
					uni.showToast({
						icon: 'none',
						title: errMsg,
					})
				}else if(code !== 200) {
					const errMsg = 'unknown exception'
					uni.showToast({
						icon: 'none',
						title: errMsg,
					})
				}
			},
		}
	}
</script>