/**
 * 变更审批
 */

import moment = require("moment");
import { BANXUELEIXING, CERTIFICATETYPE, CHANGEAPPLYTYPE, CLIENTMSGLABLE, INDIVIDUALMEMBERTYPE, INFOCHANGEAPPLYTYPE, MAILTYPE, MEMBERLEVEL, MEMBERSTATE, MEMBERTYPE, STATE, UNITMEMBERTYPE } from "../../config/enum";
import { TABLEENUM } from "../../data/models/model";
import { find, findCount, findOnce, findOnceToSort, findToPage, findToSort, findToSortToPage } from "../../data/select";
import { extractData } from "../../util/piecemeal";
import { changeEnumValue } from "../../util/verificationEnum";
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";
import { generateSystemId, getMenberNum, successResult } from "../../tools/system";
import { updateOneData } from "../../data/update";
import { setEnumInterface } from "../public";
import { addOneData } from "../../data/add";
import { systemSendMail } from "../mail";


/**
 * 变更审批列表
 * @param name 单位名称，名称 
 * @param joinStartTime 入会开始时间
 * @param joinEndTime 入会结束时间
 * @param memberCategory 会员类别 UNITMEMBERTYPE INDIVIDUALMEMBERTYPE 前端用：MEMBERTYPEECCENUM
 * @param beforeChange 变更前会员
 * @param memberLevel 申请变更会员
 * @returns 
 */
export async function applyList({name, joinStartTime, joinEndTime, memberCategory, beforeChange, memberLevel, pageNumber, pageSize}) {
    let selectParam:any = {
        isBlackUser:STATE.否,
        changeApplyType:{"$gt":CHANGEAPPLYTYPE.注册信息补充完成} //返回除了补充注册信息之外的所有状态数据
    };
    if (name) {
        selectParam["$and"] = [{
            "$or":[
                {unitName:{"$regex":`${name}`}},
                {name:{"$regex":`${name}`}}
            ]
        }]
    }
    if (joinStartTime) {
        selectParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!selectParam["joinTime"]) selectParam["joinTime"] = {};
        selectParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (memberCategory) {
        if ( memberCategory >= 9) selectParam.unitMemberType = memberCategory;
        else selectParam.individualMemberType = memberCategory;
    }
    if (memberLevel && memberLevel.length) selectParam.applyMemberLevel = {"$in":memberLevel};
    if (beforeChange && beforeChange.length) selectParam.beforeChange = {"$in":beforeChange};

    let selectConf = ["userId", "applyId", "changeApplyType", "unitName", "name", "beforeChange", "applyMemberLevel", "applyStr", "applyApplicationTime", "applyReviewTime", "individualMemberType", "unitMemberType", "memberType"];
    let dbList = await findToSortToPage(TABLEENUM.用户表, selectParam, selectConf, {applyApplicationTime:-1}, pageNumber, pageSize);
    let dataCount = await findCount(TABLEENUM.用户表, selectParam);

    let dataList = [];

    let itemConf = ["userId", "applyId", "changeApplyType", "unitName", "name", "beforeChange", "applyMemberLevel", "applyStr", "applyApplicationTime", "applyReviewTime", "memberType"];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let item:any = extractData(info, itemConf);
        item.changeApplyType = changeEnumValue(CHANGEAPPLYTYPE, item.changeApplyType);
        item.memberType = changeEnumValue(MEMBERTYPE, item.memberType);

        let applyMemberLevel = "";
        if (!item.applyMemberLevel) applyMemberLevel = "未选择";
        else applyMemberLevel = changeEnumValue(MEMBERLEVEL, item.applyMemberLevel)
        if (!item.beforeChange) item.beforeChange = "未选择";
        else item.beforeChange = changeEnumValue(MEMBERLEVEL, item.beforeChange)
        // MEMBERTYPEECCENUM
        let memberCategory = "";
        if (info.memberType == MEMBERTYPE.个人会员) {
            memberCategory = changeEnumValue(INDIVIDUALMEMBERTYPE, info.individualMemberType);//会员类别/级别
        }
        else{
            memberCategory = changeEnumValue(UNITMEMBERTYPE, info.unitMemberType);//会员类别/级别
        }
        item.memberCategory = `${memberCategory}${applyMemberLevel}`;
        item.applyApplicationTime = moment(item.applyApplicationTime).format("YYYY-MM-DD");
        item.applyReviewTime = item.applyReviewTime ? moment(item.applyReviewTime).format("YYYY-MM-DD") : '-';

        dataList.push(item);
    }

    return {dataList, dataCount};
}


