/**
 * 订单相关 success
 */
import moment = require("moment");
import { AUDITINGCLIENT, COSTTYPE, INDIVIDUALMEMBERTYPE, INVOICESTATUS, ISPAYENUM, ISRECEIVE, MAILTYPE, MEMBERLEVEL, MEMBERSTATE, MEMBERTYPE, MEMBERTYPEECCENUM, MYORDERLISTPAYSTATE, MYORDERLISTSTATE, OPERATIONREHAVIOR, ORDEREXAMINE, ORDERSTATE, PAYMENTSTATUS, PAYMENTTYPE, RECEIPTCONFIRMATION, STATE, UNITMEMBERTYPE } from "../../config/enum";
import { generateOrderId, successResult } from "../../tools/system";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";
import { addOneData } from "../../data/add";
import { TABLEENUM } from "../../data/models/model";
import { find, findCount, findOnce, findOnceToSort, findToPage, findToSort, findToSortToPage } from "../../data/select";
import { extractData } from "../../util/piecemeal";
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";
import { updateOneData } from "../../data/update";
import { systemSendMail } from "../mail";

// db.getCollection('orders').insertOne({ "paymentNum" : "", "offlinePaymentUrl" : "", "weChartPR" : "", "weChartState" : 0, "isFirst" : true, "firstPayExamine" : false, "confirmReceipt" : 0, "confirmReceiptMs" : 0, "invoiceStatus" : 1, "advanceInvoice" : false, "isReceive" : 0, "isReplenishReturnInfo" : false, "refundSuccessful" : false, "isSueInvoicesInAdvance" : false, "id" : "3f9b9936f12ed619f11458ac46ff3835", "orderCycleStart" : 1498262400100.0, "orderCycleEnd" : 1529798400100.0, "unitName" : "西安市艺术学校", "money" : 2000, "paymentMethod" : 0, "userId" : "f2bed663f23c43b751876be9eae93334", "loginId" : "西安市艺术学校1960", "memberCategory" : 2, "invoiceAdd" : "", "state" : 2, "phone" : "13991991926", "ct" : 1734334302795})


/**
 * 对内使用  创建一条订单
 * @param id userId 
 * @param unitName 单位名称
 * @param orderStartMs 订单开始时间
 * @param memberLv 会员等级 MEMBERLEVEL
 * @param memberType 会员类型 MEMBERTYPE
 * @param subType 子类型 个人会员类型  或  单位会员类型 INDIVIDUALMEMBERTYPE 或 UNITMEMBERTYPE
 * @param isFirst 是否首次缴费
 * @returns 
 */
export async function createOrder(id:string, loginId:string, phone:string, unitName:string, orderStartMs:number, memberLv:number, memberType:number, subType:number, isFirst:boolean) {
    /**计算订单周期 */
    const EndMs = moment(orderStartMs).add(1, 'years').valueOf();
    /**订单id */
    const OrderId = generateOrderId(id);
    /**计算会费 */
    let money = 0;
    if (memberType == MEMBERTYPE.个人会员) {
        if (subType != INDIVIDUALMEMBERTYPE.专家会员) {
            switch (memberLv) {
                case MEMBERLEVEL.普通会员: money = 100; break;
                case MEMBERLEVEL.理事会员: money = 200; break;
                case MEMBERLEVEL.常务理事会员: money = 500; break;
            }
        } else money = -1;
    } else {
        switch (memberLv) {
            case MEMBERLEVEL.普通会员: money = 1000; break;
            case MEMBERLEVEL.理事会员: money = 2000; break;
            case MEMBERLEVEL.常务理事会员: money = 5000; break;
        }
    }
    if ( money == -1) return;//专家会员不会创建订单

    let addInfo = {
        id:OrderId,
        orderCycleStart:orderStartMs,
        orderCycleEnd:EndMs,
        unitName,
        money,
        paymentMethod:0,
        userId:id,
        loginId,
        memberCategory:memberType,
        paymentNum:"",
        invoiceAdd:'',
        state:ORDERSTATE.未支付,
        isFirst,
        phone,
        ct:new Date().valueOf()
    };

    await addOneData(TABLEENUM.订单表, addInfo);
    return true;
}


