/**
 * 财务管理-待开发票
 * 财务管理-已开发票
 */

import moment = require("moment");
import { INVOICESTATUS, ISPAYENUM, MAILTYPE, MEMBERLEVEL, MEMBERSTATE, MEMBERTYPE, MEMBERTYPEECCENUM, MSGTYPE, ORDEREXAMINE, ORDERSTATE, PAYMENTSTATUS, PAYMENTTYPE, RECEIPTCONFIRMATION, STATE } from "../../../config/enum";
import { TABLEENUM } from "../../../data/models/model";
import { find, findCount, findOnce, findOnceToSort, findToPage, findToSortToPage } from "../../../data/select";
import { extractData } from "../../../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../../../util/verificationEnum";
import { ERRORENUM } from "../../../config/errorEnum";
import { BizError } from "../../../util/bizError";
import { updateOneData } from "../../../data/update";
import { addOneData } from "../../../data/add";
import { successResult } from "../../../tools/system";
import { systemSendMail } from "../../mail";
import { sendMessage } from "../../sms";


/**
 * 发票管理-待开发票 success
 * @param name 名称关键字：个人会员匹配真实姓名，单位会员匹配单位名称
 * @param memberType 会员类别 unitMemberType、individualMemberType  多选
 * 会员类别：个人【个人会员、专业会员】单位【院校、机构、其他】返回前端枚举：MEMBERTYPEECCENUM
 * @param documentId 身份证
 * @param phone 登录手机号
 * @param mail 单位/个人邮箱
 * @param joinStartTime 入会开始时间
 * @param joinEndTime 入会结束时间
 * @param memberLevel 会员级别/职务 多选
 * 会员级别/职务：【普通会员、理事会员、常务理事会员】
 * @param paymentType 支付方式
 * @param isPay 是否支付
 * @param weChartPR 微信订单号
 * @param pageNumber 当前页
 */
