<script>
	export default {
		data(){
            return {
                curVersion: 100
            }
        },
		onLaunch: function() {
			//console.log('App Launch')
			// #ifdef APP-PLUS
			// token标志来判断
			let token= uni.getStorageSync('userInfo');
			if (token) {
				//存在则关闭启动页进入首页
				plus.navigator.closeSplashscreen();
			
			} else {				
				//不存在则跳转至登录页
				// uni.reLaunch({
				// 	url: "/pages/login/login",
				// 	success: () => {
				// 		plus.navigator.closeSplashscreen();
				// 	}
				// })
			}
			// #endif
			let baseUrl= uni.getStorageSync('BasrUrl');
			if(baseUrl) {
				uni.setStorage({
					key: 'BasrUrl',
					data: baseUrl
				});
			}
			else {
				uni.setStorage({
					key: 'BasrUrl',
					data: 'http://192.168.150.100:8888'
				});
			}
		},
		onShow: function() {
			this.checkUpdate();
			//console.log('App Show')
		},
		onHide: function() {
			//console.log('App Hide')
		},
		globalData: {
			baseUrl: 'http://192.168.150.100:8888',
			userName: '',
			password: ''
		},
		methods: {
			// 版本升级
			async checkUpdate(){
				// 获取manifest.json 的信息
				plus.runtime.getProperty( plus.runtime.appid, async function ( wgtinfo ) {
					this.curVersion = parseInt(wgtinfo.versionCode);
					// console.log( "this.curVersion:" + this.curVersion );
					let parm = {
						url : '/GetPdaLatestmsg',
						data: {},
						method: 'GET',
						isHaveToken : false
					}
					let retData = await getApp().RequestData(parm)
					if(retData.isSuccess) {
						if(retData.data.code == 200 && parseInt(wgtinfo.versionCode) < retData.data.data.versionNo) {
							uni.showModal({
								title: '版本更新:' + retData.data.data.versionName,
								content: retData.data.data.updateDetails,
								confirmText: "更新",
								showCancel: false,
								success: function(e) {
									if (e.confirm) {
										let baseUrl= uni.getStorageSync('BasrUrl');
										// console.log(baseUrl + '/GetPdaPackage')
										getApp().createDownload(baseUrl + '/GetPdaPackage?fileName=' + retData.data.data.packageName);
									} else {
										//取消
									}
								}
							});
						}
						else {
							uni.showModal({
								title: '提示',
								content: '已是最新版本',
								showCancel: false
							});
						}
					}
					else {
						uni.showModal({
							title: '提示',
							content: '自动更新接口异常！！',
							showCancel: false
						});
					}
				});
			},
			createDownload(url){
                var dtask = plus.downloader.createDownload(url, {},
                    function(d, status) {
                        uni.showToast({
                            title: '下载完成',
                            mask: false,
                            duration: 1000
                        });
                        //console.log(dtask);
                        // 下载完成
                        // console.log('status: '+status);
                        if (status == 200) {
                            // console.log('下载成功：'+d.filename);
                            // console.log('plus.io.convertLocalFileSystemURL(d.filename): '+plus.io.convertLocalFileSystemURL(d.filename))
                            plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, function(success) {
                                uni.showToast({
                                    title: '安装成功',
                                    mask: false,
                                    duration: 1500
                                });
                            }, function(error) {
                                uni.showToast({
                                    title: '安装失败-01',
                                    mask: false,
                                    duration: 1500
                                });
                            })
                        } else {
                            uni.showToast({
                                title: '更新失败-02',
                                mask: false,
                                duration: 1500
                            });
                        }
                });
                try {
                    dtask.start(); // 开启下载的任务
                    var prg = 0;
                    var showLoading = plus.nativeUI.showWaiting("正在下载");  //创建一个showWaiting对象 
                    dtask.addEventListener('statechanged', function(task,status) {
                        // 给下载任务设置一个监听 并根据状态  做操作
                        switch (task.state) {
                            case 1:
                                showLoading.setTitle("正在下载");
                                break;
                            case 2:
                                showLoading.setTitle("已连接到服务器");
                                break;
                            case 3:
                                prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100 );
                                showLoading.setTitle("  正在下载" + prg + "%  ");
                                break;
                            case 4:
                                plus.nativeUI.closeWaiting();
                                //下载完成
                                break;
                        }
                    });
				} 
				catch (err) {
                    plus.nativeUI.closeWaiting();
                    uni.showToast({
                        title: '更新失败-03',
                        mask: false,
                        duration: 1500
                    });
                }
            },
			AppExit() {
				uni.showModal({
					//计算删除的数量
					title: '提示',
					content: '是否要退出应用?', //文章内容
					cancelText: '取消', //取消按钮的文字
					confirmText: '确定', //确定文本的文字
					cancelColor: '#007aff', //取消按钮文本颜色
					confirmColor: '#007aff', //确定按钮文本颜色
					success: function(res) {
						if (res.confirm) {
							//console.log('用户点击了确定')
							let userMsg = uni.getStorageSync('userInfo')
							if(userMsg) {
								let baseUrlStr = uni.getStorageSync('BasrUrl')
								uni.request({
									url: baseUrlStr + '/logout',
									//自定义请求头信息
									header: {
										Authorization: 'Bearer ' + userMsg.tokenStr + '',
										'content-type': 'application/json'
									},
									method: 'POST',
								})
								 //指定移除登录后缓存的user用户信息
								uni.removeStorage({
									key: 'userInfo',
									success: function(res) {
										//console.log('清空了用户缓存信息', );
										uni.showToast({
											title: '退出应用成功',
											icon: 'success',
											duration: 500
										})
									}
								})
							}
							setTimeout(() => {
								// main.finish();
								plus.runtime.quit();
							}, 600)
						} else if (res.cancel) {
							//console.log('用户点击了取消')
						}
					}
				})
			},
			RequestData(parm) {
				return new Promise((resolve,reject) => {
					let userMsg = uni.getStorageSync('userInfo')
					let baseUrlStr = uni.getStorageSync('BasrUrl')
					// console.log(parm.data)
					uni.request({
					    url: baseUrlStr + parm.url,
					    data: parm.data,
					    header: { //自定义请求头信息
							Authorization: parm.isHaveToken? 'Bearer ' + userMsg.tokenStr + '' : '',
					        'content-type': 'application/json'
					    },
						timeout: 20000,
						method: parm.method,
					    success: (res) => {
							resolve({
								isSuccess : true,
								data : res.data,
								retMsg : '请求成功！'
							})
					    },
						fail: (res) => {
							reject({
								isSuccess : false,
								data : {},
								retMsg : '请求失败！' + res.errMsg
							})
						}
					});
				})
			}
		}
	}