//1,5去掉了
// /**
//  * 初始订单 success
//  * 会员管理-待支付页
//  */
// export async function firstOrderList({unitName, joinTime, memberType, orderState, pageNumber}) {
//     /** 首次订单 并且未通过待支付页的审核 */
//     let findParam:any = { "$or":[{isFirst:true, firstPayExamine:false}] };
//     if (unitName) findParam.unitName = {"$regex":unitName};
//     if (memberType) findParam.memberCategory = memberType;
//     if (orderState) findParam.state = orderState;
//     let selectFile = ["id", "unitName", "loginId", "phone", "orderCycleStart", "orderCycleEnd", "memberCategory", "state", "userId"];
//     let dbList = await findToPage(TABLEENUM.订单表, findParam, selectFile, pageNumber);
//     let dataCount = await findCount(TABLEENUM.订单表, findParam);
//     let dataList = [];
//     let itemFile = ["id", "unitName", "loginId", "phone", "memberCategory", "userId"];
//     dbList.forEach(info =>  { 
//         let itemData:any = extractData(info, itemFile);
//         itemData.joinTime = moment(info.orderCycleStart).format("YYYY-MM-DD");
//         itemData.memberType = changeEnumValue(MEMBERTYPE, itemData.memberCategory);
//         itemData.paymentMethod = changeEnumValue(MEMBERTYPE, itemData.paymentMethod);
//         itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
//         if (info.state == ORDERSTATE.未支付) {
//             itemData.state = "未支付";
//         } else {
//             if (info.paymentMethod == PAYMENTTYPE.银行转账)  itemData.state = "银行转账";
//             else itemData.state = "已支付";
//         }
//         dataList.push(itemData);
//     });

//     return {dataList, dataCount};
// }


//1.5去掉了
// /**
//  * 会员管理-待支付页-通过审核 success
//  * @param id 订单id  
//  */
// export async function checkOrder({id}) {
//     let orderInfo = await findOnce(TABLEENUM.订单表, {id});
//     if (!orderInfo || !orderInfo.id ) throw new BizError(ERRORENUM.目标数据不存在);
//     if (!orderInfo.isFirst || orderInfo.firstPayExamine)  throw new BizError(ERRORENUM.重复提交);

//     await updateOneData(TABLEENUM.订单表, {id}, {firstPayExamine:true, confirmReceipt:RECEIPTCONFIRMATION.待确认});

//     return successResult();
// }


// 1.5去掉了
// /**
//  * 待支付页 线下付款
//  * @param param0 
//  * @returns 
//  */
// export async function offlinePayment({orderId, paymentNum, offlinePaymentUrl }) {
//     let orderInfo = await findOnce(TABLEENUM.订单表, {id:orderId});
//     if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
//     if (orderInfo.state == ORDERSTATE.已支付 && orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.该订单已支付);

//     let updateInfo = {
//         paymentNum,
//         offlinePaymentUrl,
//         state:ORDERSTATE.已支付,
//         paymentMethod:PAYMENTTYPE.后台上传,
//         payTime:new Date().valueOf(),
//         confirmReceipt:RECEIPTCONFIRMATION.待确认
//     };

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

//     return successResult();
// }





/**
 * 转账截图、转账单号弹窗
 * @param id 订单id
 * @returns 
 */
export async function transferScreenshot({id}) {
    let oldInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "offlinePaymentUrl", "paymentNum"]);
    if (!oldInfo || !oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let dataInfo = extractData(oldInfo, ["id", "offlinePaymentUrl", "paymentNum"]);

    return {dataInfo};
}


/**
 * 转账发票弹窗
 * @param id 订单id
 * @returns 
 */
 export async function invoicePop({id}) {
    let oldInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "invoiceAdd"]);
    if (!oldInfo || !oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let dataInfo = extractData(oldInfo, ["id", "invoiceAdd"]);

    return {dataInfo};
}


/**
 * 个人页待订单列表  success
 * @param param0 
 */