export async function billStateList({name, memberType, documentId, invoiceApplyMs, phone, mail, joinStartTime, joinEndTime, memberLevel, payState,paymentType, invoiceState, weChartPR, pageSize, pageNumber}) {
    let testMs = new Date().valueOf();
    if (payState != 1 && payState != 2 && payState != 3) throw new BizError(ERRORENUM.参数错误);
    let findParam:any = {invoiceStatus:{"$ne":INVOICESTATUS.已开发票}};
    
    if (invoiceApplyMs) {
        findParam.invoiceTime = {"$gt":invoiceApplyMs, "$lt":invoiceApplyMs}
    }

    if (payState == 1) {//已支付
        findParam.state = ORDERSTATE.已支付;
        findParam.confirmReceipt = RECEIPTCONFIRMATION.收款确认;
        if (invoiceState == 1) {//已申请
            findParam.invoiceStatus = INVOICESTATUS.未开发票
        } else if (invoiceState == 2) {//未申请
            findParam["$or"] = [{invoiceStatus:INVOICESTATUS.不具备开票条件}, {invoiceStatus:INVOICESTATUS.退回}];
        } else {//全部
            // findParam.invoiceStatus = {"$ne": INVOICESTATUS.已开发票};
        }
    } else if (payState == 2){//未支付
        // findParam.state = ORDERSTATE.未支付;// todo  这里的条件有问题
        findParam["$or"] = [
            {state:ORDERSTATE.未支付},
            {state:ORDERSTATE.已支付, confirmReceipt:{"$ne":RECEIPTCONFIRMATION.收款确认} }
        ];
        if (!invoiceState || invoiceState == 1) {//已申请 和 全部
            findParam.invoiceStatus = INVOICESTATUS.未开发票
        } else {//未申请
           return {dataList:[], dataCount:0};
        }
    } else {//全部
        if (!invoiceState) {// 全部
            findParam["$or"] = [
                { state : ORDERSTATE.已支付, },
                { state : ORDERSTATE.未支付, invoiceStatus:INVOICESTATUS.未开发票},
                // { invoiceStatus : INVOICESTATUS.未开发票},
                // {"$or":[{invoiceStatus:INVOICESTATUS.不具备开票条件}, {invoiceStatus:INVOICESTATUS.退回}]}
            ]
        } else if ( invoiceState == 1) {//已申请
            findParam.invoiceStatus = INVOICESTATUS.未开发票;
        }else {//未申请
            findParam = { state : ORDERSTATE.未支付, invoiceStatus:INVOICESTATUS.未开发票};
        }
    }

    /**用户表查询条件 */
    let checkUserIdList = []
    let itemParam:any = {};
    let isSelectUser = false;
    if (name) {
        isSelectUser = true;
        itemParam = {
            "$or":[
                {unitName:{"$regex":`${name}`}},
                {name:{"$regex":`${name}`}}
            ]
        }
    }
    if (memberType && memberType.length) {
        isSelectUser = true;
        itemParam["$or"] = [ {unitMemberType:{"$in":memberType}}, {individualMemberType:{"$in":memberType}} ];
    }
    if (documentId) {
        isSelectUser = true;
        itemParam.documentId = documentId;
    }    
    if (mail) {
        isSelectUser = true;
        itemParam.mail = mail;
    }
    if (joinStartTime) {
        isSelectUser = true;
        itemParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        isSelectUser = true;
        if (!itemParam["joinTime"]) itemParam["joinTime"] = {};
        itemParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (memberLevel && memberLevel.length) {
        isSelectUser = true;
        itemParam.memberLevel = {"$in":memberLevel};
    }
    if (isSelectUser) {
        let checkUserIdDataList = await find(TABLEENUM.用户表, itemParam, ["userId"]);
        checkUserIdDataList.forEach(key => {
            checkUserIdList.push(key.userId); 
        });
    }
    if (checkUserIdList.length) {
        findParam.userId = {"$in":checkUserIdList}
    }

    if (phone) findParam.phone = phone;
    if (paymentType) {
        eccEnumValue("发票列表", "支付类型", PAYMENTTYPE, paymentType);
        findParam.paymentMethod = paymentType;
    }
    if (weChartPR) findParam.paymentNum = {"$regex":`${weChartPR}`};

    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "payTime", "invoiceTime", "paymentMethod", "memberCategory", "state", 
    "paymentNum", "userId", "desc", "invoiceMail", "weChartCreatePayMs", "invoiceStatus", "confirmReceipt"];
    let dbList = await findToSortToPage(TABLEENUM.订单表, findParam, selectFile, {payTime:-1, confirmReceiptMs:-1},pageNumber, pageSize);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];

    let itemFile = ["id", "userId", "unitName", "money", "paymentNum", "memberCategory", "state", "paymentMethod", "desc", "invoiceMail", 
    "weChartCreatePayMs", "invoiceStatus"];
    for (let i= 0; i < dbList.length; i++) {
        let info = dbList[i];
        let itemData:any = extractData(info, itemFile);
        if (!itemData.desc) itemData.desc = "-";
        if (!itemData.invoiceMail) itemData.invoiceMail = "-";
        itemData.joinTime = moment(info.orderCycleStart).format("YYYY-MM-DD");
        itemData.memberType = changeEnumValue(MEMBERTYPE, itemData.memberCategory);
        itemData.paymentMethod = changeEnumValue(PAYMENTTYPE, itemData.paymentMethod);
        // itemData.isPay = changeEnumValue(ORDERSTATE, itemData.state);

       
        if(info.confirmReceipt == RECEIPTCONFIRMATION.收款确认 && info.state == ORDERSTATE.已支付) itemData.isPay = "已支付";
        else if (info.confirmReceipt != RECEIPTCONFIRMATION.收款确认 && info.state == ORDERSTATE.已支付) itemData.isPay = "核对中"; //费用核对里待审批和驳回列表里的数据都会显示核对中
        // else if (info.refundSuccessful) itemData.isPay = "已退回";
        else itemData.isPay = "未支付";
        let userInfomation = await findOnce(TABLEENUM.用户表, {userId:itemData.userId}, ["userId", "memberState", "name", "memberLevel", "memberType", "mail", "individualMemberType", "unitMemberType"]);
        if (!userInfomation || !userInfomation.userId) continue;
        if(userInfomation) {
            if(userInfomation.memberType == MEMBERTYPE.个人会员) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfomation.individualMemberType);
                itemData.invoiceMail = userInfomation.mail;
            }
            if(userInfomation.memberType == MEMBERTYPE.单位会员) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfomation.unitMemberType);
                itemData.invoiceMail = itemData.invoiceMail;
            }
            itemData.memberLevel = changeEnumValue(MEMBERLEVEL, userInfomation.memberLevel);
            // itemData.memberState = changeEnumValue(MEMBERSTATE, userInfomation.memberState);
        }

        itemData.invoiceStatus = itemData.invoiceStatus == INVOICESTATUS.未开发票 ? "已申请" : "未申请";
        
        // itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
        itemData.cycle = `${moment(info.orderCycleStart).format("YYYY")}至${moment(info.orderCycleEnd).format("YYYY")}`;
        itemData.weChartCreatePayMs = moment(info.weChartCreatePayMs || info.payTime).format("YYYY-MM-DD");
        itemData.name = userInfomation.name;

        //发票申请时间
        if (info.memberCategory == MEMBERTYPE.个人会员) itemData.invoiceTime = "-";
        else {
            itemData.invoiceTime = info.invoiceTime ? moment(info.invoiceTime).format("YYYY-MM-DD") : "-";
            // let orderInfo = await findOnceToSort(TABLEENUM.订单审批历史表, {orderId:info.id,operationBehavior:ORDEREXAMINE.用户提交, refundName:null}, {operationTime:-1}, ["operationTime"]);
            // if (orderInfo && orderInfo.operationTime) itemData.invoiceTime = moment(orderInfo.operationTime).format("YYYY-MM-DD");
            // else itemData.invoiceTime = "-";
        }

        itemData.tjTime = "";

        if(info.state == PAYMENTSTATUS.未支付 ) {
            itemData.weChartCreatePayMs  = "-";
            itemData.paymentMethod  = "-";
        }
        if (itemData.isPay == "核对中") {
            itemData.state = PAYMENTSTATUS.未支付;
            //提交时间
            itemData.tjTime = moment(info.payTime).format("YYYY-MM-DD");

        }

       
        dataList.push(itemData);
       
    }

    console.log("请求耗时", new Date().valueOf() - testMs);
    return {dataList, dataCount};
}



