import {auth, LoginDTO} from "src/views/tabs/location-record/api";
import moment from "moment";
import {ElMessage, ElNotification} from "element-plus";

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:LoginDTO, server:string){
    logoutHandler()

    return new Promise((resolve)=>{
        auth.login(authModel,server).then((resp)=>{
            let res = resp.data
            console.log("login", res)
            if(res.code !== 200){
                ElMessage.warning({
                    message: res.data || res.msg,
                    duration: 500
                })
                resolve(false)
            } else {
                ElMessage.success({
                    message: "登录成功",
                    duration: 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)
            ElMessage.error({
                message: "登录失败",
                duration: 500,
            })
            resolve(false)
        })
    })
}
