/**
 * 注册流程 success
 */

import { BANXUELEIXING, CODETYPE, DOCUMENTTYPE, INDIVIDUALMEMBERTYPE, MEMBERLEVEL, MEMBERTYPE, NATION, OPERATIONREHAVIOR, PROFCATEGORY, REGISTERFLOW, REGISTERSTART, SEX, STATE, UNITMEMBERTYPE, USERREGISTERSTATE } from "../config/enum";
import { ERRORENUM } from "../config/errorEnum";
import { addManyData, addOneData } from "../data/add";
import { deleteManyData, deleteOneData } from "../data/delete";
import { TABLEENUM } from "../data/models/model";
import { find, findCount, findOnce, findOnceToSort } from "../data/select";
import { updateOneData } from "../data/update";
import * as sysTools from "../tools/system";
import { BizError } from "../util/bizError";
import { logConsole } from "../util/log";
import { extractData } from "../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../util/verificationEnum";
import { eccFormParam } from "../util/verificationParam";
import { sendALSMS } from "./sms";

/**
 * 注册状态
 */
let RegisterStartQueue = false;
export async function updateRegisterStart({start}) {
    let updateInfo = "";
    if (start == true) {
        RegisterStartQueue = true;
        updateInfo = "true";
    } else {
        RegisterStartQueue = false;
        updateInfo = "false";
    }

    await updateOneData(TABLEENUM.系统表, {key:"注册开放时间"}, {value:updateInfo});

    return {isSuccess:true}
}

export function updateRegisterStartQueue(start) {
    RegisterStartQueue = start;
}

export function findRegisterStart() {
    return {data:RegisterStartQueue}
}


/**
 * 会员注册【个人会员】【流程一】success
 * @param form 
 */
export async function memberRegister1({form}) {
    let {loginId, mail, pwd, confirmation, phone, codeNum} = form;
    const NowMs = new Date().valueOf();
    /**校验密码 */
    if (pwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);
    if (pwd != confirmation)  throw new BizError(ERRORENUM.两次密码不一致);
    
    /**校验去重 */
    let oldData = await findOnce(TABLEENUM.用户表, {"$or":[{loginId:loginId}, {phone:phone}, {mail:mail}] });
    if (oldData && oldData.userId) {
        if (oldData.registerFlow == REGISTERFLOW.完成第一步) return {userId:oldData.userId}
        if (oldData.loginId == loginId) throw new BizError(ERRORENUM.用户名重复, loginId );
        if (oldData.phone == phone) throw new BizError(ERRORENUM.联系人手机号重复, phone );
        if (oldData.mail == mail) throw new BizError(ERRORENUM.邮箱重复, loginId );
    }

    /**比对验证码 */
    let codeInfo = await findOnceToSort(TABLEENUM.验证码表, {phone, isUse:false, type:CODETYPE.用户注册, sendMs:{"$gt":sysTools.getTodayMs() }}, {sendMs:-1});
    if (!codeInfo) throw new BizError(ERRORENUM.code无效, `${phone}在注册时，code表中不存在该手机号的验证码`);
    if (codeInfo.codeNum != codeNum) throw new BizError(ERRORENUM.验证码错误, `${phone}不存在${codeNum}`);
    if (( codeInfo.sendMs + (30 * 60 *1000) ) < NowMs ) throw new BizError(ERRORENUM.验证码过期);

    /**初始化账号信息 */
    let userId = sysTools.generateUserId();//系统生成唯一id
    let token = sysTools.generateToken(userId);
    let addInfo = {
        userId,
        memberType:MEMBERTYPE.个人会员, 
        isAdmin:STATE.否,
        registerFlow:REGISTERFLOW.完成第一步,//会员注册流程状态
        loginId, mail, pwd, phone,
        token,
        individualMemberType:INDIVIDUALMEMBERTYPE.普通会员,
        isBlackUser:STATE.否,
        saveUnsubmitted:STATE.否,
        firstStep:NowMs,
    };
    await addOneData(TABLEENUM.用户表, addInfo);

    await updateOneData(TABLEENUM.验证码表, {phone, code:codeNum, isUse:false }, {isUse:true});

    return {userId, token}
}


