import store from '../store/index.js'
// const getUpAppUrl = 'https://itunes.apple.com/cn/lookup?id=1524593346'
const getUpAppUrl = store.state.baseURL + '/api/version'
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';

function compareVersions(version1, version2) {
    const v1 = version1.split('.');
    const v2 = version2.split('.');
    
    for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
        const num1 = parseInt(v1[i] || 0);
        const num2 = parseInt(v2[i] || 0);
        
        if (num1 < num2) {
            return -1;
        } else if (num1 > num2) {
            return 1;
        }
    }
    
    return 0;
}

// 获取app是否需要升级
export function getUpApp () {
	// 获取当前运行系统
	let hj = uni.getSystemInfoSync().platform;
	// 获取仓库app数据对象
	let app = store.state.isShowIllegality;
	// 当前系统为安卓则显示数据
	if (hj === 'android') {
		// 设置默认显示数据
		app = true;
		// store.commit('changeState', {
		// 	name: 'app',
		// 	value: app
		// });
	}
	uni.request({
		url: getUpAppUrl,
		method: 'GET',
		data: {},
		success: res => {
			let r = res.data.data;
			plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
				// 保存线上版本号
				//{"app_down":"www.baidu.com","app_version":"1.0.1"} ,  app
				let version = r.app_down;
				// 获取线上版本
				const arr = r.app_version.split('.');
				console.log(arr,'app_version');
				// 获取当前系统
				const arr1 = wgtinfo.version.split('.');
				
				if(compareVersions(wgtinfo.version,r.app_version) < 0) {
					if (hj === 'android') {
						uni.navigateTo({
							url:'/pages/index/upApp?downurl=' + version
						})
					}
				}
			});
		},
	});
}
// 下载app
export function downApp (version) {
	plus.nativeUI.showWaiting('下载升级包...');
	plus.downloader
		.createDownload('http://lxscimg.liuniu946.com/lxscV' + version + '.apk', {}, (d, status) => {
			if (status == 200) {
				installApp(d.filename); // 安装app
			} else {
				plus.nativeUI.alert('下载升级包失败!');
			}
			plus.nativeUI.closeWaiting();
		})
		.start();
}
// 安装app
export function installApp (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) {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.alert('安装升级包失败[' + e.code + ']:' + e.message);
		}
	);
}