/**
 * 用户相关 登录登出
 */

import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { ERRORENUM } from "../config/enum/errorEnum";
import { operationalData, selectData } from "../data/operationalData";
import { getMySqlMs, getToken, md5PwdStr } from "../tools/system";
import { BizError } from "../util/bizError";



//==登录登出

export async function adminLogin(loginId:string, pwd:string) {
    let filesList = ["name", "aId", "pwd"];
    let adminUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.管理后台用户, {loginId}, filesList);

    if (!adminUserInfo || !adminUserInfo.aId) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }
    if (adminUserInfo.pwd != pwd) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }

    let updateUserInfo = {
        token : getToken(adminUserInfo.uId),
        tokenMs : getMySqlMs()
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.管理后台用户, updateUserInfo, {aId:adminUserInfo.aId});
    
    let userInfo = {
        userId:adminUserInfo.aId,
        userName:adminUserInfo.name,
        token:updateUserInfo.token,
    };

    return {dataInfo:userInfo};
}

export async function adminLogout(uId) {
    let filesList = ["name", "aId", "pwd"];
    let adminUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.管理后台用户, {uId}, filesList);
    let updateInfo = {
        token : getToken(adminUserInfo.aId),
        tokenMs : getMySqlMs()
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.管理后台用户, updateInfo, {uId:adminUserInfo.aId});


    return {isSuccess:true};
}


export async function enterpriseLogin(uscc:string, code:string) {
    let filesList = ["eId", "uscc", "enterpriseName", "randomCode"];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc}, filesList);

    if (!enterpriseUserInfo || !enterpriseUserInfo.eId || !enterpriseUserInfo.randomCode) {
        throw new BizError(ERRORENUM.请先申请入孵);
    }
    if (enterpriseUserInfo.randomCode != code) {
        throw new BizError(ERRORENUM.验证码错误);
    }
    
    let userInfo = {
        userId:enterpriseUserInfo.eId,
        token:md5PwdStr(enterpriseUserInfo.randomCode),
        userName:enterpriseUserInfo.enterpriseName
    };
  
    return {
        dataInfo:userInfo
    };
}

export async function enterpriseLogout(eId:string) {
    return {isSuccess:true};
}