/**
 * 会员注册【个人会员】【流程二】success
 * @param form
 * @param userId  
 * @returns 
 */
export async function memberRegister2({form, id}) {
    /**校验用户是否存在 */
    let selectUserFiles = ["userId", "registerFlow", "userRegisterState"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, memberType:MEMBERTYPE.个人会员, isAdmin:STATE.否}, selectUserFiles );
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (oldInfo.registerFlow != REGISTERFLOW.完成第一步) throw new BizError(ERRORENUM.重复提交);
    let operationBehavior = 0;
    if (oldInfo.userRegisterState != USERREGISTERSTATE.待审核 && oldInfo.userRegisterState != USERREGISTERSTATE.驳回修改 ) {
        throw new BizError(ERRORENUM.数据状态错误);
    }

    /**判断是否第一次提交审核 并更新状态*/
    let remarks = "第一次提交";
    if (oldInfo.userRegisterState == USERREGISTERSTATE.待审核) operationBehavior = OPERATIONREHAVIOR.用户提交
    else {//驳回
        operationBehavior = OPERATIONREHAVIOR.重新提交;
        form.userRegisterState = USERREGISTERSTATE.重新提交;
        remarks = "重新提交";
    }
    
    /**校验枚举 */
    const EccFuncName = '注册个人会员流程2';
    eccEnumValue(EccFuncName, '性别', SEX, form.sex);
    eccEnumValue(EccFuncName, '证件类型', DOCUMENTTYPE, form.documentType);
    eccEnumValue(EccFuncName, '民族', NATION, form.nation);
    eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    
    //更新注册流程
    form.registerFlow = REGISTERFLOW.完成第二步;
    form.askForTime = new Date().valueOf();
    form.saveUnsubmitted = STATE.是;
    await updateOneData(TABLEENUM.用户表, {userId:id}, form);
    
    /**提交审批历史信息 */
    let addApprovalHistory = {
        userId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:operationBehavior,
        remarks:`个人会员${remarks}`
    };
    await addOneData(TABLEENUM.审批历史表, addApprovalHistory);

    return {userId:id};
}


/**
 * 会员注册【单位会员】【流程一】success
 * @param form 
 */
 export async function unitMemberRegister1({form}) {
    let {loginId, mail, pwd, confirmation, phone, codeNum} = form;
    const NowMs = new Date().valueOf();
    /**校验密码 */
    if (pwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);
    if (pwd != confirmation)  throw new BizError(ERRORENUM.两次密码不一致);

    /**校验去重 */
    let oldData = await findOnce(TABLEENUM.用户表, {"$or":[{loginId:loginId}, {phone:phone}, {mail:mail}] });
    if (oldData && oldData.userId) {
        if (oldData.loginId == loginId) throw new BizError(ERRORENUM.用户名重复, loginId );
        if (oldData.phone == phone) throw new BizError(ERRORENUM.联系人手机号重复, phone );
        if (oldData.mail == mail) throw new BizError(ERRORENUM.邮箱重复, loginId );
    }
    
    /**比对验证码 */
    // let codeInfo = await findOnceToSort(TABLEENUM.验证码表, {phone, isUse:false, type:CODETYPE.用户注册, sendMs:{"$gt":sysTools.getTodayMs() }}, {sendMs:-1});
    // if (!codeInfo) throw new BizError(ERRORENUM.code无效, `${phone}在注册时，code表中不存在该手机号的验证码`);
    // if (codeInfo.codeNum != codeNum) throw new BizError(ERRORENUM.验证码错误, `${phone}不存在${codeNum}`);
    // if (( codeInfo.sendMs + (30 * 60 *1000) ) < NowMs ) throw new BizError(ERRORENUM.验证码过期);

    /**初始化账号信息 */
    let userId = sysTools.generateUserId();
    let token = sysTools.generateToken(userId);
    let addInfo = {
        userId,
        memberType:MEMBERTYPE.单位会员,
        isAdmin:STATE.否, //是否管理员
        registerFlow:REGISTERFLOW.完成第一步, //会员注册流程状态
        askForTime:NowMs, //申请时间
        loginId,
        mail,
        pwd,
        phone,
        token,
        unitMail:mail,
        isBlackUser:STATE.否,
        saveUnsubmitted:STATE.否,
        firstStep:NowMs,
    };
    await addOneData(TABLEENUM.用户表, addInfo);

    /**修改验证码状态为已使用 */
    await updateOneData(TABLEENUM.验证码表, {phone, code:codeNum, isUse:false }, {isUse:true});

    return {userId, token};
}


