/**
 * 会员管理逻辑
 */

import { MEMBERSTATE, MEMBERLEVEL, DOCUMENTTYPE, NATION, PROFCATEGORY, MEMBERTYPE, USERREGISTERSTATE, STATE, ADMINLV, ADMINTYPE, SEX, CERTIFICATETYPE, INDIVIDUALMEMBERTYPE, EDUCATION, UNITMEMBERTYPE, CLIENTMEMBERTYPE, BANXUELEIXING, MEMBERTYPEECCENUM, CLIENTMSGLABLE } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { TABLEENUM } from "../../data/models/model";
import { find, findCount, findOnce, findOnceToSort, findToPage, findToSortToPage } from "../../data/select";
import { updateOneData } from "../../data/update";
import { generateSystemId, getEdition, successResult } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { extractData } from "../../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { addManyData } from "../../data/add";
import { deleteManyData, deleteOneData } from "../../data/delete";
import moment = require("moment");
import { eccCityCode, getCityNameByCode } from "../../config/cityConfig";
import { eccFormParam } from "../../util/verificationParam";

/**
 * 单位会员列表 success
 * @param unitName 单位名称 
 * @param mail 单位邮箱
 * @param phone 登录手机号
 * @param joinStartTime 入会开始时间
 * @param joinEndTime 入会结束时间
 * @param unitMemberType 单位会员所属类型 UNITMEMBERTYPE
 * @param memberLevel 会员等级 职务 MEMBERLEVEL
 * @param session 届次 
 * @param memberState 状态
 * @param sheng 省
 * @param shi 市
 * @param pageNumber 当前页
 */
export async function unitMemberList({unitName, mail, phone, joinStartTime, joinEndTime, unitMemberType, memberLevel, session, memberState, sheng, shi, lableId, yuanXiaoBanXueLeiXing, pageNumber}) {
    let selectParam:any = {
        isAdmin:STATE.否,
        memberType : MEMBERTYPE.单位会员,
        userRegisterState : USERREGISTERSTATE.通过,
        isBlackUser:STATE.否
    };
    if (unitName) selectParam.unitName = {"$regex":unitName};
    if (mail) {
        selectParam.mail = mail;
        selectParam.legalPersonMail = mail; //法人邮箱
        selectParam.ZhuYaoFuZeRenYouXiang = mail; //主要负责人邮箱
    }
    if (phone) {
        selectParam.phone = phone;
        selectParam.legalPersonPhone = phone; //法人联系电话
        selectParam.yuanXiaoFuZeRenDianHua = phone; //院校主要负责人电话
        selectParam.yuanXiaoBanGongFuZeRenDianHua = phone; //院校办公负责人电话
        selectParam.yuanXiaoKeYanFuZeRenDianHua = phone; //院校科研负责人电话
        selectParam.jiaoXueFuZeRenDianHua = phone; //教学负责人电话
    }
    if (joinStartTime) {
        selectParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!selectParam["joinTime"]) selectParam["joinTime"] = {};
        selectParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (unitMemberType.length) selectParam.unitMemberType = {"$in":unitMemberType};
    if (memberLevel.length) selectParam.memberLevel = {"$in":memberLevel};
    if (session) selectParam.session = session;
    if (memberState) selectParam.memberState = memberState;
    if (sheng) selectParam.sheng = sheng;
    if (shi) selectParam.shi = shi;
    if (lableId && lableId.length) selectParam.lableId = {"$in":lableId};
    if (yuanXiaoBanXueLeiXing && yuanXiaoBanXueLeiXing.length) selectParam.yuanXiaoBanXueLeiXing = {"$in":yuanXiaoBanXueLeiXing};
    
    const SelectFiles = ["userId", "memberState", "unitMemberType", "unitName", "contactPerson", "phone", "mail", "sheng", "joinTime", "memberLevel", "lableId", "session", ""];
    let dbList = await findToSortToPage(TABLEENUM.用户表, selectParam, SelectFiles, {joinTime:-1}, pageNumber);
    let dataCount = await findCount(TABLEENUM.用户表, selectParam);

    let dataList = [];

    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let item:any = extractData(info, SelectFiles);
        item.memberState = changeEnumValue(MEMBERSTATE, item.memberState);
        item.unitMemberType = changeEnumValue(MEMBERTYPEECCENUM, item.unitMemberType);
        if (!item.memberLevel) item.memberLevel = "未选择";
        else item.memberLevel = changeEnumValue(MEMBERLEVEL, item.memberLevel);
        item.joinTime = moment(item.joinTime).format("YYYY-MM-DD");
        item.sheng = getCityNameByCode(item.sheng);
        item.lableId = [];
        let lableInfo = await find(TABLEENUM.标签表, {lableId:{"$in":info.lableId}}, ["lableName"]);
        lableInfo.forEach ( lableItem => {
            item.lableId.push(lableItem.lableName);
        });

        item.session = getEdition(Math.floor(item.session/100), item.session%100 );

        dataList.push(item);
    }    

    return {dataList, dataCount};
}


