/**
 * 订单相关 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";


/**
 * 对内使用  创建一条订单
 * @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();
// }


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

    let findParam:any = {
        // "$and":[
        //     { "$or":[{isFirst:false}, {isFirst:true, firstPayExamine:true }] },
        // ],
        confirmReceipt:RECEIPTCONFIRMATION.待确认,
        state:ORDERSTATE.已支付
    }
    if (name) {
        findParam["$or"] = [
            {unitName:{"$regex":`${name}`}},
            {name:{"$regex":`${name}`}}
        ]
    }
    if (memberType.length) {
        if (memberType < UNITMEMBERTYPE.院校) {
            findParam.individualMemberType = {"$in":memberType};
        } else {
            findParam.unitMemberType = {"$in":memberType};
        }
    }
    if (documentId) findParam.documentId = documentId;
    if (phone) findParam.phone = phone;
    if (mail) findParam.mail = mail;
    if (joinStartTime) {
        findParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!findParam["joinTime"]) findParam["joinTime"] = {};
        findParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (memberLevel.length) findParam.memberLevel = {"$in":memberLevel};
    if (paymentType) findParam.paymentMethod = paymentType;
    if (costType) findParam.isFirst = costType == COSTTYPE.首次;

    let selectFile = ["id", "unitName", "userId", "orderCycleStart", "orderCycleEnd", "money", "paymentMethod", "memberCategory", "isFirst", "paymentNum", "memberState", "operationTime" ];
    let dbList = await findToPage(TABLEENUM.订单表, findParam, selectFile, pageNumber);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];

    let itemFile = ["id", "unitName", "money", "paymentNum", "userId"];
    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.operationTime = moment(info.operationTime).format("YYYY-MM-DD");
        itemData.memberType = changeEnumValue(MEMBERTYPE, info.memberCategory);
        itemData.paymentMethod = changeEnumValue(PAYMENTTYPE, info.paymentMethod);
        itemData.costType = info.isFirst == COSTTYPE.首次 ? "首次" : "续费";
        itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`

        if (!info.paymentMethod) {
            itemData.paymentMethod = "-";
            itemData.paymentNum = "-";
        }
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:info.userId}, ["memberState", "name", "memberLevel"]);
        if (userInfo) itemData.memberState = changeEnumValue(MEMBERSTATE, userInfo.memberState);
        itemData.memberLevel = changeEnumValue(MEMBERLEVEL, userInfo.memberLevel);
        itemData.name = userInfo.name;

        dataList.push(itemData);
    }

    return {dataList, dataCount};
}


/**
 * 发票管理-财务核对页-收款确认 success
 * @param id 订单id 
 */