/**
 * 会员注册【单位会员】【流程二】success
 * @param form 表单 
 * @param keyanForm 科研表单
 * @param userId 
 * @returns 
 */
export async function unitMemberRegister2({form, keyanForm, id}) {
    const keyanFormItemConfig = {
        startTime: {type:'Number'},
        endTime: {type:'Number'},
        describe: {type:'String'}
    };
    keyanForm.forEach(item => {
        eccFormParam("会员注册流程二", keyanFormItemConfig, item );
    });
    let selectUserFiles = ["userId", "registerFlow", "userRegisterState"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, memberType:MEMBERTYPE.单位会员, isAdmin:STATE.否}, selectUserFiles);
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (oldInfo.registerFlow != REGISTERFLOW.完成第一步) throw new BizError(ERRORENUM.重复提交);
    if (oldInfo.userRegisterState != USERREGISTERSTATE.待审核 && oldInfo.userRegisterState != USERREGISTERSTATE.驳回修改 ) {
        throw new BizError(ERRORENUM.数据状态错误);
    }

    /**校验枚举 */
    const EccFuncName = '注册单位会员流程2';
    eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    eccEnumValue(EccFuncName, '院校办学类型', BANXUELEIXING, form.yuanXiaoBanXueLeiXing);
    eccEnumValue(EccFuncName, '单位会员类型', UNITMEMBERTYPE, form.unitMemberType);

    form.registerFlow = REGISTERFLOW.完成第二步;
    await updateOneData(TABLEENUM.用户表, {userId:id, saveUnsubmitted:STATE.否}, form);

    /**注册提交单位科研成果信息 */
    await deleteManyData(TABLEENUM.单位所获得科研成果表, {userId:id});
    let addList = [];
    for (let i = 0; i < keyanForm.length; i++) {
        let {startTime, endTime, describe} = keyanForm[i];
        addList.push({
            id:sysTools.generateSystemId(TABLEENUM.单位所获得科研成果表, id),
            userId:id,
            startTime, endTime, describe
        });
    }
    await addManyData(TABLEENUM.单位所获得科研成果表, addList);
    
    return sysTools.successResult();
}


/**
 * 会员注册【单位会员】【流程三】success
 * @param application 入会申请表地址
 * @param userId 
 */
export async function unitMemberRegister3({application, id}) {
    let selectUserFiles = ["userId", "registerFlow", "userRegisterState", "application", "memberType"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, memberType:MEMBERTYPE.单位会员, isAdmin:STATE.否}, selectUserFiles);
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (oldInfo.registerFlow != REGISTERFLOW.完成第二步) throw new BizError(ERRORENUM.重复提交);
    if (oldInfo.memberType != MEMBERTYPE.单位会员) throw new BizError(ERRORENUM.流程3不支持会员身份非单位会员);
    
    /**判断是否第一次提交审核 并更新状态*/
    let operationBehavior = 0;
    let userRegisterState = USERREGISTERSTATE.待审核;
    let remarks = "第一次提交";
    if (oldInfo.userRegisterState == USERREGISTERSTATE.待审核) operationBehavior = OPERATIONREHAVIOR.用户提交
    else {//驳回
        operationBehavior = OPERATIONREHAVIOR.重新提交;
        userRegisterState = USERREGISTERSTATE.重新提交;
        remarks = "重新提交";
    }

    let updateForm = {
        userRegisterState, 
        applicationForm:application, 
        registerFlow:REGISTERFLOW.完成第三步, 
        askForTime : new Date().valueOf(), 
        saveUnsubmitted:STATE.是
    };
    await updateOneData(TABLEENUM.用户表, {userId:id}, updateForm);

    /**提交审批历史信息 */
    let addApprovalHistory = {
        id:sysTools.generateSystemId(TABLEENUM.审批历史表, id),
        userId:id,
        operationTime: new Date().valueOf(),
        operationBehavior:operationBehavior,
        remarks:`单位会员${remarks}`,
    };
    await addManyData(TABLEENUM.审批历史表, addApprovalHistory);

    return sysTools.successResult();
}