/**
 * 通过
 * @param id 待审核列表返回的用户id 
 * @returns 
 */
 export async function applyAdopt({id}) {
    // let selectConf = [];
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id, isAdmin:STATE.否});
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.注册信息待补充) {
        throw new BizError(ERRORENUM.注册信息待补充, `${userInfo.userId}用户注册信息未补充完整`);
    }
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.驳回修改) {
        throw new BizError(ERRORENUM.不具备审批条件, `${userInfo.userId}当前状态为驳回修改`);
    }
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.通过) {
        throw new BizError(ERRORENUM.重复提交, `${userInfo.userId}当前状态为已通过`);
    }

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

    let lableInfo = userInfo.lableId.toObject() || [];
    let newLable;
        if (userInfo.applyMemberLevel == MEMBERLEVEL.理事会员) {
            newLable = lableInfo.filter( (item) => {
                return item !== CLIENTMSGLABLE.驳回理事申请;
            })
            if (!newLable.includes(CLIENTMSGLABLE.通过理事申请)) {
                newLable.push(CLIENTMSGLABLE.通过理事申请);
            }
        } else if (userInfo.applyMemberLevel == MEMBERLEVEL.常务理事会员) {
            newLable = lableInfo.filter( (item) => {
                return item !== CLIENTMSGLABLE.驳回常务理事申请;
            })
            if (!newLable.includes(CLIENTMSGLABLE.通过常务理事申请)) {
                newLable.push(CLIENTMSGLABLE.通过常务理事申请);
            }
        }
    let lableId = newLable;

    let updateInfo:any = {
        memberLevel:userInfo.applyMemberLevel,
        applyReviewTime:NowMs,
        changeApplyType:CHANGEAPPLYTYPE.通过,
        lableId
    };
    await updateOneData(TABLEENUM.用户表, {userId:id}, updateInfo);
    /**添加审批历史 */
    await updateOneData(TABLEENUM.理事变更审批历史表, {applyId:userInfo.applyId}, updateInfo);

    //发送邮件
    await systemSendMail(id, MAILTYPE.变更已通过 );

    return successResult();
}


/**
 * 批量通过
 * @param param0 
 */
