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

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

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

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


export function getTokenFromApi():Promise<string> {
	console.log(`${globalConfig.host}${globalConfig.tokenURL}${storage.getString(constant.name)}`)
	
	return new Promise<string>((resolve) =>{
		uni.request({
			url: `${globalConfig.host}${globalConfig.tokenURL}${storage.getString(constant.name)}`,
			method: "GET",
			timeout: 30000,
			success: (res) => {
				let tokenObj = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
				console.log(tokenObj?.['token']);
				storage.set("ApiToken", tokenObj?.['token'])
				resolve(tokenObj?.['token'] as string);
			},
			fail: (err) => {
				console.error('获取Token失败:', err);
				resolve("");
			},
		})
	})
}