/**
 * 会员首页展板逻辑
 * 【二期内容：申请理事、申请常务理事、申请专家会员、会员积分、活动列表[立即参加]、消息中心暂时展示缴费提醒】
 */

import moment = require("moment");
import { CHANGEAPPLYTYPE, CLIENTMSGLABLE, CODPARTICIPANT, DOCUMENTTYPE, INDIVIDUALMEMBERTYPE, MEMBERLEVEL, MEMBERLEVELCHANGE, MEMBERSTATE, MEMBERTYPE, NATION, PAYMENTSTATUS, PROFCATEGORY, SEX, STATE, UNITMEMBERTYPE, USERREGISTERSTATE } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { addManyData, addOneData } from "../../data/add";
import { deleteManyData } from "../../data/delete";
import { TABLEENUM } from "../../data/models/model";
import { find, findOnce } from "../../data/select";
import { updateOneData } from "../../data/update";
import { generateSystemId, getEdition, successErrorResult, successResult } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { extractData } from "../../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import { getCityNameByCode } from "../../config/cityConfig";


/**
 * 会员信息展示
 * @param userId 登录的用户id
 * @returns 个人会员：{头部数据， 基本信息， 专业信息， 其他附件}
 * @returns 单位会员：{头部数据， 基本信息， 单位信息， 单位所获得科研成果}
 */
