import FetchRequest from "@/api/FetchRequest";
import { logout } from '@/api/Login'
import { useWsStore } from '@/store/WsStore'
import {useChatStore} from "@/store/chatStore";
import MessageUtils from "@/utils/MessageUtils";

class Auth {
	static getToken = () : string => {
		return uni.getStorageSync("access_token") ?? "";
	};

	static setToken = (token : string) : void => {
		uni.setStorageSync("access_token", token);
	};

	static setRefreshToken = (token : string) : void => {
		uni.setStorageSync("refresh_token", token);
	};

	static getRefreshToken = () : string => {
		return uni.getStorageSync("refresh_token") ?? "";
	};

	static clearToken = () : void => {
		uni.removeStorageSync("access_token");
	};

	static isLogin = () => {
		return new Promise((resolve, reject) => {
			const header : HeadersInit = {
				"Accept": "application/json",
				"Content-Type": "application/json",
				"Authorization": "Bearer " + Auth.getToken()
			};
			const config : RequestInit = {
				method: 'GET',
				mode: "cors",
				headers: header,
			};
			FetchRequest.fetch(`${FetchRequest.getHost()}/api/sys/users/my`, config)
				.then(res => {
					if (res.data.code === 200) {
						uni.setStorageSync('userId',res.data.id)
						resolve(true)
					}else{
						reject(false)
					}
				}).catch(err => {
					console.error(err)
					reject(false)
				})
		})
	}

	static logout = () => {
		logout()
			.finally(() => {
				useChatStore().clearMessage();
				this.clearToken();
				useWsStore().close(true)
				uni.redirectTo({
					url:"/pages/login/login",
					fail(err) {
						MessageUtils.error('无法跳转到登录界面');
					}
				})
			})
	}
}
export default Auth;