/**
 * 单位会员详情 
 * @param id 会员列表返回的userId 
 * @returns {顶部数据, 基本信息, 单位信息, 单位所获得科研成果}
 * 基本信息: "unitName"：单位名称、原社会信用代码, "uscc"：单位信用代码、原发票抬头, "legalPerson"：法人代表, "legalPersonPhone"：法人代表联系电话, "legalPersonMail"：法人邮箱, "mail"：单位电子邮箱, "contactPerson"：日常联系人, "contactPersonDuties"：日常联系人职务, "phone"：日常联系人电话, "uusinessLicenseUrl"：营业执照图片地址, "addres"：通信地址, "sheng"：省, "shi"：市, "qu"：区, "newUscc"：新社会信用代码, "newUnitName"：新发票抬头
 * 单位信息: "unitMemberType"：单位类型, "yuanXiaoBanXueLeiXing"：办学类型, "yuanXiaoZhuGuanBuMen"：主管部门, "yuanXiaoFuZeRen"：主要负责人姓名, "yuanXiaoFuZeRenZhiWu"：主要负责人职位, "yuanXiaoFuZeRenDianHua"：主要负责人电话, 
"yuanXiaoBanGongFuZeRen"：办公负责人姓名, "yuanXiaoBanGongFuZeRenDianHua"：办公负责人电话, "ZhuYaoFuZeRenYouXiang"：主要负责人邮箱, "yuanXiaoKeYanFuZeRen"：科研负责人姓名, "yuanXiaoKeYanFuZeRenDianHua"：看科研负责人电话,
"jiaoXueFuZeRenXinMing"：教学负责人姓名, "jiaoXueFuZeRenDianHua"：教学负责人电话
 * 单位所获得科研成果: "id", "startTime"：开始时间, "endTime"：结束时间, "describe"：描述
 */

const UnitRegisterConfig = ["phone", "mail", "pwd"];
const UnitBasicConfig = ["userId", "unitName", "uscc", "legalPerson", "legalPersonPhone", "legalPersonMail", "contactPerson", "contactPersonDuties",
"uusinessLicenseUrl", "addres", "sheng", "shi", "qu", "applicationForm"];
const UnitConfig = ["unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", "yuanXiaoFuZeRenDianHua", 
"yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", "yuanXiaoKeYanFuZeRenDianHua",
"jiaoXueFuZeRenXinMing", "jiaoXueFuZeRenDianHua", "kaishezhuanYe", "danWeiJianJie"];

