<template>
	<common-layout :bgColor="themeStore.theme.startColor">
		<!-- <view class="w-full relative" style="height: 100vh;overflow: hidden;"> -->
		<StartLoading :visible="true" />
		<!-- #ifdef APP-PLUS -->
		<view class="progress" v-if="showProgress">
			<progress :percent="appStore.progress" activeColor="#ffffff" backgroundColor="#400105"></progress>
			<view style="text-align: center;margin-top: 10rpx;">Loading...</view>
		</view>
		<Download ref="downloadRef" @close="handleClose" @confirm="handleConfirm" />
		<!-- #endif -->
		<!-- </view> -->
	</common-layout>
</template>

<script setup>
import { computed, ref } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import StartLoading from "@/components/loading/StartLoading.vue"
import { useUserStore } from "@/store/useUserStore"
import { useAppStore } from "@/store/useAppStore"
// import { getAdjustAdid } from '@/module/third/adjust.js'
import { requestJiliLogout } from '@/api/game.js'
import { requestAppFbparams } from "@/api/app"
import { usePromoStore } from "@/store/usePromoStore"
import Download from "@/components/popup/Download.vue"
// #ifdef APP-PLUS
import { getAdid } from "@/module/utils/util"
import { getAndroidId } from "@/uni_modules/x-uniq-id"
// #endif
import md5 from "crypto-js/md5"
import { getFbInfoApi } from "@/api/account"
import { useThemeStore } from "@/store/useThemeStore"

const themeStore = useThemeStore()
const userStore = useUserStore()
const appStore = useAppStore()
const downloadRef = ref(null)
const showProgress = ref(false)
onLoad(async () => {
	console.log('index onLoad');

	uni.setNavigationBarTitle({
		title: `${appStore.appName}`
	})
	// #ifdef APP-PLUS
	try {
		await appStore.getAppUpdate()
	} catch (error) {
		console.log("err:", error);
	}

	if (appStore.updateReady) {
		console.log("updateReady");

		if (appStore.updateData.updateType === 2) {
			showProgress.value = true
			await handleDownloadAndUpdate()
			initData()
		}
		if (appStore.updateData.updateType === 1 && appStore.updateData.downloadUrl.endsWith('.apk')) {
			downloadRef.value.open()
			return
		}
	}

	// #endif
	initData()
	//包名+广告ID
})
const handleClose = () => {
	initData()
}
const handleConfirm = async () => {
	// showProgress.value = true
	// await handleDownloadAndUpdate()
	plus.runtime.openURL(appStore.updateData.downloadUrl)
	initData()
}
const handleDownloadAndUpdate = () => {
	return new Promise((resolve, reject) => {
		const dwTask = uni.downloadFile({
			url: appStore.updateData.downloadUrl,
			success: (dwResult) => {
				console.log("tempFilePath:", dwResult.tempFilePath)
				if (dwResult.statusCode === 200) {
					plus.runtime.install(dwResult.tempFilePath, { force: false },
						function () {
							console.log("installed")
							appStore.setUpdateReady(false)
							appStore.updateData = {}
							plus.runtime.restart();
							resolve()
						},
						function (e) {
							console.error('install fail...', e);
							appStore.setUpdateReady(false)
							resolve()
						}
					);
				}
			},
			fail(err) {
				console.log("download err:", err)
				reject()
			}
		});
		dwTask.onProgressUpdate((res) => {
			console.log('dwTask.onProgressUpdate', res.progress);
			appStore.setProgress(res.progress)
		});
	})

}

const initData = async () => {
	uni.preloadPage({
		url: '/pages/home/Home'
	})
	console.log("init", appStore.androidId);

	// #ifdef APP-PLUS
	if (!appStore.androidId) {
		console.log("init");
		const systemInfo = uni.getSystemInfoSync()
		const deviceInfo = uni.getStorageSync('DEVICE_INFO')
		if (!deviceInfo) {
			let s = ''
			try {
				const gaid = await getAdid()
				console.log("gaid:", gaid)
				appStore.androidId = gaid
				s = 'g_'
			} catch (error) {
				appStore.androidId = getAndroidId()
				s = 'a_'
				if(!appStore.androidId){
					appStore.androidId = systemInfo.deviceId
				}
			}
			console.log("androidId:", appStore.androidId)
			appStore.deviceId = s + md5(appStore.packageName + appStore.androidId).toString()
			uni.setStorageSync('DEVICE_INFO', JSON.stringify({ androidId: appStore.androidId, s }))
		} else {
			const info = JSON.parse(deviceInfo)
			appStore.androidId = info.androidId
			appStore.deviceId = info.s + md5(appStore.packageName + appStore.androidId).toString()
		}
	}
	// #endif
	console.log('isLogin', userStore.isLogin);
	const { data } = await getFbInfoApi()
	if (data?.name) {
		appStore.channelId = data?.name
	}
	if (data?.pixelH5) {
		appStore.h5No = data?.pixelH5
	}

	if (userStore.isLogin) {
		// await userStore.getUserTotalInfo()
		// await getAdjustAdid()
		if (appStore.fbc || appStore.fbp) {
			await requestAppFbparams({ fbc: appStore.fbc, fbp: appStore.fbp, uniKey: appStore.uniKey })
		}
		await userStore.guestLogin()
		await userStore.getAgentInfoV2()
		await usePromoStore().getPromoList()
		handleFinishInit()

	} else {
		// await getAdjustAdid()
		if (appStore.fbc || appStore.fbp) {
			await requestAppFbparams({ fbc: appStore.fbc, fbp: appStore.fbp, uniKey: appStore.uniKey })
		}
		try {

			await userStore.guestLogin()
			await userStore.getAgentInfoV2()
			await usePromoStore().getPromoList()
			handleFinishInit()
		} catch (error) {
			console.log(error);
		}

	}
}

const handleFinishInit = () => {
	userStore.startReportOnline()
	requestJiliLogout();
	console.log('finish init');

	setTimeout(() => {
		uni.switchTab({
			url: '/pages/home/Home'
		})
	}, 100)
}
</script>

<style lang="scss" scoped>
.progress {
	position: absolute;
	bottom: 80rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 60%;
	z-index: 100000;
	font-size: 12px;
	color: #ffffff;
}
</style>