import apis from "@/apis";
import LocalStorageUtil from "@/utils/local";

class AuthUtil {
    static async auth(params: URLSearchParams): Promise<boolean> {
        return await new Promise((resolve) => {
            if (process.env.REACT_APP_ENV === "development") {
                LocalStorageUtil.setItem("__TOKEN__", "ada783c899924df29b3c2e7d4a75ffd4");
                resolve(true);
            } else {
                const token = LocalStorageUtil.getItem("__TOKEN__");
                if (!token) {
                    if (!params.get("code")) {
                        apis.common.getLoginUrl().then(res => {
                            if (res.ok) {
                                window.location.replace(res.data);
                            }
                        });
                    } else {
                        apis.common.login({
                            code: params.get("code") || "",
                            state: params.get("state") || "",
                            amp: params.get("amp") || ""
                        }).then(res => {
                            if (res.ok) {
                                LocalStorageUtil.setItem("__TOKEN__", res.data.token);
                            }
                            resolve(true);
                        });
                    }
                } else {
                    resolve(true);
                }
            }
        });
    }
}

export default AuthUtil;