export async function unitMemberDetails({userId, id}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId:id});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    let topInfo:any = extractData(oldInfo, ["session", "memberLevel"]);
    let session = "";
    if (!topInfo.session) session = "";
    else session = getEdition(parseInt(`${topInfo.session/100}`), parseInt(`${topInfo.session%100}`) );
    topInfo.session = session;

    /**处理枚举值 */
    let registerInfo:any = extractData(oldInfo, UnitRegisterConfig);

    /**处理枚举值 */
    topInfo.memberLevel = changeEnumValue(MEMBERLEVEL, topInfo.memberLevel);
    let basicInfo:any = extractData(oldInfo, UnitBasicConfig);
    /**获取订单表新社会信用代码和新发票抬头 */
    let orderInfo = await findOnce(TABLEENUM.订单表, {userId:id});
    if (orderInfo && orderInfo.id) {
        if (!orderInfo.newUscc || ! orderInfo.newUnitName) {
            basicInfo.newUscc = "-";
            basicInfo.newUnitName = "-";
        } else {
            basicInfo.newUscc = orderInfo.newUscc;
            basicInfo.newUnitName = orderInfo.newUnitName;
        }
    } else {
        basicInfo.newUscc = "-";
        basicInfo.newUnitName = "-";
    }
    let unitInfo = extractData(oldInfo, UnitConfig);
    
    let oldKeYanList = await find(TABLEENUM.单位所获得科研成果表, {userId:id}, ["id", "startTime", "endTime", "describe"]);
    let scientificResearch = [];
    oldKeYanList.forEach(info => {
        scientificResearch.push({
            id:info.id,
            startTime:info.startTime,
            endTime:info.endTime,
            describe:info.describe
        });
    })

    /**按钮权限 */
    let userInfo = await findOnce(TABLEENUM.用户表, {userId});
    let permission = [];
    if (userInfo.adminLv.indexOf(ADMINLV.会员信息修改) > -1 ) {
        permission.push(ADMINLV.会员信息修改);
    }
    if (userInfo.adminLv.indexOf(ADMINLV.单位会员申请表) > -1 ) {
        permission.push(ADMINLV.单位会员申请表);
    }

    return {topInfo, registerInfo, basicInfo, unitInfo, scientificResearch, permission};
}


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

    /**校验枚举 */
    const EccFuncName = '单位会员修改';
    /**校验入参 */
    if (form.sheng && form.shi && form.qu) eccCityCode(form.sheng, form.shi, form.qu);
    if (form.sex) eccEnumValue(EccFuncName, '性别', SEX, form.sex);
    if (form.documentType) eccEnumValue(EccFuncName, '证件类型', DOCUMENTTYPE, form.documentType);
    if (form.nation) eccEnumValue(EccFuncName, '民族', NATION, form.nation);
    if (form.profCategory) eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    
    /**修改会员用户信息 */
    let distinctMailInfo = await findOnce(TABLEENUM.用户表, {mail:form.mail}, ["userId"]);
    if (distinctMailInfo && distinctMailInfo.userId && distinctMailInfo.userId != oldInfo.userId) {
        // throw new BizError(ERRORENUM.邮箱重复, oldInfo.loginId, oldInfo.mail );
    }
    // form.phone = form.phone;
    // form.mail = form.mail;
    // form.pwd = form.pwd;
    await updateOneData(TABLEENUM.用户表, {userId:id}, form);

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

    return successResult();
}


/**
 * 删除单位所获得科研成果
 * @param id 科研成果返回的id 
 * @returns 
 */