export async function orderList({userId, type}) {
    eccEnumValue("个人页待订单列表", "类型", ISPAYENUM, type);
    let findParam:any = {userId};
    if (type == ORDERSTATE.已支付) findParam.state = ORDERSTATE.已支付;
    else if (type == ORDERSTATE.未支付) findParam.state = ORDERSTATE.未支付;

    const SelectFile = ["orderCycleStart", "orderCycleEnd", "money", "state", "id", "advanceInvoice", 
        "invoiceStatus", "unitName", "confirmReceipt", "newUscc", "isReceive", "isReplenishReturnInfo", 
        "refundSuccessful", "refundImgUrl", "isSueInvoicesInAdvance"];
    let dbList = await find(TABLEENUM.订单表, findParam, SelectFile);
    /**查询证明函需要字段会员等级 */
    let myOldInfo = await findOnce(TABLEENUM.用户表, {userId}, ["memberLevel", "userId", "uscc", "memberType"]);
    if (!myOldInfo || !myOldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    let memberLevel = changeEnumValue(MEMBERLEVEL, myOldInfo.memberLevel);

    let dataList = [];
    dbList.forEach(info => {
        let {orderCycleStart, orderCycleEnd, money, state, id, unitName, confirmReceipt, newUscc, isReceive, isReplenishReturnInfo, refundSuccessful, refundImgUrl, isSueInvoicesInAdvance} = info;
        let payState;
        if (state == ORDERSTATE.已支付) {
            if (!confirmReceipt) {/**首次支付 待确认未审核*/
                payState = MYORDERLISTPAYSTATE.财务查账中;
            } else if (confirmReceipt == RECEIPTCONFIRMATION.待确认) {
                payState = MYORDERLISTPAYSTATE.财务查账中;
            } else if (confirmReceipt == RECEIPTCONFIRMATION.收款确认) {
                payState = MYORDERLISTPAYSTATE.已缴费;
            } else {//退回
                if ( isReceive == ISRECEIVE.提供账户_zkh需退款_ykh ) {//收到了用户的款项的退款
                    if (isReplenishReturnInfo && refundSuccessful ) {
                        payState = MYORDERLISTPAYSTATE.退款成功;
                    } else {
                        payState = MYORDERLISTPAYSTATE.退款通知;
                    }
                } else {//无需退款
                    payState = MYORDERLISTPAYSTATE.缴费失败;
                }
            }
        } else {
            payState = MYORDERLISTPAYSTATE.待缴费;
        }

        let invoiceState;
        if (info.invoiceStatus == INVOICESTATUS.已开发票) {
            invoiceState = MYORDERLISTSTATE.下载发票;
        } else {
            if (info.advanceInvoice) invoiceState = MYORDERLISTSTATE.申请进度;
            if (!info.advanceInvoice) invoiceState = MYORDERLISTSTATE.申请发票;
        }
       

        let item:any = {
            cycle:`${moment(orderCycleStart).format("YYYY-MM-DD")}至${moment(orderCycleEnd).format("YYYY-MM-DD")}`,
            money:money,
            id,
            uscc:newUscc || myOldInfo.uscc,
            invoiceStatus:invoiceState,
            invoiceStatusStr:changeEnumValue(MYORDERLISTSTATE , invoiceState),
            unitName,
            orderCycleStart:moment(orderCycleStart).format("YYYY"),
            orderCycleEnd:moment(orderCycleEnd).format("YYYY"),
            memberLevel,
            payState,
            payStateStr:changeEnumValue(MYORDERLISTPAYSTATE, payState),
            memberType:myOldInfo.memberType,
            isSueInvoicesInAdvance
        };
        if (refundImgUrl) item.refundImgUrl = refundImgUrl;

        dataList.push(item);
    });

    return {dataList}
}


/**
 * 个人页申请开发票 
 * @param id 会员缴费列表返回的id 
 * @param newUscc 社会信用代码 
 * @param newUnitName 发票抬头 
 */
export async function applicationInvoice({id, memberType, newUscc, newUnitName}) {
    return successResult();
    let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "userId", "invoiceStatus", "advanceInvoice", "invoiceAdd", "state", "advanceInvoice"]);
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.invoiceStatus == INVOICESTATUS.已开发票) throw new BizError(ERRORENUM.发票已开具不可重复提交);
    if (orderInfo.invoiceStatus == INVOICESTATUS.退回) throw new BizError(ERRORENUM.请求已被退回请重新申请);

    // let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["userId", "memberType"]);
    
    let updateInfo:any = {};
    //个人会员申请发票锁定文字，无法修改
    if (memberType == MEMBERTYPE.单位会员) {
        updateInfo = {invoiceStatus:INVOICESTATUS.未开发票, newUscc, newUnitName, advanceInvoice : true};
    } else {
        updateInfo = {invoiceStatus:INVOICESTATUS.未开发票, advanceInvoice : true};
    }

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


