<template>
	<view :class="[AppTheme]">
		<view class="download">
			<uni-popup ref="popup" type="center">
				<view class="upgrade">
					<view class="logo">
						<image src="./static/upgrade.png" mode="widthFix" />
					</view>
					<view class="content">
						<view class="title">
							<text>{{ upgrading ? '正在升级' : '发现新版本' + versionStr }}</text>
						</view>
						<view class="container">
							<view class="descriptions">
								<text>{{ upgrading ? '正在为您下载,请耐心等待' : '本次版本更新描述内容:' }}</text>
							</view>
							<view class="details" v-if="!upgrading">
								<view class="item">
									<u-parse :content="versions_desc"></u-parse>
								</view>
							</view>
							<view v-else class="prpgroess"><progress :percent="downloadTime" active-mode="forwards"
									activeColor="red" active stroke-width="4" show-info /></view>
						</view>
						<view v-if="!upgrading" class="btn-group">
							<view class="cancel" @click="hiddenUppop"><text>取 消</text></view>
							<view class="confirm bg-primary" @click="upgradeEvent"><text>确 定</text></view>
						</view>
						<view v-else class="btn-group">
							<view v-if="!isForceUpgrade" class="cancel" @click="abortDownload"><text>取消下载</text></view>
							<view v-if="!isForceUpgrade" class="confirm bg-primary" @click="hiddenUpgradeEvent">
								<text>后台下载</text>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import Vue from 'vue';
	import uniPopup from './uni-popup/uni-popup.vue';
	import uniPopupMessage from './uni-popup/uni-popup-message.vue';
	import uniPopupDialog from './uni-popup/uni-popup-dialog.vue';
	import update from "@/api/update/index.js"
	export default {
		props: {
			isUpdate: false
		},
		data: () => ({
			tempFilePaths: '',
			// 版本代码
			versionCode: 28,
			// 版本字符串
			versionStr: '1.0.0530',
			// 是否更新
			upgrading: false,
			// 下载时间
			downloadTime: 0,
			// 定时器
			timer: null,
			// 是否强制更新
			isForceUpgrade: false,
			// 下载任务
			downloadTask: null,
			// 下载地址
			downloadUrl: '',
			//版本更新内容
			versions_desc: '系统优化已知问题',
			settingFile: getApp().globalData.siteinfo,
		}),
		// 使用的组件
		components: {
			uniPopup,
			uniPopupMessage,
			uniPopupDialog
		},
		mounted() {
			let _this = this;
			_this.init(_this.isUpdate)
		},
		methods: {
			init(_isUpdate, fun) {
				let _this = this;
				const res = uni.getSystemInfoSync();
				if (res.platform == 'android') {
					let _this = this;
					if (_isUpdate) {
						update.download_link({
								platform: 'android'
							}).then(res => {
								if (res.status == 1) {
									plus.runtime.getProperty(plus.runtime.appid, function(inf) {
										if (inf.version !== res.data.version_number) {
											_this.$refs.popup.open();
											_this.downloadUrl = res.data.link;
											_this.versionStr = res.data.version_number;
											_this.versions_desc = res.data.content
											_this.versions_desc = _this.versions_desc.replace(/\<img src="/gi,
												`<img style='width:100%;display:block' src="${_this.settingFile.root_rich_img}`
											);
										} else {
											if (fun) {
												fun();
											}
										}
									});
								}
							})
							.catch(error => {
								console.log(error, "失败了")
							});
					}
				} else if (res.platform == 'ios') {}

			},
			// 取消更新
			hiddenUppop() {
				this.$store.commit('changeUpdate', false);
				this.$refs.popup.close();
			},
			// 检测更新
			upgrade() {
				let _this = this;
				_this.init(true, function() {
					uni.showToast({
						title: '恭喜您的应用是最新版本!',
						duration: 2000,
						icon: 'none'
					});
				})
			},
			// 点击更新
			upgradeEvent() {
				this.$store.commit('changeUpdate', false);
				if (!this.upgrading) {
					let versionInfo = this.getVersionAndPlatform();
					// 如果是正式更新需要打开下面这行注释
					// 这里只是做了简单的判断
					// 这里可以更据平台来下载
					// -------------------------
					console.log('versionInfo',versionInfo)
					if (versionInfo) {
						this.upgrading = true;
						// 如果是强制更新
						this.isForceUpgrade = true;
						// 正式下载请打开这里的注释
						this.downloadApplications();
					}
					// -----------------------
				}
			},
			// 后台下载
			hiddenUpgradeEvent() {
				this.$store.commit('changeUpdate', false);
				this.$refs.popup.close();
			},
			// 检测平台和当前app版本号
			getVersionAndPlatform() {
				// 这里try-catch是因为，当前代码是在浏览器上调试的
				// 由于浏览器不支持所以加了try-catch
				// 你也可以加这个玩意
				// #ifdef APP-PLUS

				// #endif
				// 你可以删除
				try {
					// 获取版本号
					let version = plus.runtime.version;
					// 获取当前平台
					// - Android
					// - Ios
					// 两种平台
					let platform = plus.os.name;
					return {
						version: version,
						platform: platform
					};
				} catch {
					console.error('当前平台不支持5+SDK!');
				}
			},
			// 下载
			downloadApplications() {
				let that = this;
				// 建立下载任务
				that.downloadTask = uni.downloadFile({
					// 下载地址
					url: that.downloadUrl,
					success: res => {
						console.log('res',res)
						if (res.statusCode === 200) {
							// 把当前app保存下载
							let tempFilePaths = res.tempFilePath
							uni.saveFile({
								tempFilePath: tempFilePaths,
								success: resp => {
									// 保存成功
									var savedFilePath = resp.savedFilePath;
									const installPath = plus.io.convertLocalFileSystemURL(
										savedFilePath);
									// 安装
									that.installApplications({
										filePath: installPath,
										success: res => {
											that.$store.commit('changeUpdate', false);
											that.$refs.popup.close();
											plus.nativeUI.alert("应用资源更新完成！",
												function() {
													plus.runtime.restart();
												});
										},
										error: err => {
											that.$refs.popup.close();
											that.upgrading = false;
											that.$api.msg(err);
										}
									});
								},
								fail: err => {
									// 保存失败
									that.upgrading = false;
									that.$refs.popup.close();
									that.$api.msg(err);
								}
							});
						}
					}
				});

				that.downloadTask.onProgressUpdate(res => {
					// 下载进度
					that.downloadTime = res.progress;
				});
			},
			// 取消下载
			abortDownload() {
				let that = this;
				that.downloadTime = 0;
				if (that.$refs.popup) {
					that.$refs.popup.close();
					setTimeout(() => {
						that.upgrading = false;
					}, 200)
				}
				clearInterval(that.timer);
				if (that.downloadTask) {
					that.downloadTask.abort();
				}
			},
			//安装
			installApplications({
				filePath,
				success,
				error
			}) {
				let that = this;
				plus.runtime.install(filePath, {
					force: that.isForceUpgrade
				}, success, error);
			}
		},
		computed: {},
		watch: {}
	};