export async function applyBatchAdopt({idList}) {
    //限制长度
    if (idList.length > 50) throw new BizError(ERRORENUM.批量操作超过个数限制);

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

    for (let i = 0; i < idList.length; i++) {
        let id = idList[i];
        if (!id) continue;//空id跳过

        let userInfo = await findOnce(TABLEENUM.用户表, {userId:id, isAdmin:STATE.否});
        if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
        if (userInfo.changeApplyType == CHANGEAPPLYTYPE.注册信息待补充) {
            throw new BizError(ERRORENUM.注册信息待补充, `${userInfo.userId}用户注册信息未补充完整`);
        }
        if (userInfo.changeApplyType == CHANGEAPPLYTYPE.驳回修改) {
            throw new BizError(ERRORENUM.不具备审批条件, `${userInfo.userId}当前状态为驳回修改`);
        }
        if (userInfo.changeApplyType == CHANGEAPPLYTYPE.通过) {
            throw new BizError(ERRORENUM.重复提交, `${userInfo.userId}当前状态为已通过`);
        }

        let lableInfo = userInfo.lableId.toObject() || [];
        let newLable;
        if (userInfo.applyMemberLevel == MEMBERLEVEL.理事会员) {
            newLable = lableInfo.filter( (item) => {
                return item !== CLIENTMSGLABLE.驳回理事申请;
            })
            if (!newLable.includes(CLIENTMSGLABLE.通过理事申请)) {
                newLable.push(CLIENTMSGLABLE.通过理事申请);
            }
        } else if (userInfo.applyMemberLevel == MEMBERLEVEL.常务理事会员) {
            newLable = lableInfo.filter( (item) => {
                return item !== CLIENTMSGLABLE.驳回常务理事申请;
            })
            if (!newLable.includes(CLIENTMSGLABLE.通过常务理事申请)) {
                newLable.push(CLIENTMSGLABLE.通过常务理事申请);
            }
        }

        let lableId = newLable;

        let updateInfo:any = {
            memberLevel:userInfo.applyMemberLevel,
            applyReviewTime:NowMs,
            changeApplyType:CHANGEAPPLYTYPE.通过,
            lableId,
        };
        await updateOneData(TABLEENUM.用户表, {userId:id}, updateInfo);
        /**添加审批历史 */
        await updateOneData(TABLEENUM.理事变更审批历史表, {applyId:userInfo.applyId}, updateInfo);

        //发送邮件
        await systemSendMail(id, MAILTYPE.变更已通过 );

    }

    return successResult();
}


/**
 * 驳回 success
 * @param userId 
 * @param remarks 驳回理由
 * @returns 
 */
export async function applyReject({id, remarks}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:id, isAdmin:STATE.否});
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.注册信息待补充) {
        throw new BizError(ERRORENUM.注册信息待补充, `${userInfo.userId}用户注册信息未补充完整`);
    }
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.驳回修改) {
        throw new BizError(ERRORENUM.不具备审批条件, `${userInfo.userId}当前状态为驳回修改`);
    }
    if (userInfo.changeApplyType == CHANGEAPPLYTYPE.通过) {
        throw new BizError(ERRORENUM.重复提交, `${userInfo.userId}当前状态为已通过`);
    }

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

    let lableInfo = userInfo.lableId.toObject() || [];
    let newLable;
    if (userInfo.applyMemberLevel == MEMBERLEVEL.理事会员) {
        newLable = lableInfo.filter( (item) => {
            return item !== CLIENTMSGLABLE.通过理事申请;
        })
        if (!newLable.includes(CLIENTMSGLABLE.驳回理事申请)) {
            newLable.push(CLIENTMSGLABLE.驳回理事申请);
        }
    } else if (userInfo.applyMemberLevel == MEMBERLEVEL.常务理事会员) {
        newLable = lableInfo.filter( (item) => {
            return item !== CLIENTMSGLABLE.通过常务理事申请;
        })
        if (!newLable.includes(CLIENTMSGLABLE.驳回常务理事申请)) {
            newLable.push(CLIENTMSGLABLE.驳回常务理事申请);
        }
    }
    
    let lableId = newLable;

    let updateInfo:any = {
        applyReviewTime:NowMs,
        changeApplyType:CHANGEAPPLYTYPE.驳回修改,
        lableId,
        rejectRemarks:remarks
    };
    await updateOneData(TABLEENUM.用户表, {userId:id}, updateInfo);
    /**添加审批历史 */
    let applyInfo = {
        applyReviewTime:NowMs,
        changeApplyType:CHANGEAPPLYTYPE.驳回修改,
        rejectRemarks:remarks
    }
    await updateOneData(TABLEENUM.理事变更审批历史表, {applyId:userInfo.applyId}, applyInfo);
    /**重置消息为未读 */
    let msgInfo;
    if (userInfo.applyMemberLevel == MEMBERLEVEL.理事会员) {
        msgInfo = await findOnce(TABLEENUM.消息通知表, {lableId:{"$in":CLIENTMSGLABLE.驳回理事申请}});
    } else if (userInfo.applyMemberLevel == MEMBERLEVEL.常务理事会员) {
        msgInfo = await findOnce(TABLEENUM.消息通知表, {lableId:{"$in":CLIENTMSGLABLE.驳回常务理事申请}});
    }
    
    await updateOneData(TABLEENUM.消息已读状态表, {userId:id, msgId:msgInfo.msgId}, {isRead: STATE.否});

    //发送邮件
    await systemSendMail(id, MAILTYPE.变更驳回 );

    return successResult();
}