/**
 * 开发票
 * @param param0 
 * @returns 
 */
export async function applicationInadvanceInvoice({id, mail, desc}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "userId", "state"]);
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.invoiceStatus == INVOICESTATUS.已开发票) throw new BizError(ERRORENUM.发票已开具不可重复提交);
    if (orderInfo.invoiceStatus == INVOICESTATUS.退回) throw new BizError(ERRORENUM.请求已被退回请重新申请);

    let userInfo = await findOnce(TABLEENUM.用户表, {userId:orderInfo.userId}, ["userId", "unitMemberType", "memberType"]);
    
    if (userInfo.memberType != MEMBERTYPE.单位会员) {
        throw new BizError(ERRORENUM.发票已发送至邮请注意查看);
    }else if (orderInfo.state == ORDERSTATE.未支付 && userInfo.unitMemberType != UNITMEMBERTYPE.院校) {
        throw new BizError(ERRORENUM.请先付款后进行发票操作);
    }

    let updateInfo = {
        invoiceMail:mail,
        desc:desc,
        invoiceStatus:INVOICESTATUS.未开发票, 
        advanceInvoice : true,
        isSueInvoicesInAdvance:true,
        invoiceTime:new Date().valueOf()
    };

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


export async function applicationInadvanceInvoiceInfo({id}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "userId", "invoiceMail", "desc", "invoiceStatus", "state"]);
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let userInfo = await findOnce(TABLEENUM.用户表, {userId:orderInfo.userId}, ["userId", "memberType", "mail", "unitMemberType", "unit", "uscc", "unitName"]);
    if (userInfo.memberType != MEMBERTYPE.单位会员) {
        throw new BizError(ERRORENUM.发票已发送至邮请注意查看);
    }else if (orderInfo.state == ORDERSTATE.未支付 && userInfo.unitMemberType != UNITMEMBERTYPE.院校) {
        throw new BizError(ERRORENUM.请先付款后进行发票操作);
    }

    let resultObj = {
        invoiceMail: orderInfo.invoiceMail || "",
        desc:orderInfo.desc || "",
        uscc:userInfo.uscc,
        unitName:userInfo.unitName
    }    

    return resultObj;
}



/**
 * 重新申请发票
 * @param id 会员缴费列表返回的id 
 */
export async function reapplyInvoice({id}) {
    let orderInfo = await find(TABLEENUM.订单表, {id}, ["id", "invoiceStatus", "advanceInvoice", "invoiceAdd", "state", "advanceInvoice"]);
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.invoiceStatus != INVOICESTATUS.退回) throw new BizError(ERRORENUM.不满足重新请求条件);

    let updateInfo:any = {invoiceStatus:INVOICESTATUS.未开发票, invoiceTime:new Date().valueOf()};
    if (orderInfo.state != ORDERSTATE.已支付) updateInfo.advanceInvoice = true;

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


/**
 * 下载发票
 * @param id 会员缴费列表返回的id 
 */
export async function downInvoice({id}) {
    let oldInfo = await findOnce(TABLEENUM.订单表, {id, invoiceStatus:INVOICESTATUS.已开发票}, ["invoiceAdd"]);
    if (!oldInfo || !oldInfo.invoiceAdd) throw new BizError(ERRORENUM.目标数据不存在);

    let dataInfo = extractData(oldInfo, ["invoiceAdd"]);

    return {dataInfo};
}


/**
 * 发票后台审批进度
 * @param id 会员缴费列表返回的id 
 */
