import {
	reactive,
	toRefs
} from 'vue'
import {
	defineStore
} from 'pinia'
import {
	upDateAppApi
} from '@/api/api.js'
import {
	hasNewVersion,
	onClickUpdate
} from '@/utils/index.js';
const baseUrl = import.meta.env.VITE_REQUEST_BASE_URL + '/jeecg-boot/sys/common/static/' 

export const useUpdateApp = defineStore('updateApp', () => {
	const updateOptions = reactive({
		force: false,
		hasNew: false,
		content: '',
		url: '',
		wgtUrl: ''
	})
	const systemInfo = uni.getSystemInfoSync()

	/**
	 * 当前处于APP_PLUS时 检查是否有新版本
	 * 
	 * @param to 是否跳转新页面显示更新 默认值false
	 */
	function checkAppUpdate(to = false) {
		try {
			upDateAppApi().then(async (res) => {
				let {
					result
				} = res
				result.apkUrl = baseUrl + result.apkUrl;
				result.wgtUrl = baseUrl + result.wgtUrl
				// updateOptions.force = res.is_force === 1
				// updateOptions.content = res.update_content
				updateOptions.wgtUrl = result.wgtUrl
				if (systemInfo.osName === 'android') {
					// Android
					updateOptions.apkUrl = result.apkUrl
					// #ifdef APP_PLUS
					updateOptions.hasNew = await hasNewVersion(result.versionCode, result.update ==
						'wgt')
					// #endif
				} else {
					// IOS
					updateOptions.url = `itms-apps://itunes.apple.com/cn/app/id${123456}?mt=8`

				}
				updateOptions.hasNew &&
					uni.showModal({
						title: '更新',
						content: '发现新版本，请更新',
						success(res) {
							if (res.confirm) {
								onClickUpdate(result.update, result)
							}else{
								plus.runtime.quit()
							}
						}
					})
			})
		} catch (error) {
			updateOptions.hasNew = false
		}
	}

	return {
		checkAppUpdate,
		...toRefs(updateOptions),
		systemInfo
	}
})