<template>
	<view class="m-shade n-flex-1 n-align-center n-justify-center">
		<view :style="{width:'580rpx'}">
			<image src="/static/image/upgrade.png" mode="widthFix"></image>
			<view class="n-ps-all-ll n-ms-top-ll n-position-absolute">
				<text class="n-size-mm n-weight-7 n-color-inverse">发现新版本</text>
				<text class="n-size-base n-ms-top-ss n-color-inverse">V{{model.version}}</text>
			</view>
			<view class="n-ps-all-l n-radius-lb-base" :style="{backgroundColor:'#f3f3f3',borderRadius:'0 0 16rpx 16rpx'}">
				<view :style="{height:'300rpx'}">
					<scroll-view class="n-flex-1" :show-scrollbar="false" scroll-y>
						 <rich-text class="n-size-s" :nodes="model.content" :style="{lineHeight:'26rpx'}"></rich-text>
					</scroll-view>
				</view>
				<view class="n-height-base n-justify-center">
					<view v-if="progress">
						<uv-line-progress :percentage="value" activeColor="#fc3463"></uv-line-progress>
					</view>
					<view class="n-flex-row" v-else>
						<uv-button class="n-flex-1 n-ms-right-ll" v-if="model.force==0" @click="cancel" :customStyle="{backgroundColor:'#f3f3f3'}" text="暂不更新" color="#fc3463" shape="circle" throttleTime="1000" plain></uv-button>
						<uv-button class="n-flex-1" @click="upgrade" text="立即更新" color="#fc3463" shape="circle" throttleTime="1000"></uv-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				value: 0,
				model: {
					force: 1,
					version: '1.0.0',
					content: ''
				},
				progress: false,
				download: false
			}
		},
		onLoad(evt) {
			if(evt.model){
				this.model = {...this.model, ...JSON.parse(evt.model)}
			}
		},
		onBackPress() {
			if(this.model.force==1){
				return true
			}
		},
		methods: {
			// 取消更新
			cancel() {
				uni.navigateBack()
				uni.setStorageSync('skip_version', this.model.version)
			},
			// 立即更新
			upgrade(){
				// 检测更新方式
				if(this.model.type==0 || this.model.type==1){
					this.downloadUpdate()
				}else{
					plus.runtime.openURL(this.model.source_text)
				}
			},
			// 下载更新
			downloadUpdate() {
				if(!this.download){
					this.progress = true
					this.download = true
					// 下载安装包
					const download = uni.downloadFile({
						url: this.model.source_text,
						success: result=>{
							// 自动安装软件
							plus.runtime.install(result.tempFilePath, {force:true}, ()=>{
								// 防止强制更新无法关闭界面
								this.model.force = 0
								if(this.model.type==1){
									uni.showToast({
										title:'更新成功，软件重启'
									})
									setTimeout(()=>{ plus.runtime.restart() }, 1500)
								}
							})
						},
						fail: error=>{
							uni.showToast({
								title:'下载失败，请检查您的网络情况'
							})
						}
					})
					// 监听下载进度
					download.onProgressUpdate(result=>{
						this.value = result.progress
					})
				}
			}
		}
	}
</script>

<style>
	.m-shade{
		background-color: rgba(0, 0, 0, 0.1);
	}
</style>
