/**
 * 订单相关 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" ];
    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.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"]);
        if (userInfo) itemData.memberState = changeEnumValue(MEMBERSTATE, userInfo.memberState);
        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.收款确认};
    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);
    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.提供账户_zkh需退款_ykh,
        remarks:`${changeEnumValue(ISRECEIVE, isReceive)}`
    };
    await addOneData(TABLEENUM.订单审批历史表, addLogInfo );

    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 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" ];
    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"];
    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.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);

    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();
}


/**
 * 发票管理-已开发票 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" ];
    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"];
    
    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.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 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"];
    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} = 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.下载发票;
        if (info.invoiceStatus != INVOICESTATUS.已开发票 && info.advanceInvoice) invoiceState = MYORDERLISTSTATE.申请进度;
        if (info.invoiceStatus != INVOICESTATUS.已开发票 && !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
        };
        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();
}


/**
 * 重新申请发票
 * @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);

    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.refundBankCarId}`
    };
    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();
}



/**
 * 审批历史
 */
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 addInfo:any = {
    //         operationTime:moment(operationTime).format("YYYY-MM-DD HH:mm:SS"),
    //         operationBehavior:changeEnumValue(ORDEREXAMINE, info.operationBehavior),
    //         remarks,
    //         other
    //     };
    //     if (info.refundImgUrl) {
    //         addInfo.refundImgUrl = refundImgUrl;
    //     }
    // } );
}