</script>

<style>
	.scroll-view_H {
		hight: 400rpx;
	}

	.download .logo {
		width: 208rpx;
	}

	.cancel {
		background-color: #cbcbcb;
	}

	.download .upgrade {
		position: relative;
		background: #fff;
		width: 680rpx;
		min-height: 400rpx;
		border-radius: 20rpx;
	}

	.download .logo image {
		width: 208rpx;
		position: absolute;
		top: -80rpx;
		left: 0;
		right: 0;
		margin: 0 auto;
	}

	.download .content {
		padding-top: 80rpx;
	}

	.download .content .title {
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
	}

	.download .content .container {
		color: #666;
		overflow-y: scroll;
		min-height: 200rpx;
	}

	.download .content .container .descriptions {
		padding: 15rpx 30rpx;
		text-align: center;
		font-size: 28rpx;
	}

	.download .content .container .details {
		/* max-height:300rpx; */
		/* overflow: auto; */
		/* word-wrap:break-word; */
	}

	,
	.download .content .container .details .item {
		padding: 20rpx;
		max-height: 500rpx;
		overflow-y: scroll;
		font-size: 30rpx;
	}

	,
	.download .content .prpgroess {
		padding: 16rpx 46rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}

	.download .content .prpgroess {
		padding: 16rpx 22rpx;
		margin: 20rpx 0;
	}

	.download .content .btn-group {
		display: flex;
		justify-content: center;
		align-items: center;
		padding-bottom: 25rpx;
	}

	.download .content .btn-group view {
		width: 200rpx;
		height: 70rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 14rpx;
		font-size: 28rpx;
		border-radius: 42rpx;
		line-height: 70rpx;
	}

	.download .content .btn-group view:last-child {
		/* 		background: #ef5656; */
		color: #fff;
	}
</style>