/**
 * 变更审批数据导出
 * @param param0 
 * @returns 
 */
export async function outPutApply() {
    // let exportColumns:any = setEnumInterface({defaultParam:APPLYCOLUMNS});
    let selectParam = {
        isAdmin:STATE.否, 
        changeApplyType:{"$gt":CHANGEAPPLYTYPE.注册信息补充完成} //返回除了补充注册信息之外的所有状态数据
    };
    
    let selectTitle = ["序号", "状态", "单位/个人名称", "变更前职位", "申请变更职位", "申请理由", "申请时间", "审核时间"];
    let selectConf = ["changeApplyType", "unitName", "name", "memberType", "beforeChange", "applyMemberLevel", "applyStr", "applyApplicationTime", "applyReviewTime"];

    let dbList = await find(TABLEENUM.用户表, selectParam, selectConf);
    
    let timeChnageList = ["applyApplicationTime", "applyReviewTime"];

    let dataList = [selectTitle];
    let dataConf = ["changeApplyType", "name", "beforeChange", "applyMemberLevel", "applyStr", "applyApplicationTime", "applyReviewTime"];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let subList = [ (i+1).toString() ];
        for (let i = 0; i < dataConf.length; i++) {
            let key = dataConf[i];
            let value = info[key] || "";
            if (key == "name") {
                if (info.memberType == MEMBERTYPE.个人会员) value = info.name;
                else if (info.memberType == MEMBERTYPE.单位会员) value = info.unitName;
            }
            if (value) {
                if (timeChnageList.indexOf(key) != -1) value = moment(value).format("YYYY-MM-DD");
                else if (key == "applyMemberLevel") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "beforeChange") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "changeApplyType") value = changeEnumValue(CHANGEAPPLYTYPE, value);
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList};
}


/**
 * 审核历史 success
 * @param userId
 * @returns 
 */
 export async function applyHistoryList({id}) {
    let dbList = await find(TABLEENUM.理事变更审批历史表, {userId:id});

    let dataList = [];
    dbList.forEach(info => {
        let item:any = extractData(info, ["changeApplyType", "applyReviewTime", "rejectRemarks", "applyStr"]);
        item.changeApplyType = changeEnumValue(CHANGEAPPLYTYPE, item.changeApplyType);
        item.applyReviewTime = moment(item.applyReviewTime).format("YYYY-MM-DD");
        if (!item.applyStr) item.applyStr = "-" 
        if (!item.rejectRemarks) item.rejectRemarks = "-" 
        dataList.push(item);
    });

    return {dataList};
}


//==========================资料变更

/**
 * 资料审批列表 success
 * @param name 名称关键词
 * @param changeState 审核状态
 * @param unitMemberType 会员类别
 * @param uscc 统一信用代码
 * @param legalPerson 法人代表
 * @param legalPersonPhone 法人联系电话
 * @param legalPersonMail 法人邮箱
 * @returns 
 */
