/**
 * 变更审批
 */

import moment = require("moment");
import { CERTIFICATETYPE, CHANGEAPPLYTYPE, CLIENTMSGLABLE, INDIVIDUALMEMBERTYPE, MEMBERLEVEL, MEMBERSTATE, MEMBERTYPE, STATE, UNITMEMBERTYPE } from "../../config/enum";
import { TABLEENUM } from "../../data/models/model";
import { find, findCount, findOnce, 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 { getMenberNum, successResult } from "../../tools/system";
import { updateOneData } from "../../data/update";
import { setEnumInterface } from "../public";
import { addOneData } from "../../data/add";


/**
 * 变更审批列表
 * @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}) {
    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);
    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);

    return successResult();
}


/**
 * 批量通过
 * @param param0 
 */
export async function applyBatchAdopt({idList}) {
    //限制长度
    if (idList.length > 10) 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);

    }

    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.否});

    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 = [];
        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};
}






