import md5 from "js-md5";
import store from '@/store'
import { login,phoneLogin } from '@/api/basicsModules/index';
import { setToken,setExpiresIn } from '@/utils/auth';

//账号登录
export function Login(userInfo) {
    const account = userInfo.username.trim();
    const password = md5(userInfo.password);
    const code = userInfo.code;
    const uuid = userInfo.uuid;
    const userType = userInfo.userType
    return new Promise((resolve, reject) => {
        login(account, password, code, uuid, userType).then(res => {
            if(res.code == 530 || res.code == 503 || res.code == 303){
                resolve(res)
                return
            }
            let data = res.data;
            let avatar = data.avatar?data.avatar:false;
            store.dispatch('setToken',data.token);
            store.dispatch('setName',data.userName);
            store.dispatch('setAvatar',avatar);
            localStorage.setItem('userId',data.userId);
            setToken(data.token)
            setExpiresIn(data.expires_in)
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}

//手机号登录
export function LoginPhone(userInfo) {
    return new Promise((resolve, reject) => {
        phoneLogin(userInfo).then(res => {
            if(res.code == 530 || res.code == 503 || res.code == 303){
                resolve(res)
                return
            }
            let data = res.data;
            let avatar = data.avatar?data.avatar:false;
            store.dispatch('setToken',data.token);
            store.dispatch('setName',data.userName);
            store.dispatch('setAvatar',avatar);
            localStorage.setItem('userId',data.userId);
            setToken(data.token)
            setExpiresIn(data.expires_in)
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}