export async function infomationChangeList({name, changeState, unitMemberType, uscc, legalPerson, legalPersonPhone, legalPersonMail, pageSize, pageNumber}) {
    let selectParam:any = {memberType:MEMBERTYPE.单位会员, infoChangeId:{"$ne":null}};
    let selectHistoryParam:any = {}
    if (name) {
        selectParam.unitName = {"$regex":name}
    }
    if (changeState) {
        selectParam.infoChangeOptionType = changeState;
    }

    if (unitMemberType) {
        selectParam
    }
    
    let dbList = await findToSortToPage(TABLEENUM.用户表, selectParam, ["userId", "memberType", "userId", "unitName", "infoChangeId", "uscc", "legalPerson", "unitMemberType", "yuanXiaoBanXueLeiXing"], {infoChangeMs:-1}, pageNumber, pageSize);
    let dataCount = await findCount(TABLEENUM.用户表, selectParam);

    let dataList = [];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i]; 
        let itemFileList = ["unitName","uscc", "legalPerson", "yuanXiaoBanXueLeiXing", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId", "yuanXiaoBanXueLeiXing", "legalPersonMail", "legalPersonPhone"];
        let logInfo = await findOnceToSort(TABLEENUM.资料变更审批历史表, {infoChangeId:info.infoChangeId}, {createTimeMs:-1}, itemFileList);
        let yuanXiaoBanXueLeiXing= logInfo.yuanXiaoBanXueLeiXing || info.yuanXiaoBanXueLeiXing;
        let item = {                               
            infoChangeOptionType:changeEnumValue(INFOCHANGEAPPLYTYPE, logInfo.infoChangeOptionType),
            infoChangeId:info.infoChangeId,
            unitName:logInfo.unitName,
            uscc:logInfo.uscc,
            legalPerson:logInfo.legalPerson,
            unitMemberType:changeEnumValue(UNITMEMBERTYPE, logInfo.unitMemberType),
            uusinessLicenseUrl:logInfo.uusinessLicenseUrl,
            applicationForm:logInfo.applicationForm,
            yuanXiaoBanXueLeiXing:changeEnumValue(BANXUELEIXING, yuanXiaoBanXueLeiXing),
            desc:logInfo.desc,
            unitNameChange:false,
            usccChange:false,
            unitMemberTypeChange:false,
            legalPersonChange:false,
            yuanXiaoBanXueLeiXingChange:false,
            memberType:changeEnumValue(MEMBERTYPE, info.memberType),
            userId:info.userId,
            legalPersonMail:logInfo.legalPersonMail || '',
            legalPersonPhone:logInfo.legalPersonPhone || '',
            legalPersonMailChange:false,
            legalPersonPhoneChange:false,
            rejectRemarks:logInfo.rejectRemarks || ""
        };
        if (logInfo.unitName != info.unitName) item.unitNameChange = true;
        if (logInfo.uscc != info.uscc) item.usccChange = true;
        if (logInfo.unitMemberType != info.unitMemberType) item.unitMemberTypeChange = true;
        if (logInfo.legalPerson != info.legalPerson) item.legalPersonChange = true;
        if (logInfo.yuanXiaoBanXueLeiXing != info.yuanXiaoBanXueLeiXing) item.yuanXiaoBanXueLeiXingChange = true;
        if (logInfo.legalPersonMail != info.legalPersonMail) item.legalPersonMailChange = true;
        if (logInfo.legalPersonPhone != info.legalPersonPhone) item.legalPersonPhoneChange = true;
        if (item.infoChangeOptionType == "驳回修改") item.infoChangeOptionType = "已驳回"; // 2025.02.25【驳回修改】文字修改为【已驳回】
        dataList.push(item);
    }

    return {dataList, dataCount};
}


