<template>
	<view>
		<web-view src="http://61.177.40.178:8001" @message="handleMessage" id="myWebview"></web-view>
		<!-- <web-view src="http://192.168.0.138:3200" @message="handleMessage" id="myWebview"></web-view> -->
		<!-- <web-view src="http://120.192.74.74:7501" @message="handleMessage" id="myWebview"></web-view> -->
		<!-- <button @click="downloadFile">点击下载文件</button> -->

	</view>
</template>
<!--  -->
<!-- <script src="../../js/uni-webview"></script> -->
<script>
	export default {
		data() {
			return {

			}
		},


		onReady() {

		},

		onLaunch() {
			// uni.onPushMessage((res)=>{
			// 	console.log('8888',res);
			// })
		},


		onLoad: function() {
			// this.currentWebView = plus.webview.currentWebview();
			// console.log('5555',this.currentWebView);

			// this.handleMessage();
			// this.downloadFile();
		},
		methods: {

			handleMessage(evt) {
				console.log('原始信息:' + evt)
				console.log('接收到的消息：' + JSON.stringify(evt));
				if (evt) {
					// let data={};
					let data = JSON.parse(evt.detail.data);
					console.log('json解析：' + JSON.stringify(data));
					if (data && data.content && data.title && data.content != '' && data.title != '') {
						uni.createPushMessage({
							content: data.content, // 推送内容
							title: data.title, // 推送标题
							sound: "system",
							success: function(res) {
								console.log('推送成功', res);
							},
							fail: function(err) {
								console.log('推送失败', err);
							}
						});
					} else if (data && data.type && data.type == 'file' && data.url && data.url != '' && data.fileName &&
						data.fileName != '' && data.token && data.token != '') {
						//判断是否为post请求
						let isPost = false;
						try {
							let urlType = data.urlType;
							let postRequest = data.postRequest;
							if (urlType == 'POST') {
								isPost = true;
							}
						} catch (e) {
							isPost = false;
						}

						let url = data.url;
						let fileName = data.fileName;
						let token = data.token;
						if (!isPost) {
							console.log("移动端文件下载通用方式")
							console.log('url:' + url);
							this.downloadFile(url, fileName, token);
						} else {
							let postRequest = data.postRequest;
							this.downloadPostFile(url, fileName, token, postRequest)
						}
					} else if (data && data.type && data.type == 'scanCode') {
						this.currentWebView = plus.webview.currentWebview();
						console.log('66666', this.currentWebView);
						this.scancode();

					} else {
						return;
					}

				}
			},
			// downloadFile(url) {
			// 	uni.downloadFile({
			// 		url: url,
			// 		success: function(res) {
			// 			if (res.statusCode === 200) {
			// 				console.log('下载成功:' + JSON.stringify(res));
			// 				uni.saveFile({
			// 					tempFilePath: res.tempFilePath,
			// 					success: function(res) {
			// 						var savedFilePath = res.savedFilePath;
			// 						console.log("download:" + savedFilePath)
			// 						uni.openDocument({
			// 							filePath: savedFilePath
			// 						});
			// 					}
			// 				});
			// 			}
			// 		} 
			// 	});
			// },
			scancode() {
				uni.scanCode({
					scanType: ['qrCode'],
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						// let result=JSON.stringify(res.result)
						plus.webview.getDisplayWebview()[0].evalJS(`window.postJS(${res.result})`)
					},

				});

				// uni.postMessage({
				// 	data:{
				// 		title:'555555'
				// 	}
				// })
			},

			downloadFile(_url, _name, _token) {

				uni.downloadFile({
					url: _url, //文件链接
					header: {
						"token": _token
					},
					success: (res) => {
						if (res.statusCode === 200) {
							console.log("res:", res)
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(res) {
									var savedFilePath = res.savedFilePath;
									let lastSlashIndex = savedFilePath.lastIndexOf("/");
									let name_index = _name.lastIndexOf('.');
									let fileName = _name.slice(0, name_index) + Date.now() + _name
										.slice(name_index, _name.length)
									var newFilePath = savedFilePath.slice(0, lastSlashIndex + 1) +
										fileName;
									console.log("download:" + savedFilePath)
									console.log('修改之后的文件路径：' + newFilePath)
									//修改名称

									plus.io.resolveLocalFileSystemURL(savedFilePath, entry => {
										entry.getParent(_oldFile => {
											entry.moveTo(_oldFile, '/' + fileName,
												newFilePath => {
													console.log('文件名称替换完成');
													// console.log('000',newFilePath.fullPath);
												})
										})
									})
									setTimeout(() => {
										uni.openDocument({
											filePath: newFilePath,
											success() {
												console.log('打开成功');
											},
											fail() {
												console.log('打开失败');
											}
										});
									}, 1000)
								}
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '失败请重新下载',
						});
					},
				})
			},

			downloadPostFile(_url, _name, _token, _data) {
				let name_index = _name.lastIndexOf('.');
				let fileName = "_doc/uniapp_save/" + _name.slice(0, name_index) + Date.now() + _name
					.slice(name_index, _name.length);
				console.log('文件路径:' + fileName)

				var dtask = plus.downloader.createDownload(_url, {
					filename: fileName, //利用保存路径，实现下载文件的重命名
					method: 'POST',
					data: _data
				}, function(d, status) {
					console.log("d====>", d)
					console.log("status====>", status)
					//d为下载的文件对象
					if (status == 200) {
						// var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
						plus.runtime.openFile(d.filename); //选择软件打开文件
					} else {
						//下载失败
						plus.downloader.clear(); //清除下载任务
						reject({
							data: d,
							status
						})
					}
				})

				dtask.setRequestHeader("token", _token)
				dtask.setRequestHeader("Content-Type", "application/json")
				dtask.start(); //执行下载

			},

		}
	}
</script>

<style>

</style>