<script>
	import {
		config
	} from '@/common/config.js';
	export default {
		data() {
			return {
				downloadUrl: ''
			}
		},
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
			this.getDownloadUrl();
		},
		methods: {
			/**
			 * 通过参数设置获取最新版本信息
			 */
			getVersion() {
				uni.$u.api.getParameterApi({
					key: 'parking.operation.version'
				}).then(res => {
					if (res.code === 200) {
						if (res.msg !== config.version) {
							uni.showModal({
								title: '版本发布更新',
								content: '发现新版本，请进行更新',
								confirmText: '更新',
								confirmColor: '#EE8F57',
								success: (res) => {
									if (res.confirm) {
										this.downloadAppFile();
									}
								}
							})
						}
					}
				})
			},
			/**
			 * 通过参数设置获取最新下载链接
			 */
			getDownloadUrl() {
				uni.$u.api.getParameterApi({
					key: 'parking.operation.package'
				}).then(res => {
					if (res.code === 200) {
						this.downloadUrl = res?.msg
						uni.getSystemInfo({
							success: (res) => {
								this.getVersion();
							}
						})
					}
				})
			},
			/**
			 * 下载文件
			 */
			downloadAppFile() {
				uni.showLoading({
					title: '下载中',
				})
				let downloadTask = uni.downloadFile({ // 执行下载
					url: this.downloadUrl,
					success: downloadResult => {
						// 下载成功
						if (downloadResult.statusCode === 200) {
							uni.showModal({
								title: '',
								content: '下载成功，确定现在更新吗？',
								confirmText: '更新',
								confirmColor: '#EE8F57',
								success: function(res) {
									if (res.confirm) {
										plus.runtime.install( //安装
											downloadResult.tempFilePath, {
												force: true
											},
											function() {
												plus.runtime.restart();
												uni.navigateBack()
											},
											function(e) {
												utils.showToast('更新失败');
											}
										);
									}
								}
							});
						}
					},
					complete: (res) => {
						uni.hideLoading();
					}
				});
				downloadTask.onProgressUpdate((res) => {
					if (res.progress === 100) {
						uni.hideLoading();
					}
				});
			}
		},
		onHide: function() {
			console.log('App Hide')
		},
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	/*每个页面公共css */
	@import "@/uni_modules/uview-ui/index.scss";
</style>