export async function getInvoiceStatus({id}) {
    let oldInfo = await findOnce(TABLEENUM.订单表, {id}, ["invoiceStatus", "userId", "id"]);
    if (!oldInfo || !oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let dataInfo = {state:AUDITINGCLIENT.已申请, remark:""};
    if (oldInfo.invoiceStatus == INVOICESTATUS.已开发票) dataInfo.state = AUDITINGCLIENT.审核通过;
    if (oldInfo.invoiceStatus != INVOICESTATUS.未开发票) dataInfo.state = AUDITINGCLIENT.后台审批中;
    if (oldInfo.invoiceStatus != INVOICESTATUS.退回) dataInfo.state = AUDITINGCLIENT.审核失败;

    /**获取驳回理由 */
    let userOldInfo = await findOnceToSort(TABLEENUM.订单审批历史表, {userId:oldInfo.userId, operationBehavior:OPERATIONREHAVIOR.驳回修改},{operationTime:-1}, ["userId", "remarks"]);
    if (userOldInfo && userOldInfo.userId) dataInfo.remark = userOldInfo.remark;

    return {dataInfo};
}


/**
 * 上传转账截图   个人页面的线下付款
 * @param param0 
 */
 export async function upTransferImg({id, weChartPR, offlinePaymentUrl, invoiceMail, desc}) {

    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.state == ORDERSTATE.已支付 && orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.该订单已支付);

    let updateInfo = {
        paymentNum:weChartPR,
        offlinePaymentUrl,
        state:ORDERSTATE.已支付,
        paymentMethod:PAYMENTTYPE.后台上传,
        payTime:new Date().valueOf(),
        confirmReceipt:RECEIPTCONFIRMATION.待确认,
        invoiceMail,
        desc,
        invoiceStatus:INVOICESTATUS.未开发票,
        advanceInvoice:true,
        invoiceTime:new Date().valueOf()
    };

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

    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.用户提交,
        remarks:`${desc}`
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    return successResult();
}


/**
 * 退款信息回显
 * @param param0 
 */
export async function reasonInfo({id}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if ( orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.该订单未被退回);
    
    
    let logInfoList = await findToSort(TABLEENUM.订单审批历史表, {orderId:id}, {operationTime:-1});

    let dataList = [];
    logInfoList.forEach(info => {
        let isReceiveMoney = info.isReceiveMoney ? "已收到" : "未收到";
        
        let remarks = info.remarks
        if (info.operationBehavior == ORDEREXAMINE.退款申请) {
            isReceiveMoney = "-";
            if (info.refundName) remarks += `-${info.refundName}`;
            if (info.refundBankNum) remarks += `-${info.refundBankNum}`;
            if (info.refundBankName) remarks += `-${info.refundBankName}`;
        } else if (info.operationBehavior == ORDEREXAMINE.用户提交) {
            // isReceiveMoney = "-";
            isReceiveMoney = "-";
        }

        let dataInfo = {
            operationTime:moment(info.operationTime).format("YYYY/MM/DD HH:mm:SS"),
            behavior:changeEnumValue(ORDEREXAMINE, info.operationBehavior),
            isReceiveMoney,
            remarks
        };
        dataList.push(dataInfo);
    })

    let isUpdate = true;
    if ( orderInfo.isReplenishReturnInfo && orderInfo.refundReject == false ) isUpdate = false;
    
    return {dataList:dataList, isUpdate};
}


/**
 * 退款信息更新
 * @param param0 
 */
export async function accountInfo({id, form}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if ( orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.该订单未被退回);
    if (orderInfo.isReplenishReturnInfo) throw new BizError(ERRORENUM.不可重复提交)

    //添加信息
    let updateInfo = {
        refundName : form.refundName,
        refundBankCarId : form.refundBankCarId,
        refundBankName : form.refundBankName,
        refundDesc : form.refundDesc,
        isReplenishReturnInfo:true,
        refundReject:false
    };

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

    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.退款申请,
        remarks:`${form.refundDesc}`,
        refundName:form.refundName,
        refundBankNum:form.refundBankCarId,
        refundBankName:form.refundBankName
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    return successResult();
}


/**
 * 退款列表
 * @param param0 
 */