/**
 * 获取当前会员注册流程
 * registerFlow：注册流程状态 REGISTERFLOW 会员注册流程步骤
 * userRegisterState：用户注册状态 USERREGISTERSTATE 会员注册是否已审批通过
 * 前端通过该方法获取注册流程状态，流程1通过返回状态【完成第一步】，流程2通过返回状态【完成第二步】，流程3通过返回状态【完成第三步】
 */
export async function registerFlowType({id}) {
    if(!id) return {};
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, isAdmin:STATE.否}, ["userId", "registerFlow", "userRegisterState", "memberType"]);
    if (!oldInfo || !oldInfo.userId) return {code:200, msg:"用户未注册"} //用户不存在不需要报错
    if (oldInfo.userRegisterState == USERREGISTERSTATE.通过) {
        return {code:601, msg:"用户已注册"}
    }

    let dataInfo:any = extractData(oldInfo, ["userId", "registerFlow", "userRegisterState", "memberType"]);

    return {dataInfo};
}

/**
 * 会员注册【短信验证码】 success
 * @param userId 
 * @param phone 
 * @returns 
 */
export async function memberRegisterSendCode({phone}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {phone}, ["userId"]);
    if (userInfo && userInfo.userId) throw new BizError(ERRORENUM.该手机号已被注册);
    const NowMs = new Date().valueOf();
    let codeSelectParam = { phone, isUse:false,  type:CODETYPE.用户注册, sendMs:{"$gt":sysTools.getTodayMs()} }
    let lastCodeInfo = await findOnceToSort(TABLEENUM.验证码表, codeSelectParam, {sendMs:-1});
  
    if (lastCodeInfo && lastCodeInfo.codeNum) {
        if ( (lastCodeInfo.sendMs + (60*1000)) > NowMs ) throw new BizError(ERRORENUM.频繁操作请稍后再试);
        /**校验今日同类型验证码次数 */
        let todayNotUseCount = await findCount(TABLEENUM.验证码表, codeSelectParam);
        if (todayNotUseCount >= 4) throw new BizError(ERRORENUM.发送验证码次数超限制, `${phone} 注册验证码超过限制3`);
    }

    const Code = sysTools.generateSMSCode();//生成短信验证码

    /**发送短信模块 */
    await sendALSMS(Code, phone);
    let addInfo = {codeNum:Code, phone, sendMs:NowMs, type:CODETYPE.用户注册, isUse:false};
    await addOneData(TABLEENUM.验证码表, addInfo);

    return {code:""};
}


/**
 * 单位会员回显【流程二】
 * @param userId 
 * @returns {基本信息, 单位信息, 单位所获得科研成果}
 */

const UnitBasicConfig = ["userId", "unitName", "sheng", "shi", "qu", "addres", "uscc", "legalPerson", "legalPersonPhone", "legalPersonMail",
"contactPerson", "contactPersonDuties", "contactPersonPhone", "uusinessLicenseUrl", "unitMail"];
const UnitConfig = ["unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", "yuanXiaoBanGongFuZeRenZhiWu", 
"yuanXiaoFuZeRenDianHua", "yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", "yuanXiaoKeYanFuZeRenDianHua", 
"jiaoXueFuZeRenXinMing", "yuanXiaoXueShengZongRenShu", "yuanXiaoJiaoZhiGongZongRenShu", "jiaoXueFuZeRenDianHua", "kaishezhuanYe", "danWeiJianJie"];

