import {auth} from "matrix-middle-service-web/src/api/auth";
import {Notify} from "quasar";
import moment from "moment";

export function checkLoginStatus(){
    let user = localStorage.getItem("user")
    let lastLogin = localStorage.getItem("lastLogin")
    let token = localStorage.getItem("token")

    return !!user &&
        !!lastLogin &&
        !!token &&
        moment().diff(moment(lastLogin),"h") < 24
}

export function logoutHandler(){
    localStorage.removeItem("user")
    localStorage.removeItem("lastLogin")
    localStorage.removeItem("token")
}

export function loginRequest(authModel){
    logoutHandler()

    return new Promise((resolve)=>{
        auth.login(authModel).then((resp)=>{
            let res = resp.data
            console.log("login", res)
            if(res.code !== 200){
                Notify.create({
                    position: "top",
                    color:"warning",
                    message: res.data || res.msg,
                    timeout: 500,
                })
                resolve(false)
            } else {
                Notify.create({
                    position: "top",
                    color:"positive",
                    message: "登录成功",
                    timeout: 500,
                })
                localStorage.setItem("user", authModel.account)
                localStorage.setItem("lastLogin", moment().format("YYYY-MM-DD HH:mm:ss"))
                localStorage.setItem("token",res.data.token)
                resolve(true)
            }
        }).catch((e)=>{
            console.error(e)
            Notify.create({
                color: "negative",
                message: "登录失败",
                timeout: 500,
            })
            resolve(false)
        })
    })
}