export async function infomationChangePass({infoChangeId}) {
    let selectParam:any = {infoChangeId};
    let fileList = ["userId","unitName", "uscc", "legalPerson", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId", "legalPersonPhone", "legalPersonMail", "yuanXiaoBanXueLeiXing"];
    let onceData = await findOnceToSort(TABLEENUM.资料变更审批历史表, selectParam, {createTimeMs:-1},fileList);
    if (!onceData || !onceData.infoChangeId) throw new BizError(ERRORENUM.目标数据不存在);
    
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:onceData.userId}, ["infoChangeId", "infoChangeOptionType", "userId"]);
    if (userInfo.infoChangeOptionType == INFOCHANGEAPPLYTYPE.通过) {
        throw new BizError(ERRORENUM.不可重复提交);
    }


    //添加日志
    let applyInfo:any = {
        infoChangeId,
        applyId:generateSystemId(TABLEENUM.资料变更审批历史表, onceData.userId),
        userId:onceData.userId,
        unitName:onceData.unitName,
        infoChangeOptionType:INFOCHANGEAPPLYTYPE.通过,
        uscc:onceData.uscc, 
        legalPerson:onceData.legalPerson, 
        unitMemberType:onceData.unitMemberType, 
        uusinessLicenseUrl:onceData.uusinessLicenseUrl, 
        applicationForm:onceData.applicationForm, 
        yuanXiaoBanXueLeiXing:onceData.yuanXiaoBanXueLeiXing,
        legalPersonMail:onceData.legalPersonMail || '',
        legalPersonPhone:onceData.legalPersonPhone || '',
        desc:onceData.desc,
        createTimeMs:new Date().valueOf()
    };
    await addOneData(TABLEENUM.资料变更审批历史表, applyInfo);

    let updateInfo = {
        infoChangeOptionType:INFOCHANGEAPPLYTYPE.通过,
        unitName:onceData.unitName,
        uscc:onceData.uscc,
        legalPerson:onceData.legalPerson,
        unitMemberType:onceData.unitMemberType,
        uusinessLicenseUrl:onceData.uusinessLicenseUrl,
        applicationForm:onceData.applicationForm,
        yuanXiaoBanXueLeiXing:onceData.yuanXiaoBanXueLeiXing,
        legalPersonMail:onceData.legalPersonMail,
        legalPersonPhone:onceData.legalPersonPhone,
    };
    await updateOneData(TABLEENUM.用户表, {userId:onceData.userId}, updateInfo);
    
    //发送邮件
    await systemSendMail(userInfo.userId, MAILTYPE.变更已通过 );

    return successResult();
}