export async function unitMemberEcho2({id}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    let basicInfo:any = extractData(oldInfo, UnitBasicConfig);
    let unitInfo:any = extractData(oldInfo, UnitConfig);
    delete basicInfo.userId;
    /**处理枚举值 */
    // unitInfo.unitMemberType = changeEnumValue(UNITMEMBERTYPE, unitInfo.unitMemberType);
    // unitInfo.yuanXiaoBanXueLeiXing = changeEnumValue(BANXUELEIXING, unitInfo.yuanXiaoBanXueLeiXing);
    
    let oldKeYanList = await find(TABLEENUM.单位所获得科研成果表, {userId:id});
    let scientificResearch = [];
    oldKeYanList.forEach(info => {
        let item = extractData(info, ["id", "startTime", "endTime", "describe"]);
        scientificResearch.push(item);
    });
    
    return {basicInfo, unitInfo, scientificResearch};
}


/**
 * 单位会员回显【流程三】
 * @param userId 
 * @returns 
 */
export async function unitMemberEcho3({id}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id}, ["userId", "applicationForm"]);
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    let dataInfo:any = extractData(oldInfo, ["applicationForm"]);
    dataInfo.defaultApplicationForm = "https://cefa-exam.oss-cn-beijing.aliyuncs.com/public/%E5%8D%95%E4%BD%8D%E4%BC%9A%E5%91%98%E6%83%85%E5%86%B5%E7%BB%9F%E8%AE%A1%E8%A1%A8.docx?Expires=1714044309&OSSAccessKeyId=TMP.3KeeLL9N8Dqf4H3NtckLxQ92VhuFr4XnmF673gTUjgsQHXK5GLLXMXVNCY4JjXUwRs5uqHamQbv3DdYqi4BKkMhcTYyyPS&Signature=b%2BJhkE%2BHEBhuVPQlqVsPoxDJoMQ%3D";

    return {dataInfo};
}


/**
 * 个人会员回显【流程二】
 * @param param0 
 * @returns {基本信息, 专业信息, 其他附件}
 */

const IndividualBasicConfig = ["name", "sex", "documentType", "documentId", "birth", "nation", "sheng", "shi", "qu", "addres", "education", "photoUrl"];
const SpecialityConfig = ["unitName", "duties", "workTitle", "profCategory", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF"];

export async function individualMemberDetails({id}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let basicInfo:any = extractData(oldInfo, IndividualBasicConfig);
    // basicInfo.documentType = changeEnumValue(DOCUMENTTYPE, basicInfo.documentType);
    // basicInfo.nation = changeEnumValue(NATION, basicInfo.nation);

    let specialityInfo:any = extractData(oldInfo, SpecialityConfig);
    basicInfo.profCategory = changeEnumValue(PROFCATEGORY, basicInfo.profCategory);
    
    let otherAttachment:any = extractData(oldInfo, ["cardUrlJust", "cardUrlBack", "academicCERTUrl", "professionalCERTUrl", "auxiliaryMaterial"]);
    
    return {basicInfo, specialityInfo, otherAttachment};
}


// 2.0 注册第二步保存功能

/**
 * 会员注册【单位会员】【流程二】
 * 注册第二步保存未提交
 * @param form 表单 
 * @param keyanForm 科研表单
 * @param userId 
 * @returns 
 */
export async function unitMemberNotSaved({form, keyanForm, id}) {
    const keyanFormItemConfig = {
        startTime: {type:'Number'},
        endTime: {type:'Number'},
        describe: {type:'String'}
    };

    if (keyanForm) {
        keyanForm.forEach(item => {
            eccFormParam("注册单位会员第二步保存未提交", keyanFormItemConfig, item );
        });
    }

    let selectUserFiles = ["userId", "registerFlow", "userRegisterState"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, memberType:MEMBERTYPE.单位会员, isAdmin:STATE.否}, selectUserFiles);
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (oldInfo.registerFlow != REGISTERFLOW.完成第一步) throw new BizError(ERRORENUM.重复提交);
    if (oldInfo.userRegisterState != USERREGISTERSTATE.待审核 && oldInfo.userRegisterState != USERREGISTERSTATE.驳回修改 ) {
        throw new BizError(ERRORENUM.数据状态错误);
    }

    /**校验枚举 */
    const EccFuncName = '注册单位会员流程第二步保存未提交';
    eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    eccEnumValue(EccFuncName, '院校办学类型', BANXUELEIXING, form.yuanXiaoBanXueLeiXing);
    eccEnumValue(EccFuncName, '单位会员类型', UNITMEMBERTYPE, form.unitMemberType);

    form.saveUnsubmitted = STATE.否;
    await updateOneData(TABLEENUM.用户表, {userId:id, saveUnsubmitted:STATE.否}, form);
    
    return sysTools.successResult();
}