/**
 * 发票管理-财务核对页面-审批历史
 * @param param0 
 * @returns 
 */
export async function confirmReceiptHistory({id}) {
    let dbList = await find(TABLEENUM.订单审批历史表, {orderId:id});

    let dataList = [];
    dbList.sort((a, b) => {return b.operationTime- a.operationTime});

    dbList.forEach(info => {
        let item:any = extractData(info, ["operationTime", "operationBehavior", "remarks", "refundImgUrl", "isReceiveMoney"]);
        item.operationTime = moment(item.operationTime).format("YYYY-MM-DD HH:mm:SS");
        // item.operationBehavior = changeEnumValue(ORDEREXAMINE, item.operationBehavior);

        item.desc = "";
        let operationBehaviorStr = changeEnumValue(ORDEREXAMINE, item.operationBehavior);
        if (item.operationBehavior == ORDEREXAMINE.用户提交) {
            item.desc = "未收到/已收到"; //线下付款
        } else {
            if (item.isReceiveMoney) { //判断是否收到款项
                if (info.operationBehavior == ORDEREXAMINE.驳回) operationBehaviorStr = `${changeEnumValue(ORDEREXAMINE, info.operationBehavior)}-不需退款`;
                item.desc = "未收到/已收到"
            } else {
                if (info.operationBehavior == ORDEREXAMINE.驳回) operationBehaviorStr = `${changeEnumValue(ORDEREXAMINE, info.operationBehavior)}-需退款`;
                item.desc = "已收到"
            }
            // desc = isReceiveMoney ? changeEnumValue(ISRECEIVE, ISRECEIVE.未收到款项_xg其他) : changeEnumValue(ISRECEIVE, ISRECEIVE.提供账户_zkh需退款_ykh)
        }
        item.operationBehavior = operationBehaviorStr;

        dataList.push(item);
    });

    return {dataList};
}



/**
 * 上传发票 success  发票审核通过
 * @param param0 
 */
export async function upInvoice({id, invoiceUrl}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});

    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.invoiceStatus != INVOICESTATUS.未开发票 && orderInfo.invoiceStatus != INVOICESTATUS.已开发票 ) throw new BizError(ERRORENUM.订单状态无法开具发票, `${orderInfo.id}无法开具发票，因为发票状态为${orderInfo.invoiceStatus}`);
    
    let updateInfo = {
        invoiceStatus : INVOICESTATUS.已开发票,
        // invoiceAdd:invoiceUrl
        invoiceExamineTime:new Date().valueOf()

    };
    await updateOneData(TABLEENUM.订单表, {id}, updateInfo);

    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.已开票,
        isReceiveMoney:true,
        remarks:``
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    if(orderInfo.state == STATE.否) {
        //提前开票 发送邮件
        await systemSendMail(orderInfo.userId, MAILTYPE.会员催缴通知提前开发票 );

        let userInfo = await findOnce(TABLEENUM.用户表, {userId:orderInfo.userId});
        let smsName = userInfo.memberType == MEMBERTYPE.个人会员 ? userInfo.name : userInfo.unitName;
        sendMessage(userInfo.phone, {name:smsName}, MSGTYPE.会员催缴通知提前开发票);
    }

    return successResult();
}


