import { getCookie } from "../util/cookie_util";
import { get } from "../util/http_util";
import { SESSION_ID } from "../constant/user"

function parseToken(token) {
    let base64Url = token.split('.')[1];
    let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
    return (decodeURIComponent(escape(window.atob(base64))));
}

export function setLoginSuccessParam(token) {
    //登录状态
    sessionStorage.setItem("isLogin", true);
    //解析token
    // let token = getCookie(SESSION_ID);
    let user = parseToken(token);
    sessionStorage.setItem("user", user);
    sessionStorage.setItem("token", token);
}

export function login(account, password) {
    return new Promise((resolve, reject) => {
        get(
            "api/rest/system/user/login?account=" +
            account + "&password=" + btoa(password)
        )
            .then(res => {
                if (res) {
                    setLoginSuccessParam(res);
                    resolve("登录成功");
                } else {
                    reject("密码错误");
                }
            })
            .catch(err => {
                console.log(err);
                reject(err.message);
            });
    });
}

export function loginByToken(token) {
    return new Promise((resolve, reject) => {
        get("api/rest/user/loginByToken?originToken=" + token)
            .then(res => {
                setLoginSuccessParam();
                resolve();
            })
            .catch(err => {
                console.log(err);
                reject(err);
            });
    });
}