/**
 * 管理后台用户逻辑层 
 * 作者: lxm
 * 主要包括有 孵化器账号的登录 
 * 预留好  重置密码  退出登录 接口  
 */

import { ERRORENUM } from "../../config/errorEnum";
import { findGuanWeiHuiUserInfoByLoginId } from "../../data/guanWeiHui/guanweihui";
import { BizError } from "../../util/bizError";
import { getPwdMd5, getToken } from "../../tools/system";


/**
 * 登录
 * @param loginId 信用代码
 * @param pwd 密码
 * @returns resultUserInfo:{uscc, name} 登录后的信息
 */
export async function login(loginId:string, pwd:string) {
    
    let userInfo = await findGuanWeiHuiUserInfoByLoginId(loginId);
    if(!userInfo) throw new BizError(ERRORENUM.账号不存在, loginId);

    let checkPwd = getPwdMd5(loginId, pwd); 
    if (userInfo.pwd != checkPwd) throw new BizError(ERRORENUM.密码错误);

    const Token = getToken(loginId);
    
    let resultUserInfo = {
        loginId: userInfo.loginId,
        name: userInfo.name,
        token:Token
    };

    userInfo.token = Token;
    userInfo.tokenMs = new Date().valueOf();

    await userInfo.save();
    
    return resultUserInfo;
}