/**
 * 会员注册【个人会员】【流程二】
 * 注册第二步保存未提交
 * @param form
 * @param userId  
 * @returns 
 */
export async function memberNotSaved({form, id}) {
    /**校验用户是否存在 */
    let selectUserFiles = ["userId", "registerFlow", "userRegisterState"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id, memberType:MEMBERTYPE.个人会员, isAdmin:STATE.否}, selectUserFiles );
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (oldInfo.registerFlow != REGISTERFLOW.完成第一步) throw new BizError(ERRORENUM.重复提交);
    let operationBehavior = 0;
    if (oldInfo.userRegisterState != USERREGISTERSTATE.待审核 && oldInfo.userRegisterState != USERREGISTERSTATE.驳回修改 ) {
        throw new BizError(ERRORENUM.数据状态错误);
    }

    /**判断是否第一次提交审核 并更新状态*/
    let remarks = "第一次提交";
    if (oldInfo.userRegisterState == USERREGISTERSTATE.待审核) operationBehavior = OPERATIONREHAVIOR.用户提交
    else {//驳回
        operationBehavior = OPERATIONREHAVIOR.重新提交;
        form.userRegisterState = USERREGISTERSTATE.重新提交;
        remarks = "重新提交";
    }
    
    /**校验枚举 */
    const EccFuncName = '注册个人会员第二步保存未提交';
    eccEnumValue(EccFuncName, '性别', SEX, form.sex);
    eccEnumValue(EccFuncName, '证件类型', DOCUMENTTYPE, form.documentType);
    eccEnumValue(EccFuncName, '民族', NATION, form.nation);
    eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    
    //更新注册流程
    // form.registerFlow = REGISTERFLOW.完成第一步;
    form.saveUnsubmitted = STATE.否;
    form.askForTime = new Date().valueOf();
    await updateOneData(TABLEENUM.用户表, {userId:id}, form);

    return {userId:id};
}


/**
 * 删除14天未注册成功的用户
 * 设置定时器，一天检查一次是否注册成功
 */
 export async function initSaveUnsubmitted() {
    deleteSaveUnsubmitted();
    setInterval(async function () {
        await deleteSaveUnsubmitted();
    }, 3600 * 1000 * 24);
}


export async function deleteSaveUnsubmitted() {
    let time = sysTools.getTodayMs();
    let oldInfo = await find(TABLEENUM.用户表, {saveUnsubmitted:STATE.否}, ["userId", "firstStep"]);
    if (!oldInfo || !oldInfo.length) return;

    // 14天的时间间隔（毫秒）
    const fourteenDays = 14 * 24 * 3600 * 1000;

    for (let i = 0; i < oldInfo.length; i++) {
        let info = oldInfo[i];
        let futureDate = info.firstStep + fourteenDays; //计算第一步创建14天后时间戳
        /**判断今天是否已经是14天后 */
        if (time > futureDate) { //14天后，直接删除该用户信息
            await deleteOneData(TABLEENUM.用户表, {userId:info.userId});
            logConsole(`用户超出14天未提交注册，已删除改用户信息 userid：${info.userId}`, time);
            // throw new ConsoleError(`用户超出14天未提交注册，已删除改用户信息 userid：${info.userId}`);
        }
    }


}
