/**
 * 退回发票 success
 * @param param0 
 */
export async function backInvoice({id}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});

    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.invoiceStatus != INVOICESTATUS.未开发票) throw new BizError(ERRORENUM.订单状态无法开具发票, `${orderInfo.id}无法开具发票，因为发票状态为${orderInfo.invoiceStatus}`);

    if (orderInfo.paymentMethod == PAYMENTTYPE.微信支付) throw new BizError(ERRORENUM.微信支付无法退回发票请求);

    let updateInfo:any = {
        invoiceStatus : INVOICESTATUS.退回,
        advanceInvoice:false,
    };
    if (orderInfo.state == ORDERSTATE.已支付 ) updateInfo.confirmReceipt = RECEIPTCONFIRMATION.待确认
    await updateOneData(TABLEENUM.订单表, {id}, updateInfo);
    
    return successResult();
}


/**
 * 发票管理-待开发票-数据导出
 * @param param0 
 */
 export async function outPutBillState({exportColumns, payState, invoiceState}) {
    let findParam:any = { };
    if (payState == 1) {//已支付
        findParam.state = ORDERSTATE.已支付;
        if (invoiceState == 1) {//已申请
            findParam.invoiceStatus = INVOICESTATUS.未开发票
        } else if (invoiceState == 2) {//未申请
            
            findParam["$or"] = [{invoiceStatus:INVOICESTATUS.不具备开票条件}, {invoiceStatus:INVOICESTATUS.退回}];
        } else {//全部
            // findParam.invoiceStatus = {"$ne": INVOICESTATUS.已开发票};
        }
    } else if (payState == 2){//未支付
        findParam.state = ORDERSTATE.未支付;
        if (!invoiceState || invoiceState == 1) {//已申请 和 全部
            findParam.invoiceStatus = INVOICESTATUS.未开发票
        } else {//未申请
           return {dataList:[], dataCount:0};
        }
    } else {//全部
        if (!invoiceState) {// 全部
            findParam["$or"] = [
                { state : ORDERSTATE.已支付, },
                { state : ORDERSTATE.未支付, invoiceStatus:INVOICESTATUS.未开发票},
                // { invoiceStatus : INVOICESTATUS.未开发票},
                // {"$or":[{invoiceStatus:INVOICESTATUS.不具备开票条件}, {invoiceStatus:INVOICESTATUS.退回}]}
            ]
        } else if ( invoiceState == 1) {//已申请
            findParam.invoiceStatus = INVOICESTATUS.未开发票;
        }else {//未申请
            findParam = { state : ORDERSTATE.未支付, invoiceStatus:INVOICESTATUS.未开发票};
        }
    }

    let selectTitle = ["序号"];
    let selectConf = [];
    exportColumns.forEach( info=> {
        selectTitle.push(info.key);
        selectConf.push(info.value);
    })
    
    let selectFile = ["id", "unitName", "userId", "orderCycleStart", "orderCycleEnd", "money", "paymentMethod", "memberCategory", "paymentNum", "desc", 
    "invoiceMail", "confirmReceiptMs", "payTime", "invoiceTime"];
    let dbList = await find(TABLEENUM.订单表, findParam, selectFile);
    let timeChnageList = ["orderCycleStart", "operationTime", "confirmReceiptMs", "payTime", "invoiceTime"];
    let memberChnageList = ["name", "card", "mail"];

    let dataList = [selectTitle];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:info.userId}, ["memberState", "name", "unitName", "documentId", "uscc", "mail", "memberLevel", "phone", "individualMemberType", "unitMemberType"]);
        let orderInfo = await findOnceToSort(TABLEENUM.订单审批历史表, {orderId:info.id,operationBehavior:ORDEREXAMINE.用户提交, refundName:null}, {operationTime:-1}, ["operationTime"]);
        let subList = [ (i+1).toString() ];
        for (let i = 0; i < selectConf.length; i++) {
            let key = selectConf[i];
            let value = info[key] || "";
            if (userInfo) {
                if (key == "memberCategory") {
                    if (info.memberCategory == MEMBERTYPE.个人会员) value = changeEnumValue(MEMBERTYPEECCENUM, userInfo.individualMemberType);
                    else if (info.memberCategory == MEMBERTYPE.单位会员) value = changeEnumValue(MEMBERTYPEECCENUM, userInfo.unitMemberType);
                }
                if (key == "name") {
                    if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.name;
                    else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitName;
                }
                if (key == "card") {
                    if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.documentId;
                    else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.uscc;
                }
                if (key == "mail") {
                    value = userInfo.mail;
                }
                if (key == "phone") {
                    value = userInfo.phone;
                }
                if (key == "memberLevel") {
                    value = changeEnumValue(MEMBERLEVEL, userInfo.memberLevel);
                }
            }
            
            if (key == "operationTime") {
                if (orderInfo && orderInfo.operationTime) value = moment(orderInfo.operationTime).format("YYYY-MM-DD");
                else value = "-"
            }
            if (key == "paymentMethod" || key == "paymentNum") {
                if (!info.paymentMethod) {
                    value = "-";
                }
            }
            if (key == "orderCycle") value = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
            if (key == "invoiceTime") {
                if (orderInfo && orderInfo.operationTime) value = moment(orderInfo.operationTime).format("YYYY-MM-DD");
                else value = "-"
            }
            // if (key == "payTime") {
            //     if (info.paymentMethod != PAYMENTTYPE.微信支付) value = "-"
            // }
            if (value && value != "-") {
                if (timeChnageList.indexOf(key) != -1) value = moment(value).format("YYYY-MM-DD");
                // else if (key == "memberCategory") value = changeEnumValue(MEMBERTYPE, value);
                // else if (key == "memberLevel") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "paymentMethod") value = changeEnumValue(PAYMENTTYPE, value);
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList};
}