export async function refundList({name, memberType, joinStartTime, joinEndTime, pageNumber}) {
    let findParam:any = { 
        isReceive:{"$gt":0}
    };
    
    /**用户表查询条件 */
    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 (joinStartTime) {
        isSelectUser = true;
        itemParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        isSelectUser = true;
        if (!itemParam["joinTime"]) itemParam["joinTime"] = {};
        itemParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (isSelectUser) {
        let checkUserIdDataList = await find(TABLEENUM.用户表, itemParam, ["userId"]);
        checkUserIdDataList.forEach(key => {
            checkUserIdList.push(key.userId); 
        });
    }
    if (checkUserIdList.length) {
        findParam.userId = {"$in":checkUserIdList}
    }

    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "memberCategory", "userId", "refundBankCarId", "refundBankName", "refundSuccessful", "isReplenishReturnInfo", "desc", "isReceive" ];
    let dbList = await findToSortToPage(TABLEENUM.订单表, findParam, selectFile, {orderCycleStart:-1}, pageNumber);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];

    let itemFile = ["id", "name", "unitName", "money", "userId", "memberCategory", "refundBankCarId", "refundBankName", "desc", "isReceive"];
    
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let itemData:any = extractData(info, itemFile);
        // itemData.joinTime = moment(info.orderCycleStart).format("YYYY-MM-DD");
        itemData.memberType = changeEnumValue(MEMBERTYPE, itemData.memberCategory);
        itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:itemData.userId}, ["memberState", "name", "individualMemberType", "unitMemberType"]);
        
        if (userInfo) {
            itemData.name = userInfo.name;
            if(userInfo.individualMemberType) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfo.individualMemberType);
            }
            if(userInfo.unitMemberType) {
                itemData.memberType = changeEnumValue(MEMBERTYPEECCENUM, userInfo.unitMemberType);
            }
        }

        if (!info.isReplenishReturnInfo || (info.refundReject== true && !info.refundSuccessful)) itemData.state = "资料补充中";
        else {
            if (info.refundSuccessful) itemData.state = "已退款";
            else itemData.state = "待退款"; 
        }

        dataList.push(itemData);
    }

    return {dataList, dataCount};
}


/**
 * 退款确认
 */
export async function refundApprove({id, refundImgUrl}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id ) throw new BizError(ERRORENUM.目标数据不存在);
    // if (orderInfo.isFirst && !orderInfo.firstPayExamine ) throw new BizError(ERRORENUM.重复提交, '发票管理-财务核对页-收款确认', `提交通过时订单未通过待支付页的校验`);
    if (orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.订单非退回状态, '发票管理-退款列表页-退款确认', `退款确认时订单已经不是退款状态 是${orderInfo.confirmReceipt}`);
    if (orderInfo.paymentMethod == PAYMENTTYPE.微信支付) throw new BizError(ERRORENUM.微信支付无法被退回);
    if (orderInfo.isReceive != ISRECEIVE.提供账户_zkh需退款_ykh) throw new BizError(ERRORENUM.该类型退款无需确认);
    
    let updateInfo:any = {refundSuccessful:true, refundImgUrl};

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

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

     //发送邮件
    await systemSendMail(orderInfo.userId, MAILTYPE.财务退款通知 );

    return successResult();
}


/**
 * 发票管理-退款列表-数据导出
 * @param param0 
 */
 export async function outPutRefund({exportColumns}) {
    let findParam:any = { 
        isReceive:ISRECEIVE.提供账户_zkh需退款_ykh
    };

    let selectTitle = [];
    let selectConf = [];
    exportColumns.forEach( info=> {
        selectTitle.push(info.key);
        selectConf.push(info.value);
    })
    
    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "memberCategory", "userId", "refundBankCarId", "refundBankName", "refundSuccessful", "isReplenishReturnInfo" ];
    let dbList = await find(TABLEENUM.订单表, findParam, selectFile);
    let timeChnageList = ["orderCycleStart", "operationTime"];

    let dataList = [selectTitle];
    for (let i = 0; i < dbList.length; i++) {
        let info = dbList[i];
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:info.userId}, ["userId", "memberState", "name", "unitName", "memberLevel", "phone"]);
        if (!userInfo || !userInfo.userId) continue;
        let subList = [];
        for (let i = 0; i < selectConf.length; i++) {
            let key = selectConf[i];
            let value = info[key] || "";
            if (key == "name") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.name;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitName;
            }
            if (key == "state") {
                if (!info.isReplenishReturnInfo) value = "资料补充中";
                else {
                    if (info.refundSuccessful) value = "已退款";
                    else value = "待退款"; 
                }
            }
            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);
            }
            subList.push(value);
        }
        dataList.push(subList);
    }

    return {dataList};
}

/**
 * 退款驳回
 */