export async function delResearch({id}) {
    let dataInfo = await findOnce(TABLEENUM.单位所获得科研成果表, {id});
    if (!dataInfo || !dataInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    await deleteOneData(TABLEENUM.单位所获得科研成果表, {id});
    return successResult();
}


/**
 * 个人会员列表
 * @param name 真实姓名
 * @param documentId 身份证
 * @param phone 登录手机号
 * @param mail 个人邮箱
 * @param joinStartTime 入会开始时间
 * @param joinEndTime 入会结束时间
 * @param individualMemberType 个人会员类型（会员级别）
 * @param memberLevel 会员职务 多选
 * 会员级别/职务：【普通会员、理事会员、常务理事会员】
 * @param session 届次 
 * @param profCategory 专业 PROFCATEGORY
 * @param memberState 状态
 * @param sheng 省
 * @param shi 市
 */
export async function individualMemberList({name, documentId, phone, mail, joinStartTime, joinEndTime, individualMemberType, memberLevel, session, profCategory, memberState, sheng, shi, lableId, unitName, pageNumber}) {
    let selectParam:any = {
        memberType : MEMBERTYPE.个人会员,
        userRegisterState : USERREGISTERSTATE.通过,
        isBlackUser:STATE.否
    };
    if (name) selectParam.name = {"$regex":name};

    if (documentId) selectParam.documentId = documentId;
    if (phone) selectParam.phone = phone;
    if (mail) selectParam.mail = mail;
    if (joinStartTime) {
        selectParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!selectParam["joinTime"]) selectParam["joinTime"] = {};
        selectParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (individualMemberType && individualMemberType.length) selectParam.individualMemberType = {"$in":individualMemberType};
    if (memberLevel && memberLevel.length) selectParam.memberLevel = {"$in":memberLevel};
    if (session) selectParam.session = session;
    if (profCategory && profCategory.length) selectParam.profCategory = {"$in":profCategory};
    if (memberState) selectParam.memberState = memberState;
    if (sheng) selectParam.sheng = sheng;
    if (shi) selectParam.shi = shi;
    if (lableId && lableId.length) selectParam.lableId = {"$in":lableId};
    if (unitName) selectParam.unitName = {"$regex":unitName};

    let selectConf = ["userId", "memberState", "unitName","session", "name", "sex", "documentId", "phone", "individualMemberType", "memberLevel", "joinTime", "lableId"];
    let dbList = await findToSortToPage(TABLEENUM.用户表, selectParam, selectConf, {joinTime:-1}, pageNumber);
    let dataCount = await findCount(TABLEENUM.用户表, selectParam);

    let dataList = [];

    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let item:any = extractData(info, selectConf);
        item.memberState = changeEnumValue(MEMBERSTATE, item.memberState);
        item.sex = changeEnumValue(SEX, item.sex);
        if (!item.memberLevel) item.memberLevel = "未选择";
        else item.memberLevel = changeEnumValue(MEMBERLEVEL, item.memberLevel)
        item.individualMemberType = changeEnumValue(MEMBERTYPEECCENUM, item.individualMemberType);
        item.joinTime = moment(item.joinTime).format("YYYY-MM-DD")
        
        item.lableId = [];
        let lableInfo = await find(TABLEENUM.标签表, {lableId:{"$in":info.lableId}}, ["lableName"]);
        lableInfo.forEach ( lableItem => {
            item.lableId.push(lableItem.lableName);
        })

        item.session = getEdition(Math.floor(item.session/100), item.session%100 );

        dataList.push(item);
    }

    return {dataList, dataCount};
}


/**
 * 个人会员详情
 * @param id 会员列表返回的userId  
 * @returns {顶部数据, 基本信息, 专业信息, 其他附件}
 * 基本信息: "name"：真实姓名, "sex"：性别, "nation"：民族, "birth"：出身年月, "documentType"：证件类型, "documentId"：证件号码, "sheng"：省, "shi"：市, "qu"：区, "phone"：手机号码,"mail"：电子邮箱,"addres"：通信地址, "photoUrl"：蓝底证件照, "education"：学历, "uscc"：原社会信用代码, "unitName"：原发票抬头, "newUscc"：新社会信用代码, "newUnitName"：新发票抬头
 * 专业信息: "unitName"：工作单位, "duties"：职务, "workTitle"：职称, "profCategory"：专业类别, "studyResume"：学习简历, "workResume"：工作简历, "profAchievement"：科研成果, "otherEMP"：其他组织任职情况, "otherPROF"：其他情况
 * 其他附件: "cardUrlJust"：身份证正面图片地址, "cardUrlBack"：身份证反面图片地址, "academicCERTUrl"：学历证明图片地址, "professionalCERTUrl"：工作证明图片地址, "auxiliaryMaterial"：其他辅助材料
 */