export async function getMemberData({userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let topSelectFiles = ["loginId", "memberType", "userRegisterState", "integral", "joinTime", "lifespanStartTime", "lifespanEndTime", "memberLevel", "isFirstPay", "paymentStatus", "memberState"];
    let baseSelectFiles = [];
    let majorSelectFiles = [];
    let otherAttachment:any= {};
    /**判断会员类型，个人会员与单位会员返回不同字段 */
    if (oldInfo.memberType == MEMBERTYPE.单位会员) {
        baseSelectFiles = ["userId", "unitName", "uscc", "legalPerson", "legalPersonPhone", "legalPersonMail", "unitMail", "contactPerson", 
        "contactPersonDuties", "contactPersonPhone", "uusinessLicenseUrl", "addres", "sheng", "shi", "qu", "kaishezhuanYe", "danWeiJianJie"];
        majorSelectFiles = ["unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", 
        "yuanXiaoFuZeRenDianHua", "yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", 
        "yuanXiaoKeYanFuZeRenDianHua", "jiaoXueFuZeRenXinMing", "jiaoXueFuZeRenDianHua"];
        /**获取单位科研成果数据 */
        let oldKeYanList = await find(TABLEENUM.单位所获得科研成果表, {userId}, ["id", "startTime", "endTime", "describe"]);
        if (!otherAttachment.dataList) otherAttachment.dataList = [];
        oldKeYanList.forEach(info => {
            otherAttachment.dataList.push({
                id:info.id,
                startTime: info.startTime,
                endTime: info.endTime,
                describe:info.describe
            });
        })

    } else {
        baseSelectFiles = ["userId", "name", "sex", "nation", "birth", "documentType", "documentId", "sheng", "shi", "qu", "phone", "mail", 
        "addres", "photoUrl", "education", "uscc", "unitName"];
        majorSelectFiles = ["unitName", "duties", "workTitle", "profCategory", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF"]; 
        let otherAttachmentFiles = ["cardUrlJust", "cardUrlBack", "academicCERTUrl", "professionalCERTUrl", "auxiliaryMaterial"];
        otherAttachment = extractData(oldInfo, otherAttachmentFiles);
    }

    /**返回指定配置字段 */
    let topInfo:any = extractData(oldInfo, topSelectFiles);
    // 变更申请职位不为空并且状态不等于通过的时候，代表提交了变更理事申请，并且还未通过审批，需要先使用变更前职位
    // if(!oldInfo.beforeChange && oldInfo.changeApplyType != CHANGEAPPLYTYPE.通过) topInfo.memberLevel = oldInfo.beforeChange;
    let baseInfo:any = extractData(oldInfo, baseSelectFiles);
    let majorInfo:any = extractData(oldInfo, majorSelectFiles);
    
    /**处理枚举值 */
    topInfo.integral = 0;
    if(topInfo.joinTime) topInfo.joinTime = moment(topInfo.joinTime).format("YYYY-MM-DD");
    if(topInfo.lifespanEndTime) {
        if(topInfo.memberState == MEMBERSTATE.异常) topInfo.lifespanEndTime = "欠费中"; 
        else topInfo.lifespanEndTime = moment(topInfo.lifespanEndTime).format("YYYY-MM-DD");
    }

    if(topInfo.userRegisterState == USERREGISTERSTATE.通过) topInfo.userRegisterState = "已入会";
    else topInfo.userRegisterState = "未入会";
    // if(topInfo.memberLevel) topInfo.memberLevel = changeEnumValue(MEMBERLEVEL, topInfo.memberLevel);
    // if(baseInfo.sex) baseInfo.sex = changeEnumValue(SEX, baseInfo.sex);
    // if(baseInfo.documentType) baseInfo.documentType = changeEnumValue(DOCUMENTTYPE, baseInfo.documentType);
    // if(baseInfo.nation) baseInfo.nation = changeEnumValue(NATION, baseInfo.nation);
    // if(majorInfo.profCategory) majorInfo.profCategory = changeEnumValue(PROFCATEGORY, majorInfo.profCategory);
    // if(majorInfo.unitMemberType) majorInfo.unitMemberType = changeEnumValue(UNITMEMBERTYPE, majorInfo.unitMemberType);
    // if(majorInfo.yuanXiaoBanXueLeiXing) majorInfo.yuanXiaoBanXueLeiXing = changeEnumValue(BANXUELEIXING, majorInfo.yuanXiaoBanXueLeiXing);

    return {topInfo, baseInfo, majorInfo, otherAttachment};
}


/**
 * 单位会员 修改
 * @param form 修改信息表单
 * @param keyanForm 修改科研信息表单
 * @param userId 登录的用户id
 * @returns 
 */
export async function unitMemberUpdate({form, keyanForm, userId}) {
    const keyanFormItemConfig = {
        startTime: 'Number',
        endTime: 'Number',
        describe: 'String'
    };
    keyanForm.forEach(item => {
        eccFormParam("单位会员修改", keyanFormItemConfig, item );
    });
    
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    /**校验枚举 */
    const EccFuncName = '单位会员修改';
    eccEnumValue(EccFuncName, '单位信息类型', UNITMEMBERTYPE, form.unitMemberType);

    /**确保邮箱的唯一性 */
    let distinctMailInfo = await findOnce(TABLEENUM.用户表, {mail:form.unitMail}, ["userId"]);
    if (distinctMailInfo && distinctMailInfo.userId && distinctMailInfo.userId != oldInfo.userId) throw new BizError(ERRORENUM.邮箱重复, oldInfo.loginId, oldInfo.mail );
    form.mail = form.unitMail;
    /**修改会员用户信息 */
    await updateOneData(TABLEENUM.用户表, {userId}, form);

    /**删除对应userId科研成果 */
    let oldKeYanList= await find(TABLEENUM.单位所获得科研成果表, {userId});
    if (oldKeYanList && oldKeYanList.length) {
        await deleteManyData(TABLEENUM.单位所获得科研成果表, {userId});
    }
    

    /**添加新的科研信息 */
    let addList = [];
    for (let i = 0; i < keyanForm.length; i++) {
        let { startTime, endTime, describe } = keyanForm[i];
        addList.push({
            id:generateSystemId(TABLEENUM.单位所获得科研成果表, userId),
            userId,
            startTime, endTime, describe
        });
    }
    await addManyData(TABLEENUM.单位所获得科研成果表, addList);

    return successResult();
}


/**
 * 个人会员 修改
 * @param userId 登录的用户id
 * @param form 修改信息表单
 * @returns 
 */
 export async function individualMemberUpdate({form, userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    await updateOneData(TABLEENUM.用户表, {userId}, form);

    return successResult();
}


/**
 * 消息中心列表
 * 缴费消息提醒
 * @param userId 登录的用户id
 */
export async function getXiaoXiZhongXin({userId}) {
    const SelectFiles = ["userId", "lifespanEndTime", "isGracePeriod", "gracePeriodEndTime", "lifespanStartTime"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId, isAdmin:STATE.否}, SelectFiles);

    let dataInfo:any = extractData(oldInfo, ["lifespanStartTime", "lifespanEndTime"]);

    const NowMs = new Date().valueOf();

    /**判断是否宽限期 */
    let str = '';
    if (oldInfo.isGracePeriod == STATE.是 && oldInfo.gracePeriodEndTime > NowMs) str = "宽限期中";
    else {
        if (NowMs > oldInfo.lifespanEndTime) {
            str = '过期';
            if (NowMs > oldInfo.lifespanEndTime + (90*24*3600*1000)){
                str += '1年外';
            } else if ( NowMs > oldInfo.lifespanEndTime + (90*24*3600*1000) ) {
                str += '1年内';
            } else if (NowMs > oldInfo.lifespanEndTime + (30*24*3600*1000)) {
                str += '90天内';
            } else {
                str += '30天内'; 
            }
        } else {
            if (NowMs > oldInfo.lifespanEndTime - (90*24*3600*1000) ) {
                str = "不足90天";
            } else {
                str = "大于90天";
            }
        }
    }
    dataInfo.membershipFees = str;

    return {dataInfo};
}


/**
 * 地图省数量统计
 * @param userId 登录的用户id 
 * @returns 
 */
export async function getSheng ({userId}) {
    let myOldInfo = await findOnce(TABLEENUM.用户表, {userId}, ["sheng"]);
    if (!myOldInfo || !myOldInfo.sheng) throw new BizError(ERRORENUM.目标数据不存在);
    let myDataInfo = extractData(myOldInfo, ["sheng"]);

    let allOldList = await find(TABLEENUM.用户表, {}, ["sheng"]);
    if (!allOldList || !allOldList.length) throw new BizError(ERRORENUM.目标数据不存在);
    
    let allDataList = {};
    allOldList.forEach( info => {
        //初始数据包含没有填省份的，过滤省份为undefined的数据，统计省份个数
        if (info.sheng) {
            if (!allDataList[info.sheng]) allDataList[info.sheng] = 0;
            allDataList[info.sheng] += 1;
        }
    })

    return {myDataInfo, allDataList};
}


/**
 * 活动列表
 */
 export async function getHuoDongTongZhi () {
    let oldList = await find(TABLEENUM.活动通知, {}, ["id", "name"]);
    if (!oldList || oldList.length<1) throw new BizError(ERRORENUM.目标数据不存在);
    
    let dataList = [];
    oldList.forEach( info => {
        let item = extractData(info, ["id", "name"]);
        dataList.push(item);
    })

    return {dataList};
}


/**
 * 根据会员类别返回对应可下载的证书类型
 * @param param0 
 * @returns 
 */
 export async function getCertificate({userId}) {
    const Files = ["userId", "memberType", "userRegisterState", "paymentStatus", "individualMemberType", "unitMemberType", 
    "sheng", "documentId", "memberNum", "lifespanStartTime", "lifespanEndTime", "shi","qu","addres", "unitName", "session"];
    let userInfo = await findOnce(TABLEENUM.用户表, {userId}, Files);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let certificate = false;//是否可以下载
    let cefaInfo:any = {};
    let msg = '会员注册尚未审核通过，无法下载证书';
    //判断是否审批通过
    if (userInfo.userRegisterState == USERREGISTERSTATE.通过) {
        if(userInfo.memberType == MEMBERTYPE.个人会员) {
            //个人会员已支付可下载
            if (userInfo.individualMemberType == INDIVIDUALMEMBERTYPE.普通会员 && userInfo.paymentStatus != PAYMENTSTATUS.未支付) certificate = true;
            //个人会员专家无需支付可下载
            if (userInfo.individualMemberType == INDIVIDUALMEMBERTYPE.专家会员) certificate = true;
            if (certificate) {
                cefaInfo = {
                    area:getCityNameByCode(userInfo.sheng),
                    documentId:userInfo.documentId,
                    memberNum:userInfo.memberNum,
                    session:getEdition(Math.floor(userInfo.session/100), userInfo.session%100 ),
                    lifespanTime:`${moment(userInfo.lifespanStartTime).format("YYYY年MM月DD日")}至${moment(userInfo.lifespanEndTime).format("YYYY年MM月DD日")}`
                }
                msg = ``;
            } else {
                msg = `会员注册尚未缴费，无法下载证书`;
            }
        } else if(userInfo.memberType == MEMBERTYPE.单位会员) {
            //院校无需支付可下载
            if (userInfo.unitMemberType == UNITMEMBERTYPE.院校) certificate = true;
            //机构和其他已支付可下载
            else if (userInfo.paymentStatus != PAYMENTSTATUS.未支付) {
                certificate = true;
            }
            if (certificate) {
                let addresStr = "";
                if (getCityNameByCode(userInfo.sheng) == getCityNameByCode(userInfo.shi)) {
                    addresStr = `${getCityNameByCode(userInfo.shi)}${getCityNameByCode(userInfo.qu)}${userInfo.addres}`;
                } else {
                    addresStr = `${getCityNameByCode(userInfo.sheng)}${getCityNameByCode(userInfo.shi)}${getCityNameByCode(userInfo.qu)}${userInfo.addres}`;
                }
                cefaInfo = {
                    unitName:userInfo.unitName,
                    addres:addresStr,
                    memberNum:userInfo.memberNum,
                    session:getEdition(Math.floor(userInfo.session/100), userInfo.session%100 ),
                    lifespanTime:`${moment(userInfo.lifespanStartTime).format("YYYY年MM月DD日")}至${moment(userInfo.lifespanEndTime).format("YYYY年MM月DD日")}`
                }
                if (userInfo.unitMemberType == UNITMEMBERTYPE.院校) {
                    let diffYearNum = moment().diff(moment(userInfo.lifespanStartTime), 'years');
                    let startTimeStr = moment(userInfo.lifespanStartTime).add(diffYearNum, 'years').format("YYYY年MM月DD日");
                    let endTimeStr = moment(userInfo.lifespanStartTime).add(diffYearNum+1, 'years').format("YYYY年MM月DD日");
                    cefaInfo.lifespanTime = `${startTimeStr}至${endTimeStr}`;
                }
                msg = ``;
            } else {
                msg = `会员注册尚未缴费，无法下载证书`;
            }
        }
    }
    
    return {certificate, cefaInfo, msg};
}


/**
 * 理事、常务理事证明函下载
 * @param param0 
 * @returns 
 */
export async function getCertificateType({userId}) {
    const Files = ["userId", "memberLevel", "changeApplyType", "applyApplicationTime", "unitName", "name", "beforeChange", "memberType"];
    let userInfo = await findOnce(TABLEENUM.用户表, {userId}, Files);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let certificate = false;//是否可以下载
    let cefaInfo:any = {};
    let msg = '会员理事审核未通过，无法下载证明函';
    //判断是否审批通过
    if (userInfo.beforeChange) {
        if (userInfo.changeApplyType == CHANGEAPPLYTYPE.通过) {
            if(userInfo.memberLevel == MEMBERLEVEL.理事会员 || userInfo.memberLevel == MEMBERLEVEL.常务理事会员) certificate = true
            if (certificate) {
                cefaInfo = {
                    memberLevel:changeEnumValue(MEMBERLEVEL, userInfo.memberLevel),
                    name:userInfo.name,
                    unitName:userInfo.unitName,
                    applyApplicationTime: ""
                }
                if (userInfo.applyApplicationTime) cefaInfo.applyApplicationTime = moment(userInfo.applyApplicationTime).format("YYYY年MM月DD日")
                msg = ``;
            }
        } else if (userInfo.changeApplyType == CHANGEAPPLYTYPE.注册信息待补充) {
            msg = `会员注册信息待补充，无法下载证明函`;
        } else if (userInfo.changeApplyType == CHANGEAPPLYTYPE.待审批) {
            msg = `会员理事审核中，无法下载证明函`;
        }
    } else {
        if(userInfo.memberLevel == MEMBERLEVEL.理事会员 || userInfo.memberLevel == MEMBERLEVEL.常务理事会员) certificate = true
        if (certificate) {
            let name = "";
            if (userInfo.memberType == MEMBERTYPE.个人会员) name = userInfo.name;
            else name = userInfo.unitName;
            cefaInfo = {
                memberLevel:changeEnumValue(MEMBERLEVEL, userInfo.memberLevel),
                name,
                applyApplicationTime: ""
            }
            if (userInfo.applyApplicationTime) cefaInfo.applyApplicationTime = moment(userInfo.applyApplicationTime).format("YYYY年MM月DD日")
            msg = ``;
        }
    }

    return {certificate, cefaInfo, msg};
}


/**
 * 能否申请变更理事
 * @param userId 登录的userid
 * @returns 
 */
export async function getApply({userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    const NowMs = new Date().valueOf();
    let isApply = true;

    let time = moment(1747895510765).format("YYYY-MM-dd")

    if (oldInfo.memberType == MEMBERTYPE.个人会员) {
        if(oldInfo.lifespanEndTime) {
            // 会员有效期结束时间小于当前时间的欠费会员
            if(oldInfo.memberState == MEMBERSTATE.异常 || oldInfo.lifespanEndTime < NowMs) isApply = false; 
        }
    }
    
    return {isApply};
}


/**
 * 变更理事申请，职位未发生变更不需要走当前流程
 * @param memberLevel 变更理事 
 * @param userId 登录的userid
 * @returns 
 */
export async function memberlevelUpdate({memberLevel, userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    if (oldInfo.memberLevel == memberLevel) throw new BizError(ERRORENUM.当前变更申请未发生变化);
    if (memberLevel > oldInfo.memberLevel +1) throw new BizError(`当前职位为：${oldInfo.memberLevel}，申请${memberLevel}${ERRORENUM.超出可申请范围}`);

    /**添加至变更职位 */
    eccEnumValue("变更申请", '变更申请职位' , MEMBERLEVELCHANGE, memberLevel); //校验枚举
    
    let param = {
        applyMemberLevel:memberLevel, 
        beforeChange:oldInfo.memberLevel,
    }
    await updateOneData(TABLEENUM.用户表, {userId}, param);

    return successResult();
}


/**
 * 是否需要补充用户信息
 * 判断注册资料是否完整，不完整返回false(需要补充用户信息)
 * @param userId 登录的userid
 */
export async function isNeedSupplement({userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});

    const GrRequiredConf = {
        "基本信息": ["name", "sex", "documentId", "documentType", "birth", "nation", "sheng", "shi", "qu", "addres", "education", "photoUrl"],
        "专业信息": ["duties", "workTitle", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF", "profCategory"],
        "其他附件": ["cardUrlJust", "cardUrlBack", "academicCERTUrl"]
    };

    const DwRequiredConf = {
        "基本信息": ["unitName", "sheng", "shi", "qu", "addres", "uscc", "legalPerson", "legalPersonPhone", "legalPersonMail", "contactPerson", 
        "contactPersonDuties", "contactPersonPhone", "uusinessLicenseUrl"],
        "单位信息": ["unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", 
        "yuanXiaoFuZeRenDianHua", "yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", 
        "yuanXiaoKeYanFuZeRenDianHua", "jiaoXueFuZeRenXinMing", "jiaoXueFuZeRenDianHua"]
    };

    const Dwshzycj = {
        "单位所获主要成绩及科研成果": ["startTime", "endTime", "describe"]
    };

    let dwshzycjInfo = await findOnce(TABLEENUM.单位所获得科研成果表, {userId});

    let infoCompleteData = {};
    let changeApplyType = CHANGEAPPLYTYPE.注册信息补充完成;
    if (oldInfo.memberType == MEMBERTYPE.个人会员) {
        for (let key in GrRequiredConf) {
            for (let i = 0; i < GrRequiredConf[key].length; i++) {
                if(!oldInfo[GrRequiredConf[key][i]]) {
                    infoCompleteData[key] = false;
                    changeApplyType = CHANGEAPPLYTYPE.注册信息待补充
                } else {
                    infoCompleteData[key] = true;
                }
            }
        }
        
    } else {
        for (let key in DwRequiredConf) {
            for (let i = 0; i < DwRequiredConf[key].length; i++) {
                if(!oldInfo[DwRequiredConf[key][i]]) {
                    infoCompleteData[key] = false;
                    changeApplyType = CHANGEAPPLYTYPE.注册信息待补充
                } else {
                    infoCompleteData[key] = true;
                }
            }
        }
        for (let i = 0; i < Dwshzycj.单位所获主要成绩及科研成果.length; i++) {
            if (!dwshzycjInfo) {
                infoCompleteData["单位所获主要成绩及科研成果"] = false;
            } else {
                if(!dwshzycjInfo[Dwshzycj.单位所获主要成绩及科研成果[i]]) {
                    infoCompleteData["单位所获主要成绩及科研成果"] = false;
                    changeApplyType = CHANGEAPPLYTYPE.注册信息待补充
                } else {
                    infoCompleteData["单位所获主要成绩及科研成果"] = true;
                }
            }
            
        }
    }

    let infoComplete = [];
    for (let key in infoCompleteData) {
        infoComplete.push({key, value:infoCompleteData[key]})
    }

    return infoComplete;
}


/**
 * 个人会员用户注册信息补充
 * @param userId 登录的userid
 * @param form 补充的信息表单
 * @returns 
 */
export async function infoSupplement({form, userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    /**校验枚举 */
    const EccFuncName = '个人会员用户注册信息补充';
    eccEnumValue(EccFuncName, '性别', SEX, form.sex);
    eccEnumValue(EccFuncName, '证件类型', DOCUMENTTYPE, form.documentType);
    eccEnumValue(EccFuncName, '民族', NATION, form.nation);
    eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);

    await updateOneData(TABLEENUM.用户表, {userId}, form);

    return successResult();
}


/**
 * 单位会员用户注册信息补充
 * @param userId 登录的用户id
 * @param form 补充的信息表单
 * @returns 
 */
export async function unitInfoSupplement({form, keyanForm, userId}) {
    const keyanFormItemConfig = {
        startTime: 'Number',
        endTime: 'Number',
        describe: 'String'
    };
    keyanForm.forEach(item => {
        eccFormParam("单位会员用户注册信息补充", keyanFormItemConfig, item );
    });
    
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    /**校验枚举 */
    const EccFuncName = '单位会员用户注册信息补充';
    eccEnumValue(EccFuncName, '单位信息类型', UNITMEMBERTYPE, form.unitMemberType);

    /**确保邮箱的唯一性 */
    // let distinctMailInfo = await findOnce(TABLEENUM.用户表, {mail:form.unitMail}, ["userId"]);
    // if (distinctMailInfo && distinctMailInfo.userId && distinctMailInfo.userId != oldInfo.userId) throw new BizError(ERRORENUM.邮箱重复, oldInfo.loginId, oldInfo.mail );
    form.mail = form.unitMail;
    /**修改会员用户信息 */
    await updateOneData(TABLEENUM.用户表, {userId}, form);

    /**删除对应userId科研成果 */
    let oldKeYanList= await find(TABLEENUM.单位所获得科研成果表, {userId});
    if (oldKeYanList && oldKeYanList.length) {
        await deleteManyData(TABLEENUM.单位所获得科研成果表, {userId});
    }
    
    /**添加新的科研信息 */
    let addList = [];
    for (let i = 0; i < keyanForm.length; i++) {
        let { startTime, endTime, describe } = keyanForm[i];
        addList.push({
            id:generateSystemId(TABLEENUM.单位所获得科研成果表, userId),
            userId,
            startTime, endTime, describe
        });
    }
    await addManyData(TABLEENUM.单位所获得科研成果表, addList);

    return successResult();
}


/**
 * 变更理事申请理由
 * @param applyStr 变更申请理由
 * @param userId 登录的userid
 * @returns 
 */
export async function applyReason({applyStr, userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    const Now = new Date().valueOf();
    let applyId = generateSystemId(TABLEENUM.理事变更审批历史表, userId);
    let param = {
        applyStr,
        changeApplyType:CHANGEAPPLYTYPE.待审批,
        applyApplicationTime:Now,
        applyId,
    }
    await updateOneData(TABLEENUM.用户表, {userId}, param);
    
    /**添加审批历史 */
    let applyInfo:any = {
        applyId,
        userId,
        applyMemberLevel:oldInfo.applyMemberLevel,
        beforeChange:oldInfo.beforeChange,
        applyStr,
        changeApplyType:CHANGEAPPLYTYPE.待审批,
        applyApplicationTime:Now,
    };
    await addOneData(TABLEENUM.理事变更审批历史表, applyInfo);

    return successResult();
}










