<script lang="uts">
	// #ifdef APP-ANDROID || APP-HARMONY
	let firstBackTime = 0
	// #endif
import { guestLogin } from './utils/reques.uts'
import type { ResponseData } from './utils/reques.uts'
// #ifdef APP
import { getDevicesInfo } from "@/uni_modules/zws-deviceInfo"
// #endif
	
async function getGuestLogin() {
    const params = {} as object
    try {
        const res = await guestLogin(params) as ResponseData
        if (res.code == 0) {
            let guestToken : string = ''
            if (res.data != null) {
                const dataObj = res.data as UTSJSONObject
                guestToken = dataObj.getString('guest_token') ?? ''
            }
            if (guestToken.length > 0) {
                uni.setStorage({ key: 'guestToken', data: guestToken })
            }
        } else {
            console.log('获取到的登录信息失败:', res.message)
        }
    } catch (error) {
        console.log('获取到的登录信息失败:', error)
    }
}
	
	export default {
		globalData: {
			cameraMirror: false as boolean,
			cameraPosition: 'back' as string // 'front' 或 'back'
		},
		onLaunch: function () {
			// 初始化 device_id
			// #ifdef APP
			const storedDeviceId = uni.getStorageSync('device_id') as string | null
			if (storedDeviceId == null || (storedDeviceId as string).length == 0) {
				const deviceId = getDevicesInfo().ANDROID_ID as string
				if (deviceId.length > 0) {
					uni.setStorageSync('device_id', deviceId)
					console.log('初始化 device_id:', deviceId)
				}
			}
			// #endif
			
			// #ifdef H5
			const storedDeviceIdH5 = uni.getStorageSync('device_id') as string | null
			if (storedDeviceIdH5 == null || (storedDeviceIdH5 as string).length == 0) {
				uni.setStorageSync('device_id', 'e95615ac0e36794e')
				console.log('初始化 H5 device_id: e95615ac0e36794e')
			}
			// #endif
			
			getGuestLogin()
		},
		onShow: function () {
		},
		onHide: function () {
		},
		// #ifdef APP-ANDROID || APP-HARMONY
		onLastPageBackPress: function () {
			console.log('App LastPageBackPress')
			if (firstBackTime == 0) {
				uni.showToast({
					title: '再按一次退出应用',
					position: 'bottom',
				})
				firstBackTime = Date.now()
				setTimeout(() => {
					firstBackTime = 0
				}, 2000)
			} else if (Date.now() - firstBackTime < 2000) {
				firstBackTime = Date.now()
				uni.exit()
			}
		},
		// #endif

		onExit: function () {
			console.log('App Exit')
		}
	}
</script>

<style>
	.hover_btn {
		opacity: 0.8;
	}

	.loading-text {
		font-size: 24rpx;
		color: #999999;
	}

	.empty-image {
		width: 220rpx;
		height: 220rpx;
		margin-bottom: 20rpx;
	}
	
</style>