import storage from '@/utils/storage';
import { constant } from '@/utils/constant';
import { globalConfig } from '@/config'
const TokenKey = 'App-Token'
const APITokenKey = 'Api-Token'

export function getToken() : string {
	return uni.getStorageSync(TokenKey) as string | ''
}

export function setToken(token : string) : void {
	return uni.setStorageSync(TokenKey, token)
}

export function getApiToken() : string {
	return uni.getStorageSync(APITokenKey) as string | ''
}

export function setApiToken(token : string) : void {
	return uni.setStorageSync(APITokenKey, token)
}

export function removeToken() : void {
	return uni.removeStorageSync(TokenKey)
}

export function removeApiToken() : void {
	return uni.removeStorageSync(APITokenKey)
}

export function getCurrentUserSync() : string {
	return uni.getStorageSync(constant.name) as string | ''
}

export function setCurrentUserSync(name : string) : void {
	return uni.setStorageSync(constant.name, name)
}

export function getCurrentUserNameSync() : string {
	return uni.getStorageSync(constant.username) as string | '';
}

export function setCurrentUserNameSync(username : string) : void {
	return uni.setStorageSync(constant.username, username)
}

export function getTokenFromApi() : Promise<string> {
	console.log(`${globalConfig.host}${globalConfig.tokenURL}${getCurrentUserNameSync()}`)
	return new Promise<string>((resolve) => {
		uni.request({
			url: `${globalConfig.host}${globalConfig.tokenURL}${getCurrentUserNameSync()}`,
			method: "GET",
			timeout: 30000,
			success: (res) => {
				console.log(res);
				// 处理嵌套的data结构
				let firstLayerData = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
				let tokenObj = firstLayerData?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
				console.log(tokenObj?.['token'] as string)
				setApiToken(tokenObj?.['token'] as string)
				resolve(tokenObj?.['token'] as string);
			},
			fail: (err) => {
				uni.hideLoading()
				// uni.showModal({
				// 	content: '获取Token失败:' + err.errMsg 
				// })
				resolve("");
			},
		})
	})
}

