import store from '../store/index.js'
import {
	getAppBBH
} from "@/api/index.js";
const iosAppStroeUrl =
	'https://apps.apple.com/cn/app/%E6%BB%A1%E5%9B%AD%E6%98%A5%E7%BA%BF%E4%B8%8A%E5%95%86%E5%9F%8E/id1524593346';

// 获取app是否需要升级
export function getUpApp() {
	// 获取当前运行系统
	let hj = uni.getSystemInfoSync().platform;
	// 获取仓库app数据对象
	let app = store.state.isShowIllegality;
	getAppBBH().then((res) => {
		let r = res.data;
		console.log(r, 'rdesedaf');
		plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
			console.log(r,'下载',wgtinfo.versionCode,r.app_version);
			if (+r.app_version > +wgtinfo.versionCode) {
				uni.showModal({
					title: '提示',
					content: '请更新应用',
					showCancel: false,
					success(e) {
						if (hj === 'ios') {
							plus.runtime.openURL(
								iosAppStroeUrl
							);
						}
						if (hj === 'android') {
							// plus.runtime.openURL('http://lxscimg.liuniu946.com/lxscV' + version + '.apk');
							downApp(r.file_url.app_file);
						}
					}
				});
			}
		});

	}).catch((e) => {
		console.log(e);
	})
}
// 下载app
export function downApp(version) {
	console.log(version,'下载地址');
	plus.nativeUI.showWaiting('下载升级包...');
	plus.downloader
		.createDownload(version, {}, (d, status) => {
			console.log(d);
			if (status == 200) {
				console.log('开始安装');
				installApp(d.filename); // 安装app
			} else {
				plus.nativeUI.alert('下载升级包失败！');
			}
			plus.nativeUI.closeWaiting();
		})
		.start();
}
// 安装app
export function installApp(path) {
	console.log(path,'安装');
	plus.nativeUI.showWaiting('安装升级包...');
	plus.runtime.install(
		path, {},
		function() {
			plus.nativeUI.closeWaiting();
			uni.showToast({
				icon: 'none',
				title: '升级完成，准备重新载入'
			});
			setTimeout(_ => {
				uni.hideToast();
				plus.runtime.restart();
			}, 1000);
		},
		function(e) {
			console.log(e,'安装失败');
			plus.nativeUI.closeWaiting();
			plus.nativeUI.alert('安装升级包失败[' + e.code + ']：' + e.message);
		}
	);
}