const RegisterConfig = ["phone", "mail", "pwd"];
const TopConfig = ["session", "memberLevel"];
const IndividualBasicConfig = ["userId", "name", "sex", "nation", "birth", "documentType", "documentId", "sheng", "shi", "qu", "addres", "photoUrl", "education", "uscc", "unitName"];
const SpecialityConfig = ["unitName", "duties", "workTitle", "profCategory", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF"];

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

    /**处理枚举值 */
    let registerInfo:any = extractData(oldInfo, RegisterConfig);

    let topInfo:any = extractData(oldInfo, TopConfig);
    topInfo.memberLevel = changeEnumValue(MEMBERLEVEL, topInfo.memberLevel);
    let session = "";
    if (!topInfo.session) session = "";
    else session = getEdition(parseInt(`${topInfo.session/100}`), parseInt(`${topInfo.session%100}`) );
    topInfo.session = session;

    let basicInfo:any = extractData(oldInfo, IndividualBasicConfig);
    // basicInfo.documentType = changeEnumValue(DOCUMENTTYPE, basicInfo.documentType);
    // basicInfo.nation = changeEnumValue(NATION, basicInfo.nation);
    /**获取订单表新社会信用代码和新发票抬头 */
    let orderInfo = await findOnceToSort(TABLEENUM.订单表, {userId:id}, {ct:-1});
    if (!orderInfo || !orderInfo.userId) {
        basicInfo.newUscc = "-";
        basicInfo.newUnitName = "-";
    } else {
        basicInfo.newUscc = orderInfo.newUscc;
        basicInfo.newUnitName = orderInfo.newUnitName;
    }

    let specialityInfo:any = extractData(oldInfo, SpecialityConfig);
    
    let otherAttachment:any = extractData(oldInfo, ["cardUrlJust", "cardUrlBack", "academicCERTUrl", "professionalCERTUrl", "auxiliaryMaterial"]);

    /**按钮权限 */
    let userInfo = await findOnce(TABLEENUM.用户表, {userId});
    let permission = [];
    if (userInfo.adminLv.indexOf(ADMINLV.会员信息修改) > -1 ) {
        permission.push(ADMINLV.会员信息修改);
    }
    
    return {topInfo, registerInfo, basicInfo, specialityInfo, otherAttachment, permission};
}


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

    /**校验入参 */
    let EccFuncName = "个人会员修改";
    if (form.sheng && form.shi && form.qu) eccCityCode(form.sheng, form.shi, form.qu);
    if (form.sex) eccEnumValue(EccFuncName, '性别', SEX, form.sex);
    if (form.documentType) eccEnumValue(EccFuncName, '证件类型', DOCUMENTTYPE, form.documentType);
    if (form.nation) eccEnumValue(EccFuncName, '民族', NATION, form.nation);
    if (form.profCategory) eccEnumValue(EccFuncName, '专业类别', PROFCATEGORY, form.profCategory);
    await updateOneData(TABLEENUM.用户表, {userId:id}, form);

    return successResult();
}

export async function systemBase({userId}) {
    let userInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    let superAdmin = userInfo.loginId == "admin";
    let adminLv = [];
    userInfo.adminLv.forEach(item => {
        adminLv.push({
            key:changeEnumValue(ADMINLV, item),
            value:item
        });
    });
    let dataInfo = {
        isAdmin:userInfo.isAdmin == STATE.是,
        name:userInfo.isAdmin ? changeEnumValue(ADMINTYPE, userInfo.adminType ) : userInfo.name,
        userId:userInfo.userId,
        token:userInfo.token,
        adminLv,
        superAdmin,
        timeMs:moment(userInfo.lastLoginMs).format("YYYY-MM-DD HH:mm:SS"),
    }

    return {dataInfo}
}


