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

import { ERRORENUM } from "../../config/errorEnum";
import { findGuanWeiHuiUserInfoByLoginId } from "../../data/guanWeiHui/guanweihui";
import { BizError } from "../../util/bizError";
import { getPwdMd5, getToken } from "../../tools/system";
import { findFuHuaQiByUSCC } from "../../data/fuHuaQi/fuhuaqi";
const md5 = require("md5");

/**
 * 登录
 * 4.0版本更新：加入孵化器角色登录
 * @param loginId 信用代码
 * @param pwd 密码
 * @returns resultUserInfo:{uscc, name} 登录后的信息
 */
export async function login(loginId:string, pwd:string) {
    let userInfo = await findGuanWeiHuiUserInfoByLoginId(loginId);
    let userIsNull = false;
    let isFuHuaQi = false;
    if(!userInfo || !userInfo.loginId) {
        userInfo = await findFuHuaQiByUSCC(loginId);
        if (!userInfo || !userInfo.uscc) userIsNull = true;
        isFuHuaQi = true;
        pwd = md5(pwd);
    }
    // if (userIsNull) throw new BizError(ERRORENUM.账号不存在, loginId);

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

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

    if (isFuHuaQi) {
        //孵化器登录管理后台
        token = token +'ad'
        resultUserInfo.loginId = userInfo.uscc;
        resultUserInfo.token = token;
        userInfo.adminToken = token;
        
    } else {
        //管委会登录管理后台
        resultUserInfo.loginId = userInfo.loginId;
        resultUserInfo.token = token;
        userInfo.token = token;
        userInfo.tokenMs = new Date().valueOf();
    }

    await userInfo.save();
    
    return resultUserInfo;
}