/**
 * 发票管理-待开发票-审批历史 todo
 * @param param0 
 * @returns 
 */
export async function billStateHistory({id}) {
    let dbList = await find(TABLEENUM.订单审批历史表, {orderId:id});

    let dataList = [];
    dbList.sort((a, b) => {return b.operationTime- a.operationTime});
    dbList.forEach(info => {
        let item:any = extractData(info, ["operationTime", "operationBehavior", "remarks", "refundImgUrl"]);
        item.operationTime = moment(item.operationTime).format("YYYY-MM-DD HH:mm:SS");
        item.operationBehavior = changeEnumValue(ORDEREXAMINE, item.operationBehavior);
        dataList.push(item);
    });

    return {dataList};
}


/**
 * 批量开票确认
 * @param param0 
 */
export async function billStateBatchAdopt({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 orderInfo = await findOnce(TABLEENUM.订单表, {id});

        if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
        if (orderInfo.invoiceStatus != INVOICESTATUS.未开发票 && orderInfo.invoiceStatus != INVOICESTATUS.已开发票 ) throw new BizError(ERRORENUM.订单状态无法开具发票, `${orderInfo.id}无法开具发票，因为发票状态为${orderInfo.invoiceStatus}`);
        
        let updateInfo = {
            invoiceStatus : INVOICESTATUS.已开发票,
            // invoiceAdd:invoiceUrl
        };
        await updateOneData(TABLEENUM.订单表, {id}, updateInfo);
    }

    return successResult();
}


/**
 * 发票管理-已开发票 success
 * @param name 名称关键字：个人会员匹配真实姓名，单位会员匹配单位名称
 * @param memberType 会员类别 unitMemberType、individualMemberType  多选
 * 会员类别：个人【个人会员、专业会员】单位【院校、机构、其他】返回前端枚举：MEMBERTYPEECCENUM
 * @param documentId 身份证
 * @param phone 登录手机号
 * @param mail 单位/个人邮箱
 * @param joinStartTime 入会开始时间
 * @param joinEndTime 入会结束时间
 * @param invoiceExamineTime 已开票时间
 * @param memberLevel 会员级别/职务 多选
 * 会员级别/职务：【普通会员、理事会员、常务理事会员】
 * @param paymentType 支付方式
 * @param isPay 是否支付
 * @param pageNumber 当前页
 */