/**
 * 导出个人会员数据
 * @param param0 
 */
export async function outPutIndividualMembers({exportColumns}) {
    let selectParam = {
        isAdmin:STATE.否, 
        memberType: MEMBERTYPE.个人会员, 
        userRegisterState: USERREGISTERSTATE.通过
    };
    // let selectTitle = ["入会时间", "是否是导入用户", "会员状态", "证书类型", "个人会员类型", "会员等级/职务", "是否处于宽限期", "用户名", "联系电话", "邮箱", "真实姓名", "性别", "证件号码",
    //  "证件类型", "出生年月", "民族", "省", "市", "区", "通信地址", "学历", "职务", "职称", "学习简历", "工作简历", "专业成果/教研成果", "其他任职情况", "其他专业情况", "专业类别", "工作单位"];
    // let selectConf = ["joinTime", "isInput", "memberState", "certificateType", "individualMemberType", "memberLevel", "isGracePeriod", "loginId", "phone", "mail", "name", "sex", "documentId",
    //  "documentType", "birth", "nation", "sheng", "shi", "qu", "addres", "education", "duties", "workTitle", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF", "profCategory", "unitName"];                                    
    
    let selectTitle = ["序号"];
    let selectConf = [];
    exportColumns.forEach( info=> {
        if (info.key == "省市区") {
            selectTitle.push("省", "市", "区");
            selectConf.push("sheng", "shi", "qu");
        } else {
            selectTitle.push(info.key);
            selectConf.push(info.value);
        }
    })
    
    // let dbList = await find(TABLEENUM.用户表, selectParam, selectConf);
    let dbList = await find(TABLEENUM.用户表, selectParam, []);
    let timeChnageList = ["joinTime", "birth"];
    let addList = ["sheng", "shi", "qu"];

    let dataList = [selectTitle];

    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let subList = [ (i+1).toString() ];
        for (let i = 0; i < selectConf.length; i++) {
            let key = selectConf[i];
            let value = info[key] || "";
            if (value) {
                if (timeChnageList.indexOf(key) != -1) value = moment(value).format("YYYY-MM-DD");
                else if (key == "isInput" || key == "isGracePeriod") value = value == true ? "是" : "否";
                else if (key == "memberState") value = changeEnumValue(MEMBERSTATE, value);
                else if (key == "certificateType") value = changeEnumValue(CERTIFICATETYPE, value);
                else if (key == "individualMemberType") value = changeEnumValue(INDIVIDUALMEMBERTYPE, value);
                else if (key == "memberLevel") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "sex") value = changeEnumValue(SEX, value);
                else if (key == "documentType") value = changeEnumValue(DOCUMENTTYPE, value);
                else if (key == "nation") value = changeEnumValue(NATION, value);
                else if (key == "education") value = changeEnumValue(EDUCATION, value);
                else if (key == "yuanXiaoBanXueLeiXing") value = changeEnumValue(BANXUELEIXING, value);
                else if (key == "session") value = getEdition(Math.floor(value/100), value%100 );
                else if (key == "memberState") value = changeEnumValue(MEMBERSTATE, value);
                else if (key == "profCategory") value = changeEnumValue(PROFCATEGORY, value);
                else if (addList.indexOf(key) != -1) value = getCityNameByCode(value);
                else if (key == "lableId") {
                    value = [];
                    let selectLable:any = {
                        "$or":[{ lableId:{"$in":CLIENTMSGLABLE.所有人} }]
                    };
                    selectLable["$or"].push(
                        { lableId:{"$in":info.memberType} },
                        { lableId:{"$in":info.memberLever} },
                        { lableId:{"$in":info.lableId} }
                    )
                    let lableInfo = await find(TABLEENUM.标签表, selectLable, ["lableName"]);
                    lableInfo.forEach ( lableItem => {
                        value.push(lableItem.lableName);
                    });
                    value = value.toString();
                }
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList};
}

