import { http } from '@/utils/request';

export default function () {
	// #ifdef APP
	return new Promise((resolve, reject) => {
		const systemInfo = uni.getSystemInfoSync();
		const appId = systemInfo.appId;
		const appVersion = systemInfo.appVersion; //systemInfo.appVersion
		if (typeof appId === 'string' && typeof appVersion === 'string' && appId.length > 0 && appVersion.length > 0) {
			plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {

				if (widgetInfo.version) {
					let data = {
						appVersion: appVersion,
						wgtVersion: widgetInfo.version
					};
					http.get('/latest-app-versions').then(resData => {
					
						// _id : string
						// appid : string
						// name : string
						// title : string
						// contents : string
						// url : string // 安装包下载地址
						// platform : Array<string> // Array<'Android' | 'iOS'>
						// version : string // 版本号 1.0.0
						// uni_platform : string // "android" | "ios" // 版本号 1.0.0
						// stable_publish : boolean // 是否是稳定版
						// is_mandatory : boolean // 是否强制更新
						// is_silently : boolean | null	// 是否静默更新
						// create_env : string // "upgrade-center"
						// create_date : number
						// message : string
						// code : number

						// type : string // "native_app" | "wgt"
						// store_list : StoreListItem[] | null
						// min_uni_version : string | null  // 升级 wgt 的最低 uni-app 版本

						const info = resData[systemInfo.platform];
						const appVersionCode = import.meta.env.VITE_APP_VERSION_CODE;
						let resInfo = null
						if (info == null || appVersionCode >= info?.version) {
							resInfo = {
								code: 0
							}
						} else {
							resInfo = {
								name: info.name,
								title: info.title,
								contents: info.description,
								url: info.update_strategy === 'wgt' ? info.wgt_url : info.apk_url,
								platform: [systemInfo.platform],
								version: info.version,
								uni_platform: systemInfo.platform,
								stable_publish: true,
								is_mandatory: info.is_force,
								is_silently: false,
								type: info.update_strategy,
								code: info.update_strategy === 'wgt' ? 101 : 102
							}
						}
						resolve(resInfo);
					}).catch(err => {
						reject(err);
					})
				}
				else {
					reject('widgetInfo.version is EMPTY');
				}
			});
		}
		else {
			reject('plus.runtime.appid is EMPTY');
		}
	});
	// #endif
	// #ifndef APP
	return new Promise((resolve, reject) => {
		reject({
			message: '请在App中使用'
		});
	});
	// #endif
}