export async function invoicedList({name, memberType, documentId, invoiceExamineTime, phone, memberLevel, paymentType, isPay, weChartPR, state, pageNumber}) {
    //校验参数
    eccEnumValue("发票列表", "支付类型", PAYMENTTYPE, paymentType);
    eccEnumValue("发票列表", "是否支付", ISPAYENUM, isPay );

    /**组合 用户表 查询条件 */ 
    let checkUserIdList = []
    let userTableParam:any = {};
    let isSelectUser = false;
    if (name) {
        isSelectUser = true;
        userTableParam = {
            "$or":[
                {unitName:{"$regex":`${name}`}},
                {name:{"$regex":`${name}`}}
            ]
        }
    }
    if (memberType && memberType.length) {
        isSelectUser = true;
        userTableParam["$or"] = [ {unitMemberType:{"$in":memberType}}, {individualMemberType:{"$in":memberType}} ];
    }
    if (documentId) {
        isSelectUser = true;
        userTableParam.documentId = documentId;
    }    
    // if (mail) {
    //     isSelectUser = true;
    //     itemParam.mail = mail;
    // }
    if (state) {
        isSelectUser = true;
        userTableParam.memberState = state;
    }
    if (memberLevel && memberLevel.length) {
        isSelectUser = true;
        userTableParam.memberLevel = {"$in":memberLevel};
    }
    if (isSelectUser) {
        let checkUserIdDataList = await find(TABLEENUM.用户表, userTableParam, ["userId"]);
        checkUserIdDataList.forEach(key => {
            checkUserIdList.push(key.userId); 
        });
    }

    /**组合 订单表 查询条件 */
    let findParam:any = {  invoiceStatus:INVOICESTATUS.已开发票 };
    if (invoiceExamineTime)  findParam.invoiceExamineTime = {"$gt":invoiceExamineTime, "$lt":invoiceExamineTime};
    if (checkUserIdList.length) findParam.userId = {"$in":checkUserIdList};
    if (phone) findParam.phone = phone;
    if (paymentType) findParam.paymentMethod = paymentType;
    if (isPay) findParam.state = isPay;
    if (weChartPR) findParam.paymentNum = {"$regex":`${weChartPR}`};
    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "invoiceExamineTime", "paymentMethod", "memberCategory", "state", "paymentNum", "userId", "desc", "invoiceMail", "confirmReceipt"];

    //查询结果
    let dbList = await findToPage(TABLEENUM.订单表, findParam, selectFile, pageNumber);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];
    let itemFile = ["id", "unitName", "money", "paymentNum", "state", "userId", "memberCategory", "paymentMethod", "desc", "invoiceExamineTime", "invoiceMail"];
    
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let itemData:any = extractData(info, itemFile);

        if (!itemData.desc) itemData.desc = "";
        itemData.joinTime = moment(info.orderCycleStart).format("YYYY-MM-DD");
        itemData.memberType = changeEnumValue(MEMBERTYPE, itemData.memberCategory);
        itemData.paymentMethod = changeEnumValue(PAYMENTTYPE, itemData.paymentMethod);
        // itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
        itemData.cycle = `${moment(info.orderCycleStart).format("YYYY")}至${moment(info.orderCycleEnd).format("YYYY")}`;
        itemData.isPay = ""
        if(info.confirmReceipt == RECEIPTCONFIRMATION.收款确认 && info.state == ORDERSTATE.已支付) itemData.isPay = "已支付";
        else if (info.confirmReceipt != RECEIPTCONFIRMATION.收款确认 && info.state == ORDERSTATE.已支付) itemData.isPay = "核对中"; //费用核对里待审批和驳回列表里的数据都会显示核对中
        // else if (info.refundSuccessful) itemData.isPay = "已退回";
        else itemData.isPay = "未支付";

        itemData.invoiceExamineTime = info.invoiceExamineTime ? moment(info.invoiceExamineTime).format("YYYY-MM-DD") : '-';

        let userInfo = await findOnce(TABLEENUM.用户表, {userId:itemData.userId}, ["userId", "memberState", "name", "memberLevel", "memberType", "individualMemberType", "unitMemberType", "mail"])
        if(userInfo) {
            if(userInfo.memberType == MEMBERTYPE.个人会员) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfo.individualMemberType);
                itemData.invoiceMail = userInfo.mail;
            }
            if(userInfo.memberType == MEMBERTYPE.单位会员) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfo.unitMemberType);
                itemData.invoiceMail = info.invoiceMail ? info.invoiceMail : '-';
            }
            itemData.memberLevel = changeEnumValue(MEMBERLEVEL, userInfo.memberLevel);
        }
        itemData.name = userInfo.name;
        /**会员状态显示修改为：只记录当前一笔订单的状态，如：已支付订单状态显示正常 */
        // itemData.memberState = changeEnumValue(MEMBERSTATE, userInfo.memberState); //修改前的
        itemData.memberState = (info.state == ORDERSTATE.已支付 && info.confirmReceipt == RECEIPTCONFIRMATION.收款确认) ? "运行" : "提醒" ; //修改后的
        
        dataList.push(itemData);
    }

    return {dataList, dataCount};
}


