<template>
	<view class="page-web">
		<web-view ref='webview' :webview-styles="webviewStyles" @message="handleMessage" :src="src"></web-view>
	</view>
</template>

<script>
import { loadLocation } from './tools'
import { CheckContactPermission, SelectContact } from './authPermission'
import { UploadFile } from './utils/uploads'
import Permission from '@/js_sdk/wa-permission/permission' //权限工具类
const LF = uni.requireNativePlugin('AThree-LFv2')
let token = uni.getStorageSync('token')
export default {
	name: "WEB",
	data() {
		return {
			src: '',
			wv: null,
			isLogin: token,
			canBack: false,
			webviewStyles: {
				progress: {
					color: '#5688E8'
				}
			},
			deviceStatus: '',
			typePage: false,
		};
	},
	onBackPress(e) {
		if (this.wv && this.canBack) {
			this.wv.back()
			return true
		}
		return false
	},
	onReady() {
		const _that = this
		// #ifdef APP-PLUS
		//此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
		let currentWebview = _that.$scope.$getAppWebview();
		setTimeout(() => {
			this.wv = currentWebview.children()[0]
			// 物理按键返回
			_that.wv.addEventListener(
				'loaded',
				() => {
					_that.wv.canBack((e) => {
						_that.canBack = e.canBack
					})
				},
				false
			)
		}, 1000) //如果是页面初始化调用时，需要延时一下
		// #endif
	},
	async onLoad(option) {
		const that = this;
		if (option.url) this.src = option.url
		uni.getStorage({
			key: 'm-device-info',
			success: function (res) {
				const { device } = JSON.parse(res.data)
				that.deviceStatus = device
			}
		})
	},
	onUnload() {
		const user_info_obj = uni.getStorageSync('user_info_obj')? JSON.parse(uni.getStorageSync('user_info_obj')):{}
		uni.setStorageSync('user_info_obj', JSON.stringify(user_info_obj));
	},
	methods: {
		
		handleMessage(e) {
			const data = e.detail.data;
			if (!data || data.lenght === 0) {
				this.toast('调用APP方法报错');
				return;
			}
			const {
				name,
				params
			} = data[0];
			if (!name) {
				this.toast('缺少方法名', 'error')
				return
			}
			if (this.isLogin) {
				if (params) {
					this[name](params)
				} else {
					this[name]()
				}
			}
		},
		//返回方法
		GoBack(num) {
			console.log('wori')
			try {
				const self = this
				uni.navigateBack({
					delta: num,
					success(res) {
						console.log(res, '9877')

						self.typePage = true
						console.log(self.typePage, 'resss')
					}
				})
			} catch (err) {
				this.toast('返回失败')
				console.log(err, 'err')
			}

		},

		UserToken(token) {
			uni.setStorage({
				key: 'm-token',
				data: token,
				success: () => {
					console.log('m-token存储成功');
				}
			})
		},

		// 删除localtabbar
		removeRefreshStorage() {
			uni.removeStorageSync('hasRefresh')
			console.log('删除了hasRefresh')
		},

		// 隐藏tabbar
		hideLoading() {
			// console.log('调用了APP的hideLoading方法')
			uni.hideLoading()
		},
		// 隐藏tabbar
		hideTabBar() {
			uni.hideTabBar()
		},
		// 显示tabbar
		showTabBar() {
			uni.showTabBar()
		},
		// 获取当前WebView实例
		GetWebView() {
			const currentWebview = this.$scope.$getAppWebview();
			let wv = currentWebview.children()[0];
			return wv;
		},
		// 获取状态栏高度
		GetStatusBarHei() {
			try {
				const windowInfo = uni.getWindowInfo()
				const {
					statusBarHeight
				} = windowInfo;
				this.GetWebView().evalJS("receiveStatusBarHei('" + statusBarHeight + "')")
			} catch (err) {
				console.log(err, '什么错')
				this.toast('获取状态栏高度报错')
			}
		},
		// 获取用户手机号
		GetUserMobile() {
			const self = this
			try {
				uni.getStorage({
					key: 'l-mobile',
					success: function (res) {
						console.log(res, '结果')
						const mobile = res.data;
						self.GetWebView().evalJS("receiveUserMobile('" + mobile + "')")
					},
					fail: function (err) {
						console.log(err, '报错了')
					}
				})

				// const mobileCell = uni.getStorageSync('d-mobile')
				// this.GetWebView().evalJS(`receiveUserMobile('${mobileCell}')`)
			} catch (err) {
				console.log(err, '什么错')
				self.toast('获取用户手机号报错')
			}
		},
		// 拨打电话
		MakeCall(num) {
			try {
				uni.makePhoneCall({
					phoneNumber: num
				});
			} catch (err) {
				this.toast('拨打电话报错')
			}
		},
		// Toast提示框
		toast(title, type) {
			uni.showToast({
				icon: type ? type : "none",
				title
			})
		},
		// 设置缓存
		SetLocalStore(config) {
			try {
				if (!config) return
				const { key, val } = config
				uni.setStorageSync(key, val)
			} catch (err) {
				console.log(err, '设置本地存储报错')
			}
		},
		// Toast 提示框
		Toast(config) {
			try {
				uni.showToast({
					...config
				})
			} catch (err) {
				this.toast('提示框报错')
			}
		},

		// 实名认证正面
		Camera_OCR_Front(config) {
			console.log('实名认证前面', config)
			// 检查相机权限
			// if (!this.CheckCamera()) return;
			console.log('哈哈哈')
			const that = this;
			try {
				console.log(LF, '忍忍')
				LF.Camera_UP({
					...config
				}, async (res) => {
					console.log(res, 'res-front1')
					if (res.code == 1 && res.info) {
						let chacheImg = res.standardImage.replace(/\n/g, '')
						if (res.info && res.info.rectifiedImage) delete res.info.rectifiedImage;
						const result = {
							info: res.info
						}
						UploadFile(config, `data:image/png;base64,${chacheImg}`).then(file => {
							result.fileUrl = file.fileUrl
							if (file.statusCode === 200) {
								that.wv.evalJS(`receiveOcrFront('${JSON.stringify(result)}')`)
								uni.showToast({
									icon: "success",
									title: "图片上传成功"
								})
							} else {
								uni.showToast({
									icon: "success",
									title: "图片上传失败"
								})
							}
						}).catch(err => {
							console.log(err)
							uni.showToast({
								icon: 'error',
								title: "图片上传失败"
							})
						})

					} else if (res.code == 10) {
						uni.showToast({
							icon: "none",
							title: "请重拍一张照片试一试"
						})
					} else {
						uni.showToast({
							icon: "none",
							title: "请重拍一张照片试一试"
						})
					}
				})
			} catch (err) {
				console.log(err, 'OCR识别错误')
			}
		},

		// 实名认证反面
		Camera_OCR_Back(config) {
			// 检查相机权限
			// if (!this.CheckCamera()) return;
			const that = this;
			try {
				LF.Camera_UP({
					...config
				}, (res) => {
					if (res.code == 1 && res.info) {
						let chacheImg = res.standardImage.replace(/\n/g, '')
						if (res.info && res.info.rectifiedImage) delete res.info.rectifiedImage;
						const result = {
							info: res.info
						}
						UploadFile(config, `data:image/png;base64,${chacheImg}`).then(file => {
							result.fileUrl = file.fileUrl
							if (file.statusCode === 200) {
								that.wv.evalJS(`receiveOcrBack('${JSON.stringify(result)}')`)
								uni.showToast({
									icon: "success",
									title: "图片上传成功"
								})
							} else {
								uni.showToast({
									icon: "success",
									title: "图片上传失败"
								})
							}
						}).catch(err => {
							console.log(err)
							uni.showToast({
								icon: 'error',
								title: "图片上传失败"
							})
						})



					} else if (res.code == 10) {
						uni.showToast({
							icon: "none",
							title: "请重拍一张照片试一试"
						})
					} else {
						uni.showToast({
							icon: "none",
							title: "请重拍一张照片试一试"
						})
					}
				})
			} catch (err) {
				console.log(err, 'OCR识别错误')
			}
		},

		// 专门为OCR页面做的
		SetReloadFlag(flag) {
			if (flag === 'NO') {
				uni.setStorageSync('reloadFlag', 'true')
			} else {
				if (uni.getStorageSync('reloadFlag')) uni.removeStorageSync('reloadFlag')
			}
		},


		// 隐藏导航了
		HideNavBar() {
			try {
				let pages = getCurrentPages();
				let page = pages[pages.length - 1];
				let currentWebView = page.$getAppWebview();
				let titleNView = currentWebView.getStyle().titleNView;
				console.log(titleNView, 'titleNView的值')
				currentWebView.setStyle({
					titleNView: false
				})
			} catch (err) {
				this.toast('隐藏导航报错')
			}
		},

		// 显示导航了
		ShowNavBar() {
			try {
				let pages = getCurrentPages();
				let page = pages[pages.length - 1];
				let currentWebView = page.$getAppWebview();
				let titleNView = currentWebView.getStyle().titleNView;
				console.log(titleNView, 'titleNView的值')
				currentWebView.setStyle({
					titleNView: {}
				})
			} catch (err) {
				this.toast('显示导航报错')
			}
		},

		// 活体认证    
		async Camera_Live(config) {
			// 检查相机权限
			// if (!this.CheckCamera()) return;
			const that = this;
			try {
				LF.Face_UP({
					...config
				}, (res) => {
					if (res.code === 1000) {
						const {
							image
						} = res;
						const faceImage = image.replace(/\n/g, '')
						const result = `data:image/png;base64,${faceImage}`;

						UploadFile(config, result).then(file => {
							if (file.statusCode === 200) {
								const faceImgUrl = file.fileUrl;
								// 提交活体检测
								that.GetWebView().evalJS(
									`receiveLiveBack(${JSON.stringify({ fileUrl: faceImgUrl })})`
								)
							} else {
								uni.showToast({
									icon: "success",
									title: "认证失败"
								})
							}
						}).catch(err => {
							uni.showToast({
								icon: 'error',
								title: "认证失败"
							})
						})
					}
				})
			} catch (err) {
				console.log(err, 'LIVE活体识别错误')
			}
		},

		// 活体认证
		async uniFace(config) {
			console.log(config, 'config')
			uni.setStorageSync('userFData', config)
			// 检查相机权限
			// if (!this.CheckCamera()) return;
			const that = this;
			try {
				CheckUniFace((data) => {
					that.GetWebView().evalJS(`receiveUniFace('${JSON.stringify(data)}')`)
				})
			} catch (err) {
				console.log(err, '获取人脸失败')
			}

		},

		// 获取设备信息
		async GetDeviceInfo() {
			try {
				const res = await loadLocation();
				this.GetWebView().evalJS(`receiveGetDeviceInfo('${JSON.stringify(res)}')`)
			} catch (err) {
				console.log(err, '设备信息报错')
				this.GetWebView().evalJS(`receiveGetDeviceInfo('${JSON.stringify(err)}')`)
			}
		},

		// 获取全部通讯录
		GetContacts() {
			const that = this;
			try {
				CheckContactPermission((data) => {
					that.GetWebView().evalJS(`receiveContactsBack('${JSON.stringify(data)}')`)
				})
			} catch (err) {
				console.log(err, '获取全部用户通讯录错误')
			}
		},

		// 通讯录选择
		PickContact() {
			const that = this;
			try {
				CheckContactPermission((data) => {
					SelectContact((contact) => {
						that.GetWebView().evalJS(
							`receivePickContactsBack('${JSON.stringify(contact)}')`)
					})
				})
			} catch (err) {
				console.log(err, '选择用户通讯录错误')
			}
		},

		// 图片选择上传
		PickImage(config) {
			console.log(config, '参数')
			const that = this;
			try {
				uni.chooseImage({
					count: 1,
					sourceType: ["album", "camera"],
					success: (res) => {
						if (res.tempFiles) {
							const file = res.tempFiles[0];
							UploadFile(config, file, true).then(file => {
								if (file.statusCode === 200) {
									const faceImgUrl = file.fileUrl;
									console.log(faceImgUrl, '上传成功后的地址')
									// 提交活体检测
									that.GetWebView().evalJS(`receiveImage(${JSON.stringify({ fileUrl: file.fileUrl })})`
									)
								} else {
									uni.showToast({
										icon: "success",
										title: "上传图片失败"
									})
								}
							}).catch(err => {
								uni.showToast({
									icon: 'error',
									title: "上传图片报错"
								})
							})
						}


					},
					fail: () => {
						console.log('选择图片报错')
					},
				});
			} catch (err) {
				console.log(err, 'H5调用PickImage方法报错')
			}
		},

		// 检查文件和相机权限
		async CheckFileAndCamera() {
			const that = this;
			if (plus.os.name == "iOS") {
				const iosFirstCamera = uni.getStorageSync("iosFirstCamera"); // 是不是第一次开启相机
				if (iosFirstCamera !== "false") {
					uni.setStorageSync("iosFirstCamera", "false"); // 设为false就代表不是第一次开启相机
				} else {
					if (!Permission.judgeIosPermission('camera') || Permission.judgeIosPermission('photoLibrary')) {
						that.GetWebView().evalJS(`receiveCheckFileAndCamera(${JSON.stringify({ flag: "false" })})`);
						return false
					}
				}
			} else {
				const cameraFlag = await Permission.requestAndroidPermission('android.permission.CAMERA');
				const fileFlag = await Permission.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE');
				if (cameraFlag != 1 || fileFlag != 1) {
					that.GetWebView().evalJS(`receiveCheckFileAndCamera(${JSON.stringify({ flag: "false" })})`)
					return false
				}
			}
			that.GetWebView().evalJS(`receiveCheckFileAndCamera(${JSON.stringify({ flag: "true" })})`)
			return true;
		},

		// 检测相机权限
		async CheckCamera() {
			const that = this;
			if (plus.os.name == "iOS") {
				const iosFirstCamera = uni.getStorageSync("iosFirstCamera"); // 是不是第一次开启相机
				if (iosFirstCamera !== "false") {
					uni.setStorageSync("iosFirstCamera", "false"); // 设为false就代表不是第一次开启相机
				} else {
					if (!Permission.judgeIosPermission('camera')) {
						that.GetWebView().evalJS(`receiveCheckCamera(${JSON.stringify({ flag: "false" })})`);
						uni.showModal({
							title: "提示",
							content: "您已经关闭相机权限,去设置",
							success: function (res) {
								if (res.confirm) {
									Permission.gotoAppPermissionSetting();
								}
							},
						});
						return false
					}
				}
			} else {
				const result = await Permission.requestAndroidPermission('android.permission.CAMERA');
				if (result != 1) {
					uni.showModal({
						title: "提示",
						content: "您已经关闭相机权限,去设置",
						success: function (res) {
							if (res.confirm) {
								Permission.gotoAppPermissionSetting();
							}
						}
					})
					that.GetWebView().evalJS(`receiveCheckCamera(${JSON.stringify({ flag: "false" })})`)
					return false
				}
			}
			that.GetWebView().evalJS(`receiveCheckCamera(${JSON.stringify({ flag: "true" })})`)
			return true;
		}
	}
}
</script>

<style lang="less" scoped>
.page-web {
	width: 100vw;
	height: 100vh;

	web-view {
		width: 100%;
		height: 100%;
	}
}
</style>