/**
 * 导出单位会员数据
 * @param param0 
 * @returns 
 */
export async function outPutUnitMembers({exportColumns}) {
    let selectParam = {
        isAdmin:STATE.否, 
        memberType: MEMBERTYPE.单位会员, 
        userRegisterState: USERREGISTERSTATE.通过
    };
    // let selectTitle = ["入会时间", "是否是导入用户", "会员状态", "证书类型", "个人会员类型", "会员等级/职务", "是否处于宽限期", "用户名", "联系电话", "单位电子邮箱", "单位名称", "统一信用代码", 
    // "法人代表", "法人代表联系电话", "法人邮箱", "日常联系人", "日常联系人职务", "日常联系人手机号码", "营业执照", "单位会员类型", "院校办学类型", "院校主管部门", "院校主要负责人", "院校主要负责人职务", "院校主要负责人电话", "院校办公负责人", "院校办公负责人电话", "主要负责人邮箱", "院校科研负责人", "院校科研负责人电话", "教学负责人姓名", "院校学生总人数", "教职工总人数", "教学负责人电话", "开设专业", "单位简介"];
    // let selectConf = ["joinTime", "isInput", "memberState", "certificateType", "individualMemberType", "memberLevel", "isGracePeriod", "loginId", "phone", "mail", "unitName", "uscc", 
    // "legalPerson", "legalPersonPhone", "legalPersonMail", "contactPerson", "contactPersonDuties", "phone", "uusinessLicenseUrl", "unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", "yuanXiaoFuZeRenDianHua", "yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", "yuanXiaoKeYanFuZeRenDianHua", "jiaoXueFuZeRenXinMing", "yuanXiaoXueShengZongRenShu", "yuanXiaoJiaoZhiGongZongRenShu", "jiaoXueFuZeRenDianHua", "kaishezhuanYe", "danWeiJianJie"];                                    
    
    let selectTitle = ["序号"];
    let selectConf = [];
    exportColumns.forEach( info=> {
        if (info.key == "省市区") {
            selectTitle.push("省", "市", "区");
            selectConf.push("sheng", "shi", "qu");
        } else {
            selectTitle.push(info.key);
            selectConf.push(info.value);
        }
    })
    let dbList = await find(TABLEENUM.用户表, selectParam, selectConf);
    let timeChnageList = ["joinTime"];
    let addList = ["sheng", "shi", "qu"];

    let dataList = [selectTitle];

    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let subList = [ (i+1).toString() ];
        for (let i = 0; i < selectConf.length; i++) {
            let key = selectConf[i];
            let value = info[key] || "";
            if (value) {
                if (timeChnageList.indexOf(key) != -1) value = moment(value).format("YYYY-MM-DD");
                else if (key == "isInput" || key == "isGracePeriod") value = value == true ? "是" : "否";
                else if (key == "memberState") value = changeEnumValue(MEMBERSTATE, value);
                else if (key == "certificateType") value = changeEnumValue(CERTIFICATETYPE, value);
                else if (key == "individualMemberType") value = changeEnumValue(INDIVIDUALMEMBERTYPE, value);
                else if (key == "unitMemberType") value = changeEnumValue(UNITMEMBERTYPE, value);
                else if (key == "memberLevel") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "yuanXiaoBanXueLeiXing") value = changeEnumValue(BANXUELEIXING, value);
                else if (key == "session") value = getEdition(Math.floor(value/100), value%100 );
                else if (key == "memberState") value = changeEnumValue(MEMBERSTATE, value);
                else if (addList.indexOf(key) != -1) value = getCityNameByCode(value);
                else if (key == "lableId") {
                    value = [];
                    let lableInfo = await find(TABLEENUM.标签表, {lableId:{"$in":info.lableId}}, ["lableName"]);
                    lableInfo.forEach ( lableItem => {
                        value.push(lableItem.lableName);
                    });
                    value = value.toString();
                }
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList}
}





