/**
 * 发票管理-已开发票-数据导出
 * @param param0 
 */
 export async function outPutInvoiced({exportColumns}) {
    let findParam:any = { 
        invoiceStatus:INVOICESTATUS.已开发票
    };

    let selectTitle = ["序号"];
    let selectConf = [];
    exportColumns.forEach( info=> {
        selectTitle.push(info.key);
        selectConf.push(info.value);
    })
    
    let selectFile = ["id", "unitName", "userId", "orderCycleStart", "orderCycleEnd", "invoiceExamineTime", "money", "paymentMethod", "memberCategory", "paymentNum", 
    "desc", "invoiceMail", "confirmReceiptMs", "payTime"];

    let dbList = await find(TABLEENUM.订单表, findParam, selectFile);
    let timeChnageList = ["orderCycleStart", "operationTime", "confirmReceiptMs", "payTime"];

    let dataList = [selectTitle];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:info.userId}, ["memberState", "name", "unitName", "documentId", "uscc", "mail", "memberLevel", "phone"]);
        let orderInfo = await findOnceToSort(TABLEENUM.订单审批历史表, {orderId:info.id,operationBehavior:ORDEREXAMINE.已开票}, {operationTime:-1}, ["operationTime"]);
        let subList = [ (i+1).toString() ];
        for (let i = 0; i < selectConf.length; i++) {
            let key = selectConf[i];
            let value = info[key] || "";
            if (userInfo) {
                if (key == "name") {
                    if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.name;
                    else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitName;
                }
                if (key == "card") {
                    if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.documentId;
                    else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.uscc;
                }
                if (key == "mail") {
                    value = userInfo.mail;
                }
                if (key == "phone") {
                    value = userInfo.phone;
                }
                if (key == "memberLevel") {
                    value = changeEnumValue(MEMBERLEVEL, userInfo.memberLevel);
                }
            }
            
            if (key == "operationTime") {
                if (orderInfo && orderInfo.operationTime) value = moment(orderInfo.operationTime).format("YYYY-MM-DD");
                else value = "-"
            }
            if (key == "paymentMethod" || key == "paymentNum") {
                if (!info.paymentMethod) {
                    value = "-";
                }
            }
            if (key == "invoiceExamineTime") {
                value = value ? moment(value).format("YYYY-MM-DD") : '-';
            }
            if (key == "orderCycle") value = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
            if (value && value != "-") {
                if (timeChnageList.indexOf(key) != -1) value = moment(value).format("YYYY-MM-DD");
                else if (key == "memberCategory") value = changeEnumValue(MEMBERTYPE, value);
                // else if (key == "memberLevel") value = changeEnumValue(MEMBERLEVEL, value);
                else if (key == "paymentMethod") value = changeEnumValue(PAYMENTTYPE, value);
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList};
}


/**
 * 发票管理-已开发票-审批历史 todo
 * @param param0 
 * @returns 
 */
export async function invoicedHistory({id}) {
    let dbList = await find(TABLEENUM.订单审批历史表, {orderId:id});

    let dataList = [];
    dbList.sort((a, b) => {return b.operationTime- a.operationTime});
    dbList.forEach(info => {
        let item:any = extractData(info, ["operationTime", "operationBehavior", "remarks", "refundImgUrl"]);
        item.operationTime = moment(item.operationTime).format("YYYY-MM-DD HH:mm:SS");
        item.operationBehavior = changeEnumValue(ORDEREXAMINE, item.operationBehavior);
        dataList.push(item);
    });

    return {dataList};
}