export async function infomationChangeOut({infoChangeId, rejectRemarks}) {
    let selectParam:any = {infoChangeId};
    let fileList = ["userId","unitName", "uscc", "legalPerson", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId", "legalPersonPhone", "legalPersonMail", "yuanXiaoBanXueLeiXing"];
    let onceData = await findOnceToSort(TABLEENUM.资料变更审批历史表, selectParam, {createTimeMs:-1},fileList);
    if (!onceData || !onceData.infoChangeId) throw new BizError(ERRORENUM.目标数据不存在);
    
    // let userInfo = await findOnce(TABLEENUM.用户表, {userId:onceData.userId}, ["infoChangeId", "infoChangeOptionType"]);
    if (onceData.infoChangeOptionType == INFOCHANGEAPPLYTYPE.驳回修改) {
        throw new BizError(ERRORENUM.不可重复提交);
    }

    //添加日志
    let applyInfo:any = {
        infoChangeId,
        applyId:generateSystemId(TABLEENUM.资料变更审批历史表, onceData.userId),
        userId:onceData.userId,
        unitName:onceData.unitName,
        infoChangeOptionType:INFOCHANGEAPPLYTYPE.驳回修改,
        uscc:onceData.uscc, 
        legalPerson:onceData.legalPerson, 
        unitMemberType:onceData.unitMemberType, 
        uusinessLicenseUrl:onceData.uusinessLicenseUrl, 
        applicationForm:onceData.applicationForm, 
        desc:onceData.desc,
        yuanXiaoBanXueLeiXing:onceData.yuanXiaoBanXueLeiXing,
        rejectRemarks:rejectRemarks,
        legalPersonMail:onceData.legalPersonMail || '',
        legalPersonPhone:onceData.legalPersonPhone || '',
        createTimeMs:new Date().valueOf()
    };
    await addOneData(TABLEENUM.资料变更审批历史表, applyInfo);

    let updateInfo = {
        infoChangeOptionType:INFOCHANGEAPPLYTYPE.驳回修改,
    };
    await updateOneData(TABLEENUM.用户表, {userId:onceData.userId}, updateInfo);

     //发送邮件
     await systemSendMail(onceData.userId, MAILTYPE.变更驳回 );

    return successResult();
}

export async function infomationChangeLog({infoChangeId}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {infoChangeId}, ["userId", "unitName", "uscc", "unitMemberType", "legalPerson", "yuanXiaoBanXueLeiXing", "legalPersonMail", "legalPersonPhone"]);
    if (!userInfo || !userInfo.userId) {
        throw new BizError(ERRORENUM.不存在审批历史);
    }

    let selectParam:any = {userId:userInfo.userId};
    let fileList = [];
    let dbList = await findToSort(TABLEENUM.资料变更审批历史表, selectParam, {createTimeMs:-1}, fileList);

    let dataList = [];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        // let itemFileList = ["unitName", "uscc", "legalPerson", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId"];
        // let logInfo = await findOnceToSort(TABLEENUM.资料变更审批历史表, {infoChangeId:info.infoChangeId}, {createTimeMs:-1}, itemFileList);
        let infoChangeOptionType = changeEnumValue(INFOCHANGEAPPLYTYPE, info.infoChangeOptionType);
        let desc = "";
        if (INFOCHANGEAPPLYTYPE.待审批 == info.infoChangeOptionType) {
            infoChangeOptionType = "用户-提交";
            desc = info.desc;
        } else if (INFOCHANGEAPPLYTYPE.驳回修改 == info.infoChangeOptionType) {
            desc = info.rejectRemarks;
            infoChangeOptionType = "审核-驳回";
        } else {
            desc = "通过";
            infoChangeOptionType = "审核-通过";
        }

        // let updateInfoStr = "修改了:";
        // if (info.unitName != userInfo.unitName) updateInfoStr += "单位名称";
        // if (info.uscc != userInfo.uscc) updateInfoStr += "统一信用代码";
        // if (info.unitMemberType != userInfo.unitMemberType) updateInfoStr += "单位类型";
        // if (info.legalPerson != userInfo.legalPerson) updateInfoStr += "法人代表";
        // if (info.yuanXiaoBanXueLeiXing != userInfo.yuanXiaoBanXueLeiXing) updateInfoStr += "办学类型";
        // if (info.legalPersonMail != userInfo.legalPersonMail) updateInfoStr += "法人联系邮箱";
        // if (info.legalPersonPhone != userInfo.legalPersonPhone) updateInfoStr += "法人联系电话";
        
        let updateConf = {
            "unitName":"单位名称", 
            "uscc":"统一信用代码", 
            "unitMemberType":"单位类型", 
            "legalPerson":"法人代表", 
            "yuanXiaoBanXueLeiXing":"办学类型", 
            "legalPersonMail":"法人联系邮箱", 
            "legalPersonPhone":"法人联系电话"
        };
        let updateAddress = "";
        let updateInfo = []
        for (let key in updateConf) {
            /**修改前 */
            let updateBeforeInfoStr = ""
            /**修改后 */
            let updateInfoStr = "";
            if (info[key] != userInfo[key]) {
                if (!userInfo[key]) updateBeforeInfoStr = "修改前：-";
                else updateBeforeInfoStr = `修改前：${userInfo[key]}`;
                
                if (!info[key]) updateInfoStr = "修改后：-";
                else updateInfoStr = `修改后：${info[key]}`;
                updateAddress += `${updateConf[key]}、`;
                
                updateInfo.push({ 
                    updateBeforeInfoStr, //修改前
                    updateInfoStr, //修改后
                    updateAddress:updateConf[key] //修改位置
                });
            }
        }

        let item = {
            infoChangeOptionType,
            infoChangeId:info.infoChangeId,
            unitName:info.unitName,
            uscc:info.uscc,
            legalPerson:info.legalPerson,
            unitMemberType:changeEnumValue(UNITMEMBERTYPE, info.unitMemberType),
            uusinessLicenseUrl:info.uusinessLicenseUrl,
            applicationForm:info.applicationForm,
            yuanXiaoBanXueLeiXing:info.yuanXiaoBanXueLeiXing,
            desc,
            time:moment(info.createTimeMs).format("YYYY-MM-DD HH:mm:SS"),
            updateAddress: updateAddress.replace(/、([^、]*)$/, "$1"), //去除末尾的、
            updateInfo
        };

        dataList.push(item);
    }

    return {dataList};
}