export async function refundOut({id, desc}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id ) throw new BizError(ERRORENUM.目标数据不存在);
    // if (orderInfo.isFirst && !orderInfo.firstPayExamine ) throw new BizError(ERRORENUM.重复提交, '发票管理-财务核对页-收款确认', `提交通过时订单未通过待支付页的校验`);
    if (orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.订单非退回状态, '发票管理-退款列表页-退款确认', `退款确认时订单已经不是退款状态 是${orderInfo.confirmReceipt}`);
    if (orderInfo.paymentMethod == PAYMENTTYPE.微信支付) throw new BizError(ERRORENUM.微信支付无法被退回);
    if (orderInfo.isReceive != ISRECEIVE.提供账户_zkh需退款_ykh) throw new BizError(ERRORENUM.该类型退款无需确认);
    
    let updateInfo:any = {refundSuccessful:false,isReplenishReturnInfo:false, refundReject:true};
    await updateOneData(TABLEENUM.订单表, {id}, updateInfo);

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

    return successResult();
}



/**
 * 审批历史
 */
 export async function approveLog({id}) {
    let logsList = await find(TABLEENUM.订单审批历史表, {orderId:id});

    let dataList = [];
    logsList.forEach(info => {
        let { operationTime, operationBehavior, isReceiveMoney, remarks } = info;

        let desc = "";
        let operationBehaviorStr = "";
        if (operationBehavior == ORDEREXAMINE.用户提交) desc = "未收到/已收到"; //线下付款
        else {
            if (isReceiveMoney) {
                operationBehaviorStr = "不需退款";
                desc = "未收到/已收到"
            } else {
                operationBehaviorStr = "需退款";
                desc = "已收到"
            }
            // desc = isReceiveMoney ? changeEnumValue(ISRECEIVE, ISRECEIVE.未收到款项_xg其他) : changeEnumValue(ISRECEIVE, ISRECEIVE.提供账户_zkh需退款_ykh)
        } 
        let addInfo:any = {
            operationTime,
            // operationTime:moment(operationTime).format("YYYY-MM-DD HH:mm:SS"),
            operationBehavior:operationBehaviorStr,
            desc,
            other:remarks
        };
        dataList.push(addInfo);
    } );

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

    let changeSortData = [];
    dataList.forEach( info => {
        info.operationTime = moment(info.operationTime).format("YYYY-MM-DD HH:mm:SS");
        changeSortData.push(info);
    })

    return {dataList:changeSortData};
}

// export async function approveLog({id}) {
//     let logsList = await find(TABLEENUM.订单审批历史表, {orderId:id});

//     let dataList = [];
//     logsList.forEach(info => {
//         let { operationTime, operationBehavior, isReceiveMoney, remarks } = info;

//         let desc = "";
//         if (operationBehavior == ORDEREXAMINE.用户提交) desc = "线下付款";
//         else {
//             if (isReceiveMoney) {
//                 desc = "未收到"
//             } else {
//                 desc = "已收到"
//             }
//             // desc = isReceiveMoney ? changeEnumValue(ISRECEIVE, ISRECEIVE.未收到款项_xg其他) : changeEnumValue(ISRECEIVE, ISRECEIVE.提供账户_zkh需退款_ykh)
//         } 
//         let addInfo:any = {
//             operationTime,
//             // operationTime:moment(operationTime).format("YYYY-MM-DD HH:mm:SS"),
//             operationBehavior:changeEnumValue(ORDEREXAMINE, operationBehavior),
//             desc,
//             other:remarks
//         };
//         dataList.push(addInfo);
//     } );

//     return {dataList};
// }


export async function reconfirm({id, weChartPR, offlinePaymentUrl, desc}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id});
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (orderInfo.state == ORDERSTATE.已支付 && orderInfo.confirmReceipt != RECEIPTCONFIRMATION.退回) throw new BizError(ERRORENUM.该订单已支付);

    let updateInfo = {
        paymentNum:weChartPR,
        offlinePaymentUrl,
        state:ORDERSTATE.已支付,
        paymentMethod:PAYMENTTYPE.后台上传,
        payTime:new Date().valueOf(),
        confirmReceipt:RECEIPTCONFIRMATION.待确认,
        desc
    };

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

    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.用户提交,
        remarks:`${desc}`
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    return successResult();
}

