import { selectOneDataByParam } from "../data/findData";
import { TABLENAME } from "../config/dbEnum";
import { getMySqlMs } from "../tools/systemTools";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";
import { updateManyData } from "../data/updateData";
import { addData } from "../data/addData";
import { getToken, getPwdMd5 } from "../tools/system";

/**
 * 注册
 * @param loginId 
 * @param pwd 
 */
export async function registerUser(loginId:string, pwd:string, name:string) {
    let filesList = ["loginId", "id", "pwd", "name"];
    let adminUserInfo : any = await selectOneDataByParam(TABLENAME.用户信息表, {loginId}, filesList);
    
    if (!adminUserInfo) {
        throw new BizError(ERRORENUM.用户已存在);
    }

    await addData(TABLENAME.用户信息表, {loginId, pwd: getPwdMd5(loginId, pwd), name: name});

    return { success: true };
}

/**
 * 登录
 * @param loginId 
 * @param pwd 
 * @returns 
 */
export async function adminLogin(loginId:string, pwd:string) {
    let filesList = ["name", "id", "loginId", "pwd"];
    let adminUserInfo : any = await selectOneDataByParam(TABLENAME.用户信息表, {loginId}, filesList);

    console.log(adminUserInfo.data);
    if (!adminUserInfo.data || !adminUserInfo.data.id) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }
    const encryptedPwd = getPwdMd5(adminUserInfo.data.loginId, pwd);
    if (adminUserInfo.data.pwd != encryptedPwd) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }
    let updateUserInfo = {
        token : getToken(adminUserInfo.data.loginId),
        tokenMs : getMySqlMs()
    };
    await updateManyData(TABLENAME.用户信息表, updateUserInfo, {id:adminUserInfo.data.id});
    
    let userInfo = {
        userId:adminUserInfo.data.id,
        userName:adminUserInfo.data.name,
        token:updateUserInfo.token,
    };     

    return {dataInfo:userInfo};
}