export async function infomationChangeManyPass({infoChangeIdList}) {
   if (infoChangeIdList.length > 50) throw new BizError(ERRORENUM.批量操作超过个数限制);
    for (let i = 0; i < infoChangeIdList.length; i++) {
        let infoChangeId = infoChangeIdList[i];
        let selectParam:any = {infoChangeId};
        let fileList = ["userId","unitName", "uscc", "legalPerson", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId"];
        let onceData = await findOnceToSort(TABLEENUM.资料变更审批历史表, selectParam, {createTimeMs:-1},fileList);
        if (!onceData || !onceData.infoChangeId) throw new BizError(ERRORENUM.目标数据不存在);
        
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:onceData.userId}, ["infoChangeId", "infoChangeOptionType"]);
        if (userInfo.infoChangeOptionType == INFOCHANGEAPPLYTYPE.通过) {
            throw new BizError(ERRORENUM.不可重复提交);
        }
    
    
        //添加日志
        let applyInfo:any = {
            infoChangeId,
            applyId:generateSystemId(TABLEENUM.理事变更审批历史表, onceData.userId),
            userId:onceData.userId,
            unitName:onceData.unitName,
            infoChangeOptionType:INFOCHANGEAPPLYTYPE.通过,
            uscc:onceData.uscc, 
            legalPerson:onceData.legalPerson, 
            unitMemberType:onceData.unitMemberType, 
            uusinessLicenseUrl:onceData.uusinessLicenseUrl, 
            applicationForm:onceData.applicationForm, 
            desc:onceData.desc,
            createTimeMs:new Date().valueOf()
        };
        await addOneData(TABLEENUM.理事变更审批历史表, applyInfo);
    
        let updateInfo = {
            infoChangeOptionType:INFOCHANGEAPPLYTYPE.通过,
            unitName:onceData.unitName,
            uscc:onceData.uscc,
            legalPerson:onceData.legalPerson,
            unitMemberType:onceData.unitMemberType,
            uusinessLicenseUrl:onceData.uusinessLicenseUrl,
            applicationForm:onceData.applicationForm
        };
        await updateOneData(TABLEENUM.用户表, {userId:onceData.userId}, updateInfo);

        //发送邮件
        await systemSendMail(onceData.userId, MAILTYPE.变更已通过 );

    }
   

    return successResult();
}


/**
 * 列表 success
 * @param userId
 * @returns 
 */
export async function outPutInfomationChangeList({name, changeState}) {
    let selectParam:any = {state:1, infoChangeId:{"$ne":""}};
    if (name) {
        selectParam.unitName = {"$regex":name}
    }
    if (changeState) {
        selectParam.infoChangeOptionType = changeState;
    }
    let dbList = await find(TABLEENUM.用户表, selectParam, ["userId", "unitName", "infoChangeId"]);

    let dataList = [["状态", "单位会员名称", "统一信用代码", "法人代表", "单位会员类型", "营业执照", "盖章申请表" , "描述"]]; 
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i]; 
        let itemFileList = ["unitName", "uscc", "legalPerson", "unitMemberType", "uusinessLicenseUrl", "applicationForm", "desc", "rejectRemarks", "infoChangeOptionType", "infoChangeId"];
        let logInfo = await findOnceToSort(TABLEENUM.用户表, {infoChangeId:info.infoChangeId}, {createTimeMs:-1}, itemFileList);
        let subList = [
            logInfo.infoChangeOptionType,
            logInfo.unitName,
            logInfo.uscc,
            logInfo.legalPerson,
            logInfo.unitMemberType,
            logInfo.uusinessLicenseUrl,
            logInfo.applicationForm,
            logInfo.desc,
        ]
        dataList.push(subList);
    }

    return {dataList};
}