</script>

<style>
	/* #ifndef APP-PLUS-NVUE */
	/* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
	@import './common/uni.css';
	@import '@/static/customicons.css';
	/* H5 兼容 pc 所需 */
	/* #ifdef H5 */
	@media screen and (min-width: 768px) {
		body {
			overflow-y: scroll;
		}
	}

	/* 顶栏通栏样式 */
	/* .uni-top-window {
	    left: 0;
	    right: 0;
	} */

	uni-page-body {
		background-color: #F5F5F5 !important;
		min-height: 100% !important;
		height: auto !important;
	}

	.uni-top-window uni-tabbar .uni-tabbar {
		background-color: #fff !important;
	}

	.uni-app--showleftwindow .hideOnPc {
		display: none !important;
	}

	/* #endif */

	/* 以下样式用于 hello uni-app 演示所需 */
	page {
		background-color: #efeff4;
		height: 100%;
		font-size: 28rpx;
		/* line-height: 1.8; */
	}

	.fix-pc-padding {
		padding: 0 50px;
	}

	.uni-header-logo {
		padding: 30rpx;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-top: 10rpx;
	}

	.uni-header-image {
		width: 100px;
		height: 100px;
	}

	.uni-hello-text {
		color: #7A7E83;
	}

	.uni-hello-addfile {
		text-align: center;
		line-height: 300rpx;
		background: #FFF;
		padding: 50rpx;
		margin-top: 10px;
		font-size: 38rpx;
		color: #808080;
	}

	/* #endif*/
</style>
