/**
 * 订单相关 success
 */
import moment = require("moment");
import { AUDITINGCLIENT, COSTTYPE, INDIVIDUALMEMBERTYPE, INVOICESTATUS, ISPAYENUM, ISRECEIVE, MEMBERLEVEL, MEMBERSTATE, MEMBERTYPE, 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 } from "../../data/select";
import { extractData } from "../../util/piecemeal";
import { BizError } from "../../util/bizError";
import { ERRORENUM } from "../../config/errorEnum";
import { updateOneData } from "../../data/update";

// 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,
    };

    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"]);
    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 || userInfo.mail || "",
        desc:orderInfo.desc || ""
    }    

    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.未开发票};
    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
    };

    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 logInfo = await findOnceToSort(TABLEENUM.订单审批历史表, {operationBehavior:ORDEREXAMINE.用户提交}, {operationTime:-1});

    let dataInfo = {
        operationTime:moment(logInfo.operationTime).format("YYYY/MM/DD HH:mm:SS"),
        behavior:"退回",
        isReceiveMoney:logInfo.isReceiveMoney ? "已到款项" : "未到款项",
        remarks:logInfo.remarks
    };

    return {dataList:[dataInfo]};
}


/**
 * 退款信息
 * @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
    };

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

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

    return successResult();
}


/**
 * 退款列表
 * @param param0 
 */
export async function refundList({name, pageNumber}) {
    let findParam:any = { 
        isReceive:ISRECEIVE.提供账户_zkh需退款_ykh
    };
    
    let checkUserIdList = []
    if (name) {
        let itemParam = {
            "$or":[
                {unitName:{"$regex":`${name}`}},
                {name:{"$regex":`${name}`}}
            ]
        }
        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" ];
    let dbList = await findToPage(TABLEENUM.订单表, findParam, selectFile, pageNumber);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];

    let itemFile = ["id", "name", "unitName", "money", "userId", "memberCategory", "refundBankCarId", "refundBankName"];
    
    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"]);
        if (userInfo) itemData.name = userInfo.name;

        if (!info.isReplenishReturnInfo) 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 );

    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}, ["memberState", "name", "unitName", "memberLevel", "phone"]);
        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 approveLog({id}) {
    let logsList = await find(TABLEENUM.订单审批历史表, {orderId:id});

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

        let addInfo:any = {
            operationTime:moment(operationTime).format("YYYY-MM-DD HH:mm:SS"),
            operationBehavior:changeEnumValue(ORDEREXAMINE, info.operationBehavior),
            desc:remarks,
            other:""
        };
        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();
}