export async function confirmReceiptPass({id}) {
    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}`);

    let updateInfo:any = {confirmReceipt:RECEIPTCONFIRMATION.收款确认, confirmReceiptMs:new Date().valueOf()};
    if (orderInfo.invoiceStatus != INVOICESTATUS.已开发票) updateInfo.invoiceStatus = INVOICESTATUS.未开发票;
    await updateOneData(TABLEENUM.订单表, {id}, updateInfo);

    let notPayCount = await findCount(TABLEENUM.订单表, {userId:orderInfo.userId, state:ORDERSTATE.未支付} );
    let updateUserInfo:any = {};
    /**只有一笔欠费时才更新用户状态 */
    if (notPayCount < 1) {
        let newOrderInfo = await findOnceToSort(TABLEENUM.订单表, {userId:orderInfo.userId}, {lifespanEndTime:-1}, ["orderCycleStart","orderCycleEnd"]);
        
        updateUserInfo.lifespanStartTime = newOrderInfo.orderCycleStart,
        updateUserInfo.lifespanEndTime = newOrderInfo.orderCycleEnd,
        updateUserInfo.isGracePeriod = STATE.否,
        updateUserInfo.gracePeriodEndTime = 0,
        updateUserInfo.memberState = MEMBERSTATE.正常,
        updateUserInfo.paymentStatus = PAYMENTSTATUS.已支付 
    } else {//非一笔订单 要更新会员到期时间 到 用户表
        updateUserInfo.lifespanStartTime = orderInfo.orderCycleStart;
        updateUserInfo.lifespanEndTime = orderInfo.orderCycleEnd;
    }
    if (orderInfo.isFirst) {
        updateUserInfo.isFirstPay = true;
    }
    if (Object.keys(updateUserInfo).length) await updateOneData(TABLEENUM.用户表, {userId:orderInfo.userId}, updateUserInfo);
    
    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.审核时间,
        isReceiveMoney:true,
        remarks:``
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );
    
    return successResult();
}


/**
 * 发票管理-财务核对页-收款退回 success
 * @param param0 
 */
export async function confirmReceiptOut({id, isReceive, returnsReasons}) {
    eccEnumValue("收款退回", "是否收到款项", ISRECEIVE, isReceive)
    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.微信支付无法被退回);

    let updateInfo:any = {confirmReceipt:RECEIPTCONFIRMATION.退回, returnsReasons, isReceive};
    if (orderInfo.isFirst == true) {
        updateInfo.firstPayExamine = false;
    }

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

    //添加日志
    let addLogInfo = {
        orderId:id,
        operationTime:new Date().valueOf(),
        operationBehavior:ORDEREXAMINE.驳回,
        isReceiveMoney:isReceive == ISRECEIVE.未收到款项_xg其他,
        remarks:`${changeEnumValue(ISRECEIVE, isReceive)}`
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    return successResult();
}


/**
 * 发票管理-财务核对页-数据导出
 * @param param0 
 */
export async function outPutConfirmReceipt({exportColumns}) {
    let findParam:any = {
        confirmReceipt:RECEIPTCONFIRMATION.待确认,
        state:ORDERSTATE.已支付
    }

    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"];
    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", "documentId", "uscc", "mail", "unitMail", "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 == "card") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.documentId;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.uscc;
            }
            if (key == "mail") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.mail;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitMail;
            }
            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 (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};
}


/**
 * 发票管理-财务核对页面-审批历史
 * @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"]);
        item.operationTime = moment(item.operationTime).format("YYYY-MM-DD HH:mm:SS");
        item.operationBehavior = changeEnumValue(ORDEREXAMINE, item.operationBehavior);
        dataList.push(item);
    });

    return {dataList};
}


/**
 * 发票管理-待开发票 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 pageNumber 当前页
 */
export async function billStateList({name, memberType, documentId, phone, mail, joinStartTime, joinEndTime, memberLevel, paymentType, isPay, pageNumber}) {
    eccEnumValue("发票列表", "是否支付", ISPAYENUM, isPay );
    let findParam:any = { 
        invoiceStatus:INVOICESTATUS.未开发票
    };

    if (name) {
        findParam["$or"] = [
            {unitName:{"$regex":`${name}`}},
            {name:{"$regex":`${name}`}}
        ]
    }
    if (memberType && memberType.length) {
        if (memberType < UNITMEMBERTYPE.院校) {
            findParam.individualMemberType = {"$in":memberType};
        } else {
            findParam.unitMemberType = {"$in":memberType};
        }
    }
    if (documentId) findParam.documentId = documentId;
    if (phone) findParam.phone = phone;
    if (mail) findParam.mail = mail;
    if (joinStartTime) {
        findParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!findParam["joinTime"]) findParam["joinTime"] = {};
        findParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (memberLevel.length) findParam.memberLevel = {"$in":memberLevel};
    if (paymentType) {
        eccEnumValue("发票列表", "支付类型", PAYMENTTYPE, paymentType);
        findParam.paymentMethod = paymentType;
    }
    if (isPay) findParam.state = isPay;

    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "paymentMethod", "memberCategory", "state", "paymentNum", "userId", "desc", "invoiceMail"];
    let dbList = await findToPage(TABLEENUM.订单表, findParam, selectFile, pageNumber);
    let dataCount = await findCount(TABLEENUM.订单表, findParam);

    let dataList = [];

    let itemFile = ["id", "userId", "unitName", "money", "paymentNum", "memberCategory", "state", "paymentMethod", "desc", "invoiceMail"];
    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);
        let userInfomation = await findOnce(TABLEENUM.用户表, {userId:itemData.userId}, ["userId", "memberState", "name"]);
        itemData.memberState = changeEnumValue(MEMBERSTATE, userInfomation.memberState);
        itemData.cycle = `${moment(info.orderCycleStart).format("YYYY-MM-DD")}至${moment(info.orderCycleEnd).format("YYYY-MM-DD")}`;
        itemData.name = userInfomation.name;
        dataList.push(itemData);
    }

    return {dataList, dataCount};
}


/**
 * 上传发票 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
    };
    await updateOneData(TABLEENUM.订单表, {id}, updateInfo);

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

    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}) {
    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", "money", "paymentMethod", "memberCategory", "paymentNum", "desc", "invoiceMail", "confirmReceiptMs", "payTime"];
    let dbList = await find(TABLEENUM.订单表, findParam, selectFile);
    let timeChnageList = ["orderCycleStart", "operationTime", "confirmReceiptMs", "payTime"];
    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", "unitMail", "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 == "card") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.documentId;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.uscc;
            }
            if (key == "mail") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.mail;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitMail;
            }
            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 == "payTime") {
            //     if (info.paymentMethod != PAYMENTTYPE.微信支付) value = "-"
            // }
            if (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 > 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 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 memberLevel 会员级别/职务 多选
 * 会员级别/职务：【普通会员、理事会员、常务理事会员】
 * @param paymentType 支付方式
 * @param isPay 是否支付
 * @param pageNumber 当前页
 */
export async function invoicedList({name, memberType, documentId, phone, mail, joinStartTime, joinEndTime, memberLevel, paymentType, isPay, pageNumber}) {
    eccEnumValue("发票列表", "支付类型", PAYMENTTYPE, paymentType);
    eccEnumValue("发票列表", "是否支付", ISPAYENUM, isPay );

    let findParam:any = { 
        invoiceStatus:INVOICESTATUS.已开发票
    };
    if (name) {
        findParam["$or"] = [
            {unitName:{"$regex":`${name}`}},
            {name:{"$regex":`${name}`}}
        ]
    }
    if (memberType && memberType.length) {
        if (memberType < UNITMEMBERTYPE.院校) {
            findParam.individualMemberType = {"$in":memberType};
        } else {
            findParam.unitMemberType = {"$in":memberType};
        }
    }
    if (documentId) findParam.documentId = documentId;
    if (phone) findParam.phone = phone;
    if (mail) findParam.mail = mail;
    if (joinStartTime) {
        findParam["joinTime"] = {"$gt":joinStartTime};
    }
    if (joinEndTime) {
        if (!findParam["joinTime"]) findParam["joinTime"] = {};
        findParam["joinTime"]["$lt"] = joinEndTime;
    }
    if (memberLevel && memberLevel.length) findParam.memberLevel = {"$in":memberLevel};
    if (paymentType) findParam.paymentMethod = paymentType;
    if (isPay) findParam.state = isPay

    let selectFile = ["id", "unitName", "orderCycleStart", "orderCycleEnd", "money", "paymentMethod", "memberCategory", "state", "paymentNum", "userId", "desc"];
    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"];
    
    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.isPay = changeEnumValue(ORDERSTATE, itemData.state);
        let userInfo = await findOnce(TABLEENUM.用户表, {userId:itemData.userId}, ["memberState", "name"])
        itemData.memberState = changeEnumValue(MEMBERSTATE, userInfo.memberState);
        itemData.name = userInfo.name;
        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", "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", "unitMail", "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 == "card") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.documentId;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.uscc;
            }
            if (key == "mail") {
                if (info.memberCategory == MEMBERTYPE.个人会员) value = userInfo.mail;
                else if (info.memberCategory == MEMBERTYPE.单位会员) value = userInfo.unitMail;
            }
            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 (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};
}


/**
 * 转账截图、转账单号弹窗
 * @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}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "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 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();
}

export async function applicationInadvanceInvoice({id, mail, desc}) {
    let orderInfo = await findOnce(TABLEENUM.订单表, {id}, ["id", "userId"]);
    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"]);
    if (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", "isSueInvoicesInAdvance", "invoiceStatus"]);
    if (!orderInfo || !orderInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (!orderInfo.isSueInvoicesInAdvance) {
        throw new BizError(ERRORENUM.请先提供发票信息);
    }
    let userInfo = await findOnce(TABLEENUM.用户表, {userId:orderInfo.userId}, ["userId", "unitMemberType"]);
    if (userInfo.unitMemberType != UNITMEMBERTYPE.院校) {
        throw new BizError(ERRORENUM.不可以提前下载发票);
    }

    return {
        invoiceMail:orderInfo.invoiceMail,
        desc:orderInfo.desc,
    };
}



/**
 * 重新申请发票
 * @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({pageNumber}) {
    let findParam:any = { 
        isReceive:ISRECEIVE.提供账户_zkh需退款_ykh
    };

    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", "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"]);
        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) {
                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();
}

