package cn.superdesk.uniorder.service.thirdpart.qchjc.account.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceApplyStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceMakeStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditTypeDefaultEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.qchjc.QchjcOrgEnum;
import cn.superdesk.uniorder.common.exception.OpenApiException;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplierXGoods;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplierXGoodsExample;
import cn.superdesk.uniorder.dao.entity.base.*;
import cn.superdesk.uniorder.dao.entity.invoice.supplier.InvoiceApplySupplierXGoods;
import cn.superdesk.uniorder.dao.entity.invoice.supplier.InvoiceApplySupplierXGoodsExample;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.accounting.*;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcEnterpriseEntity;
import cn.superdesk.uniorder.dao.entity.thirdpart.qchjc.organisation.QchjcSupplierEntity;
import cn.superdesk.uniorder.dao.mapper.accounting.unified.supplier.AccountingUnifiedSupplierXGoodsMapper;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dao.mapper.invoice.supplier.InvoiceApplySupplierXGoodsMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcOrderEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcOrderGoodsEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.accounting.QchjcUserEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcEnterpriseEntityMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.qchjc.organisation.QchjcSupplierEntityMapper;
import cn.superdesk.uniorder.dto.param.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.param.setting.UnifiedServicePartGoodsTransportParam;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.order.QchjcJdOrderGoodsParamReceive;
import cn.superdesk.uniorder.dto.param.thirdpart.qchjc.order.QchjcJdOrderParamReceive;
import cn.superdesk.uniorder.service.order.base.CommonMergeRefundOrderProcessService;
import cn.superdesk.uniorder.service.setting.UnifiedServiceService;
import cn.superdesk.uniorder.service.thirdpart.qchjc.account.QchjcSupplierJdOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author xc
 * @description
 * @date 2022/6/17 16:25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QchjcSupplierJdOrderServiceImpl implements QchjcSupplierJdOrderService {

    private final UnifiedOrderMapper unifiedOrderMapper;
    private final UnifiedOrderMapperEx unifiedOrderMapperEx;
    private final UnifiedOrderGoodsMapper unifiedOrderGoodsMapper;
    private final UnifiedOrderGoodsMapperEx unifiedOrderGoodsMapperEx;
    private final UnifiedOrderCreditMapper unifiedOrderCreditMapper;
    private final UnifiedOrderCreditMapperEx unifiedOrderCreditMapperEx;
    private final QchjcEnterpriseEntityMapper qchjcEnterpriseEntityMapper;
    private final QchjcSupplierEntityMapper qchjcSupplierEntityMapper;
    private final QchjcUserEntityMapper qchjcUserEntityMapper;
    private final UnifiedServiceService unifiedServiceService;
    private final QchjcOrderEntityMapper qchjcOrderEntityMapper;
    private final QchjcOrderGoodsEntityMapper qchjcOrderGoodsEntityMapper;

    private final CommonMergeRefundOrderProcessService commonMergeOrderProcessService;

    private final AccountingUnifiedSupplierXGoodsMapper accountingUnifiedSupplierXGoodsMapper;
    private final InvoiceApplySupplierXGoodsMapper invoiceApplySupplierXGoodsMapper;


    /**
     * 集采京东对账订单接收
     *
     * @param data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiveJdOrder(String data) {
        QchjcJdOrderParamReceive qchjcJdOrderParamReceive = AnJsonUtils.toObject(data, QchjcJdOrderParamReceive.class);

        //检查企业是否已存在
        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getPurchaseVirtId());
        if (qchjcEnterpriseEntity == null || qchjcEnterpriseEntity.getUnifiedId() == null) {
            throw new OpenApiException(500, "该订单所属的采购单位不存在，请先推送采购单位");
        }
        //检查供应商是否已存在
        QchjcSupplierEntity qchjcSupplierEntity = qchjcSupplierEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getSupplierId());
        if (qchjcSupplierEntity == null || qchjcSupplierEntity.getUnifiedId() == null) {
            throw new OpenApiException(500, "该订单所属的供应商不存在，请先推送供应商");
        }

        //检查订单在中间表是否已同步
        String orderSn = qchjcJdOrderParamReceive.getOrderSn();
        QchjcOrderEntityExample qchjcOrderEntityExample = new QchjcOrderEntityExample();
        qchjcOrderEntityExample.createCriteria().andOrderSnEqualTo(orderSn);
        List<QchjcOrderEntity> qchjcOrderEntities = qchjcOrderEntityMapper.selectByExample(qchjcOrderEntityExample);
        if (CollectionUtils.isEmpty(qchjcOrderEntities) || qchjcOrderEntities.get(0) == null) {
            /**
             * 订单不存在 - 需要区分正单和退单
             */
            if (CommonOrderTypeEnum.订单.getKey().equals(qchjcJdOrderParamReceive.getOrderType())) {
                //正单
                handleNotExistOrder(qchjcJdOrderParamReceive);
            } else {
                //退单
                //handleNotExistRefundOrder(qchjcJdOrderParamReceive);
            }

        } else {
            /**
             * 订单已存在 - 需要区分正单和退单
             */
            if (CommonOrderTypeEnum.订单.getKey().equals(qchjcJdOrderParamReceive.getOrderType())) {
                //正单
                handleExistOrder(qchjcJdOrderParamReceive);
            } else {
                //退单
                //handleExistRefundOrder(qchjcJdOrderParamReceive);
            }
        }
    }

    @Override
    public void fix(Integer limit, String supplierAccountingOrderSn) {
        StringBuilder sb = new StringBuilder();
        List<Long> idList = qchjcOrderGoodsEntityMapper.selectFixId(limit);
        for (Long qchjcId : idList) {
            QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntityMapper.selectByPrimaryKey(qchjcId);
            if (qchjcOrderGoodsEntity == null) {
                sb.append(qchjcId).append(",").append("中间表商品不存在").append("\n");
                continue;
            }
            UnifiedOrderGoods unifiedOrderGoods = unifiedOrderGoodsMapper.selectByPrimaryKey(qchjcOrderGoodsEntity.getUnifiedId());
            if (unifiedOrderGoods == null) {
                sb.append(qchjcOrderGoodsEntity.getUnifiedId()).append(",").append("统一订单商品不存在").append("\n");
                continue;
            }
            /**
             * 更新商品表
             */
            unifiedOrderGoods.setGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getGoodsId()));
            unifiedOrderGoods.setOutSnapshotOrderGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getOutSnapshotOrderGoodsId()));
            unifiedOrderGoodsMapper.updateByPrimaryKeySelective(unifiedOrderGoods);

            UnifiedOrderCredit unifiedOrderCredit = unifiedOrderCreditMapper.selectByPrimaryKey(qchjcOrderGoodsEntity.getUnifiedCreditId());
            if (unifiedOrderCredit == null) {
                sb.append(qchjcOrderGoodsEntity.getUnifiedCreditId()).append(",").append("统一订单流水不存在").append("\n");
                continue;
            }
            /**
             * 更新流水表
             */
            unifiedOrderCredit.setGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getGoodsId()));
            unifiedOrderCreditMapper.updateByPrimaryKeySelective(unifiedOrderCredit);
        }
        try {
            if (sb.length() > 0) {
                FileUtils.writeStringToFile(new File("/data/fix.txt"), sb.toString(), "UTF-8", true);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

        StringBuilder sb2 = new StringBuilder();
        //处理供应商的
        String[] split = supplierAccountingOrderSn.split(",");
        for (String s : split) {
            QchjcOrderGoodsEntityExample qchjcOrderGoodsEntityExample = new QchjcOrderGoodsEntityExample();
            qchjcOrderGoodsEntityExample.createCriteria().andSupplierAccountingOrderSnEqualTo(s);
            List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(qchjcOrderGoodsEntityExample);
            if (CollectionUtils.isEmpty(qchjcOrderGoodsEntities)) {
                sb2.append(s).append(",").append("供应商订单商品不存在").append("\n");
                continue;
            }

            for (QchjcOrderGoodsEntity qchjcOrderGoodsEntity : qchjcOrderGoodsEntities) {
                Long unifiedId = qchjcOrderGoodsEntity.getUnifiedId();
                UnifiedOrderGoods unifiedOrderGoods = unifiedOrderGoodsMapper.selectByPrimaryKey(unifiedId);
                if (unifiedOrderGoods == null) {
                    sb2.append(unifiedId).append(",").append("统一订单商品不存在").append("\n");
                    continue;
                }
                //更新accounting_unified_supplier_x_goods这部分记录的goods_id和outSnapshotOrderGoodsId
                AccountingUnifiedSupplierXGoodsExample accountingUnifiedSupplierXGoodsExample = new AccountingUnifiedSupplierXGoodsExample();
                accountingUnifiedSupplierXGoodsExample.createCriteria().andUnifiedOrderGoodsIdEqualTo(unifiedOrderGoods.getId());
                List<AccountingUnifiedSupplierXGoods> accountingUnifiedSupplierXGoodsList = accountingUnifiedSupplierXGoodsMapper.selectByExample(accountingUnifiedSupplierXGoodsExample);
                if (CollectionUtils.isEmpty(accountingUnifiedSupplierXGoodsList)) {
                    sb2.append(unifiedOrderGoods.getId()).append(",").append("accounting_unified_supplier_x_goods不存在").append("\n");
                    continue;
                }
                AccountingUnifiedSupplierXGoods accountingUnifiedSupplierXGoods = accountingUnifiedSupplierXGoodsList.get(0);
                accountingUnifiedSupplierXGoods.setGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getGoodsId()));
                accountingUnifiedSupplierXGoods.setOutSnapshotOrderGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getOutSnapshotOrderGoodsId()));
                accountingUnifiedSupplierXGoodsMapper.updateByPrimaryKeySelective(accountingUnifiedSupplierXGoods);


                //更新invoice_apply_supplier_x_goods这部分记录的goods_id
                InvoiceApplySupplierXGoodsExample invoiceApplySupplierXGoodsExample = new InvoiceApplySupplierXGoodsExample();
                invoiceApplySupplierXGoodsExample.createCriteria().andUnifiedOrderGoodsIdEqualTo(unifiedOrderGoods.getId());
                List<InvoiceApplySupplierXGoods> invoiceApplySupplierXGoodsList = invoiceApplySupplierXGoodsMapper.selectByExample(invoiceApplySupplierXGoodsExample);
                if (CollectionUtils.isEmpty(invoiceApplySupplierXGoodsList)) {
                    sb2.append(unifiedId).append(",").append("发票申请 x 商品不存在").append("\n");
                    continue;
                }
                InvoiceApplySupplierXGoods invoiceApplySupplierXGoods = invoiceApplySupplierXGoodsList.get(0);
                invoiceApplySupplierXGoods.setGoodsId(Long.parseLong(qchjcOrderGoodsEntity.getGoodsId()));
                invoiceApplySupplierXGoodsMapper.updateByPrimaryKeySelective(invoiceApplySupplierXGoods);

            }
        }

        try {
            if (sb2.length() > 0) {
                FileUtils.writeStringToFile(new File("/data/fix_supplier.txt"), sb.toString(), "UTF-8", true);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 处理中间表不存在的京东正单
     *
     * @param qchjcJdOrderParamReceive
     */
    private void handleNotExistOrder(QchjcJdOrderParamReceive qchjcJdOrderParamReceive) {
        /**
         * 构造order_id，goods_id， 由于集采都是uuid，所以这里要多走一步中间表获取自增的id
         */
        //订单 插入 集采订单中间表 获取自增id
        QchjcOrderEntity order = convertQchJdParam2QchEntity(qchjcJdOrderParamReceive, null);
        qchjcOrderEntityMapper.insertSelective(order);
        qchjcJdOrderParamReceive.setId(order.getId());//回写中间表的id
        //商品 插入 集采订单商品中间表 获取自增id
        List<QchjcJdOrderGoodsParamReceive> orderGoodsSelected = qchjcJdOrderParamReceive.getOrderGoodsSelected();
        String orderSn = order.getOrderSn();
        for (QchjcJdOrderGoodsParamReceive goodsParam : orderGoodsSelected) {
            QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(goodsParam, null, orderSn);
            qchjcOrderGoodsEntityMapper.insertSelective(orderGoods);
            goodsParam.setId(orderGoods.getId());//回写中间表的id
        }

        /**
         * 构造数据 插入统一订单表
         */
        UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
        convertQchJdOrderParam2OrderEntity(qchjcJdOrderParamReceive, unifiedOrderEntity);
        //处理商品
        List<UnifiedOrderGoods> processUnifiedOrderGoodsList = new ArrayList<>();
        List<Predicate<QchjcJdOrderGoodsParamReceive>> predicates = new ArrayList<>();
        predicates.add(r -> null != r.getSellingPrice() && r.getSellingPrice().compareTo(BigDecimal.ZERO) > 0);
        predicates.add(r -> null != r.getCostPrice() && r.getCostPrice().compareTo(BigDecimal.ZERO) > 0);
        List<QchjcJdOrderGoodsParamReceive> scoreOrderGoodsReceiveParamFilterList = AnLamdaUtils.filters(orderGoodsSelected, predicates);
        if (CollectionUtils.isEmpty(scoreOrderGoodsReceiveParamFilterList)) {
            log.info("scoreOrderGoodsReceiveParamFilterList is empty, orderSn : {}", qchjcJdOrderParamReceive.getOrderSn());
            throw new OpenApiException(500, "过滤后商品列表为空");
        }
        //订单商品vo转换为统一订单商品实体,并构造流水
        List<UnifiedOrderCredit> processUnifiedOrderCreditList = new ArrayList<>();
        scoreOrderGoodsReceiveParamFilterList.forEach(goodsParam -> {
            //转为商品实体
            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
            convertQchJdOrderGoodsParam2Entity(goodsParam, unifiedOrderGoods);
            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
            processUnifiedOrderGoodsList.add(unifiedOrderGoods);
            //构造流水
            UnifiedOrderCredit scoreOrderCredit = new UnifiedOrderCredit();
            convertQchJdOrderGoodsParam2CreditEntity(goodsParam, scoreOrderCredit, qchjcJdOrderParamReceive);
            scoreOrderCredit.setOrderSn(unifiedOrderEntity.getOrderSn());
            processUnifiedOrderCreditList.add(scoreOrderCredit);
        });

        //流水、商品、订单入库
        if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {
            //订单
            unifiedOrderMapper.insertSelective(unifiedOrderEntity);
            //商品
            for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
                unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
            }
            //流水
            for (UnifiedOrderCredit unifiedOrderCredit : processUnifiedOrderCreditList) {
                unifiedOrderCreditMapper.insert(unifiedOrderCredit);
            }
        }
        /**
         * 处理锁单状态 - 根据订单的 完成状态
         */
        CommonOrderCompletStateEnum commonOrderCompletStateEnum = CommonOrderCompletStateEnum.get(qchjcJdOrderParamReceive.getCompletState());
        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
        Date finishTime    = qchjcJdOrderParamReceive.getFinishTime();
        handleAccountingLockStatus(orderSn, commonOrderCompletStateEnum, callback, finishTime);
    }

    /**
     * 处理中间表不存在的京东退单
     *
     * @param qchjcJdOrderParamReceive
     */
//    private void handleNotExistRefundOrder(QchjcJdOrderParamReceive qchjcJdOrderParamReceive) {
//        /**
//         * 先判断正单有没有推过来
//         */
//        String refundOrderSn = qchjcJdOrderParamReceive.getRefundOrderSn();//正单sn
//        UnifiedOrderExample unifiedOrderExample = new UnifiedOrderExample();
//        unifiedOrderExample.createCriteria().andOrderSnEqualTo(refundOrderSn);
//        List<UnifiedOrder> unifiedOrders = unifiedOrderMapper.selectByExample(unifiedOrderExample);
//        if (CollectionUtils.isEmpty(unifiedOrders) || unifiedOrders.get(0) == null) {
//            throw new OpenApiException(500, "正单不存在，需要先推送正单");
//        }
//        //订单保存到中间表 获取自增id
//        QchjcOrderEntity order = convertQchJdParam2QchEntity(qchjcJdOrderParamReceive, null);
//        qchjcOrderEntityMapper.insertSelective(order);
//        qchjcJdOrderParamReceive.setId(order.getId());//回写中间表的id
//        //商品保存到中间表 获取自增id
//        List<QchjcJdOrderGoodsParamReceive> orderGoodsSelected = qchjcJdOrderParamReceive.getOrderGoodsSelected();
//        String orderSn = order.getOrderSn();//退单的sn
//        for (QchjcJdOrderGoodsParamReceive goodsParam : orderGoodsSelected) {
//            QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(goodsParam, null, orderSn);
//            qchjcOrderGoodsEntityMapper.insertSelective(orderGoods);
//            goodsParam.setId(orderGoods.getId());//回写中间表的id
//        }
//        /**
//         * 构造数据 插入统一订单表
//         */
//        UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
//        convertQchJdOrderParam2OrderEntity(qchjcJdOrderParamReceive, unifiedOrderEntity);
//        //处理商品
//        List<UnifiedOrderGoods> processUnifiedOrderGoodsList = new ArrayList<>();
//        List<Predicate<QchjcJdOrderGoodsParamReceive>> predicates = new ArrayList<>();
//        predicates.add(r -> null != r.getSellingPrice() && r.getSellingPrice().compareTo(BigDecimal.ZERO) > 0);
//        predicates.add(r -> null != r.getCostPrice() && r.getCostPrice().compareTo(BigDecimal.ZERO) > 0);
//        List<QchjcJdOrderGoodsParamReceive> scoreOrderGoodsReceiveParamFilterList = AnLamdaUtils.filters(orderGoodsSelected, predicates);
//        if (CollectionUtils.isEmpty(scoreOrderGoodsReceiveParamFilterList)) {
//            log.info("scoreOrderGoodsReceiveParamFilterList is empty, orderSn : {}", qchjcJdOrderParamReceive.getOrderSn());
//            throw new OpenApiException(500, "过滤后商品列表为空");
//        }
//        //订单商品vo转换为统一订单商品实体,并构造流水
//        List<UnifiedOrderCredit> processUnifiedOrderCreditList = new ArrayList<>();
//        scoreOrderGoodsReceiveParamFilterList.forEach(goodsParam -> {
//            //转为商品实体
//            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
//            convertQchJdOrderGoodsParam2Entity(goodsParam, unifiedOrderGoods);
//            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
//            processUnifiedOrderGoodsList.add(unifiedOrderGoods);
//            //构造流水
//            UnifiedOrderCredit scoreOrderCredit = new UnifiedOrderCredit();
//            convertQchJdOrderGoodsParam2CreditEntity(goodsParam, scoreOrderCredit, qchjcJdOrderParamReceive);
//            scoreOrderCredit.setOrderSn(unifiedOrderEntity.getOrderSn());
//            processUnifiedOrderCreditList.add(scoreOrderCredit);
//        });
//
//        //流水、商品、订单入库
//        if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {
//            //订单
//            unifiedOrderMapper.insertSelective(unifiedOrderEntity);
//            //商品
//            for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
//                unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
//            }
//            //流水
//            for (UnifiedOrderCredit unifiedOrderCredit : processUnifiedOrderCreditList) {
//                unifiedOrderCreditMapper.insert(unifiedOrderCredit);
//            }
//            //把退单的sn 更新到 统一订单正单的 refundSn字段
//            UnifiedOrder unifiedOrder = unifiedOrders.get(0);
//            UnifiedOrder updateOrder = new UnifiedOrder();
//            updateOrder.setId(unifiedOrder.getId());
//            updateOrder.setRefundOrderSn(qchjcJdOrderParamReceive.getOrderSn());
//            unifiedOrderMapper.updateByPrimaryKeySelective(updateOrder);
//        }
//
//        /**
//         * 处理锁单状态 - 根据售后单的 完成状态
//         */
//        CommonOrderCompletStateEnum commonOrderCompletStateEnum = CommonOrderCompletStateEnum.get(qchjcJdOrderParamReceive.getCompletState());
//        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
//        Date finishTime    = qchjcJdOrderParamReceive.getFinishTime();
//        handleAccountingLockStatus(refundOrderSn, orderSn, commonOrderCompletStateEnum, callback, finishTime);
//
//    }

    /**
     * 处理订单锁定状态
     * @param orderSn 正单的sn
     * @param commonOrderCompletStateEnum
     * @param callback
     * @param finishTime
     */
    private void handleAccountingLockStatus(String orderSn, CommonOrderCompletStateEnum commonOrderCompletStateEnum, UnifiedOrderIssuesFlowingParam callback, Date finishTime) {
        switch (commonOrderCompletStateEnum) {
            case 未完成:
                // 锁定正单
                // 锁定负单
//				commonMergeOrderProcessService.lockByOrderSn(hedgeUnifiedOrder.getOrderSn());
//				commonMergeOrderProcessService.lockByOrderSn(refundOrderSn);
                commonMergeOrderProcessService.lockByOrderSn(orderSn);
                //commonMergeOrderProcessService.lockByOrderSn(refundOrderSn);
                break;
            case 已完成:
                // 解锁正单 更新结算时间
                // 解锁负单 更新结算时间
                commonMergeOrderProcessService.unlockByOrderSn(orderSn);
                //commonMergeOrderProcessService.unlockByOrderSn(refundOrderSn);

                // TODO 结算时间逻辑 添加 mark by linjinyu at 20211112
                // |---- 1. kafka 正向通道,触发点 订单已完成 产生 结算时间(订单完成时间填充) right
                // |---- 2. kafka 负向通道,解发点 退单已完成 解锁正负单时 产生结算时间(退单完成时间填充) right
                // |---- 3. 供应商结算 未对账商品 list 逻辑 不变(没说明) 看样子是 加了个 结算时间 筛选逻辑
                commonMergeOrderProcessService.processBizOrderRecordAccountingTime(orderSn, "", finishTime, callback);
                break;
            case 已作废:
                // 解锁正单 更新结算时间
                // 解锁负单 更新结算时间
                commonMergeOrderProcessService.unlockByOrderSn(orderSn);
                //commonMergeOrderProcessService.unlockByOrderSn(refundOrderSn);
                commonMergeOrderProcessService.processBizOrderRecordAccountingTime(orderSn, "", finishTime, callback);
                break;
        }
    }

    /**
     * 处理中间表存在的京东订单
     *
     * @param qchjcJdOrderParamReceive
     */
    private void handleExistOrder(QchjcJdOrderParamReceive qchjcJdOrderParamReceive) {
        QchjcOrderEntityExample qchjcOrderEntityExample = new QchjcOrderEntityExample();
        qchjcOrderEntityExample.createCriteria().andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn());
        List<QchjcOrderEntity> qchjcOrderEntities = qchjcOrderEntityMapper.selectByExample(qchjcOrderEntityExample);
        qchjcJdOrderParamReceive.setId(qchjcOrderEntities.get(0).getId());
        //同样的 取商品的id，如果不存在的商品需要新增
        List<QchjcJdOrderGoodsParamReceive> orderGoodsSelected = qchjcJdOrderParamReceive.getOrderGoodsSelected();
        for (QchjcJdOrderGoodsParamReceive qchjcJdOrderGoodsParamReceive : orderGoodsSelected) {
            QchjcOrderGoodsEntityExample qchjcOrderGoodsEntityExample = new QchjcOrderGoodsEntityExample();
            qchjcOrderGoodsEntityExample.createCriteria()
                    .andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn())
                    .andOutSnapshotOrderGoodsIdEqualTo(qchjcJdOrderGoodsParamReceive.getOutSnapshotOrderGoodsId());
            List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(qchjcOrderGoodsEntityExample);
            if (CollectionUtils.isNotEmpty(qchjcOrderGoodsEntities) && qchjcOrderGoodsEntities.get(0) != null) {
                //已存在，直接取id，并更新中间表数据
                QchjcOrderGoodsEntity qchjcOrderGoodsEntity = qchjcOrderGoodsEntities.get(0);
                qchjcJdOrderGoodsParamReceive.setId(qchjcOrderGoodsEntity.getId());
                QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(qchjcJdOrderGoodsParamReceive, null, qchjcJdOrderParamReceive.getOrderSn());
                orderGoods.setId(qchjcOrderGoodsEntity.getId());
                qchjcOrderGoodsEntityMapper.updateByPrimaryKeySelective(orderGoods);
            }else {
                //不存在，新增 取id
                QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(qchjcJdOrderGoodsParamReceive, null, qchjcJdOrderParamReceive.getOrderSn());
                qchjcOrderGoodsEntityMapper.insertSelective(orderGoods);
                qchjcJdOrderGoodsParamReceive.setId(orderGoods.getId());//回写中间表的id
            }
        }

        /**
         * 构造数据
         */
        UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
        convertQchJdOrderParam2OrderEntity(qchjcJdOrderParamReceive, unifiedOrderEntity);
        //处理商品
        List<UnifiedOrderGoods> processUnifiedOrderGoodsList = new ArrayList<>();
        List<Predicate<QchjcJdOrderGoodsParamReceive>> predicates = new ArrayList<>();
        predicates.add(r -> null != r.getSellingPrice() && r.getSellingPrice().compareTo(BigDecimal.ZERO) > 0);
        predicates.add(r -> null != r.getCostPrice() && r.getCostPrice().compareTo(BigDecimal.ZERO) > 0);
        List<QchjcJdOrderGoodsParamReceive> scoreOrderGoodsReceiveParamFilterList = AnLamdaUtils.filters(orderGoodsSelected, predicates);
        if (CollectionUtils.isEmpty(scoreOrderGoodsReceiveParamFilterList)) {
            log.info("scoreOrderGoodsReceiveParamFilterList is empty, orderSn : {}", qchjcJdOrderParamReceive.getOrderSn());
            throw new OpenApiException(500, "过滤后商品列表为空");
        }
        //订单商品vo转换为统一订单商品实体,并构造流水
        List<UnifiedOrderCredit> processUnifiedOrderCreditList = new ArrayList<>();
        scoreOrderGoodsReceiveParamFilterList.forEach(goodsParam -> {
            //转为商品实体
            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
            convertQchJdOrderGoodsParam2Entity(goodsParam, unifiedOrderGoods);
            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
            processUnifiedOrderGoodsList.add(unifiedOrderGoods);
            //构造流水
            UnifiedOrderCredit scoreOrderCredit = new UnifiedOrderCredit();
            convertQchJdOrderGoodsParam2CreditEntity(goodsParam, scoreOrderCredit, qchjcJdOrderParamReceive);
            scoreOrderCredit.setOrderSn(unifiedOrderEntity.getOrderSn());
            processUnifiedOrderCreditList.add(scoreOrderCredit);
        });

        //判断统一订单是否存在
        UnifiedOrderExample unifiedOrderExample = new UnifiedOrderExample();
        unifiedOrderExample.createCriteria().andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn());
        List<UnifiedOrder> unifiedOrders = unifiedOrderMapper.selectByExample(unifiedOrderExample);
        if(CollectionUtils.isEmpty(unifiedOrders) || unifiedOrders.get(0) == null) {
            /**
             * 统一订单不存在，新增
             */
            if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {
                //订单
                unifiedOrderMapper.insertSelective(unifiedOrderEntity);
                //商品
                for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
                    unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
                }
                //流水
                for (UnifiedOrderCredit unifiedOrderCredit : processUnifiedOrderCreditList) {
                    unifiedOrderCreditMapper.insert(unifiedOrderCredit);
                }
            }
        }
        else {
            /**
             * 统一订单存在，更新
             */

            UnifiedOrder unifiedOrder = unifiedOrders.get(0);
            /**
             * 判断该订单数据与该企业&供应商对账状态
             */
            //判断订单下的商品是否对过账
            UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
            unifiedOrderGoodsExample.createCriteria().andOrderSnEqualTo(unifiedOrder.getOrderSn())
                    .andAccountingStateSupplierEqualTo(CommonAccountingStateEnum.已对账.getKey());
            List<UnifiedOrderGoods> alreadyAccounting = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);

            //判断订单下的明细是否已经对过账
            UnifiedOrderCreditExample unifiedOrderCreditExample = new UnifiedOrderCreditExample();
            unifiedOrderCreditExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
                    .andAccountingStateCustomerEqualTo(CommonAccountingStateEnum.已对账.getKey());
            List<UnifiedOrderCredit> unifiedOrderCredits = unifiedOrderCreditMapper.selectByExample(unifiedOrderCreditExample);


            if (CollectionUtils.isNotEmpty(alreadyAccounting) || CollectionUtils.isNotEmpty(unifiedOrderCredits)) {
                /**
                 * 已经参与对账的处理，只更新部分字段
                  */
                //订单
                processAlreadyAccountingUnifiedOrder(unifiedOrderEntity,unifiedOrder);
                /**
                 * 最终入库的商品数据和流水数据
                 */
                List<UnifiedOrderGoods> finalUnifiedOrderGoodsList = new ArrayList<>();
                List<UnifiedOrderCredit> finalUnifiedOrderCreditList = new ArrayList<>();
                //商品
                processAlreadyAccountingUnifiedOrderGoods(unifiedOrderEntity, processUnifiedOrderGoodsList,finalUnifiedOrderGoodsList);
                //流水
                processAlreadyAccountingUnifiedOrderCredit(unifiedOrderEntity, processUnifiedOrderCreditList,finalUnifiedOrderCreditList);

            }else {
                //未参与对账

                /**
                 * 重推订单处理
                 */
                unifiedOrderEntity.setId(unifiedOrder.getId());
                unifiedOrderEntity.setUpdateTime(DateUtil.date());
                //对账状态不更新，保持原状态不变
                unifiedOrderEntity.setAccountingStateCustomer(unifiedOrder.getAccountingStateCustomer());
                unifiedOrderEntity.setAccountingStateSupplier(unifiedOrder.getAccountingStateSupplier());
                unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrderEntity);
                /**
                 * 最终入库的商品数据和流水数据
                 */
                List<UnifiedOrderGoods> finalUnifiedOrderGoodsList = new ArrayList<>();
                List<UnifiedOrderCredit> finalUnifiedOrderCreditList = new ArrayList<>();
                /**
                 * 重推商品处理
                 */
                processUnifiedOrderGoodsFromQchjc(unifiedOrderEntity, processUnifiedOrderGoodsList,finalUnifiedOrderGoodsList);
                /**
                 * 重推流水处理
                 */
                processUnifiedOrderCreditFromQchjc(unifiedOrderEntity, processUnifiedOrderCreditList,finalUnifiedOrderCreditList);
            }
        }
        /**
         * 处理锁单状态 - 根据订单的 完成状态
         */
        CommonOrderCompletStateEnum commonOrderCompletStateEnum = CommonOrderCompletStateEnum.get(qchjcJdOrderParamReceive.getCompletState());
        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
        Date finishTime    = qchjcJdOrderParamReceive.getFinishTime();
        handleAccountingLockStatus(qchjcJdOrderParamReceive.getOrderSn(), commonOrderCompletStateEnum, callback, finishTime);
    }

    /**
     * 处理重推的 已参与对账的京东订单商品流水
     * @param unifiedOrderEntity
     * @param processUnifiedOrderCreditList
     * @param finalUnifiedOrderCreditList
     */
    private void processAlreadyAccountingUnifiedOrderCredit(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderCredit> processUnifiedOrderCreditList, List<UnifiedOrderCredit> finalUnifiedOrderCreditList) {
        UnifiedOrderCreditExample          orderCreditExample4SaveOrUpdate  = new UnifiedOrderCreditExample();
        orderCreditExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());

        List<UnifiedOrderCredit> existsDatabaseUnifiedOrderCreditList = unifiedOrderCreditMapper.selectByExample(orderCreditExample4SaveOrUpdate);

        log.info("\n\n\nOrderCredit: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsDatabaseUnifiedOrderCreditList),
                AnJsonUtils.toJson(processUnifiedOrderCreditList)
        );


        for (UnifiedOrderCredit processOrderCredit : processUnifiedOrderCreditList) {

            // 新过来的数据在老的是不是存在
            List<UnifiedOrderCredit> findByManyOrderCreditList          = null;

            // 查询条件 如果 goods_id 为 0 条数大于 1 是会有问题 0 默认只有运费 , 如果 附件与赠品过来的情况 就会有问题,具体的问题再写吧
            List<Predicate<UnifiedOrderCredit>> predicatesByMany = new ArrayList<>();
            // 20201016 add start 从数据上看,是会有可能 同样的 orderId 不同的 orderSn
            predicatesByMany.add(
                    r -> r.getOrderSn().equals(processOrderCredit.getOrderSn())
                            && r.getOrderId().equals(processOrderCredit.getOrderId())
                            && r.getGoodsId().equals(processOrderCredit.getGoodsId())
                            && r.getCreditType().equals(processOrderCredit.getCreditType())
                            && r.getCreditName().equals(processOrderCredit.getCreditName())
                            && r.getBalance().compareTo(processOrderCredit.getBalance()) == 0
                            && r.getBatchs().equals(processOrderCredit.getBatchs())
            );
            // 20201016 add end
            // 新过来的数据在老的是不是存在
            findByManyOrderCreditList = AnLamdaUtils.filters(existsDatabaseUnifiedOrderCreditList, predicatesByMany);


            if (CollectionUtils.isNotEmpty(findByManyOrderCreditList)) {

                UnifiedOrderCredit findedOrderCredit = findByManyOrderCreditList.get(0);

                partialOverWriteCreditField(processOrderCredit, findedOrderCredit);

                findedOrderCredit.setUpdateUserId(3L);
                findedOrderCredit.setUpdateTime(DateUtil.date());

                finalUnifiedOrderCreditList.add(findedOrderCredit);
            }
            // 两种情况都不存 才会作为新数据插入
            else {
                finalUnifiedOrderCreditList.add(processOrderCredit);
            }

            unifiedOrderCreditMapper.deleteByExample(orderCreditExample4SaveOrUpdate);
            for (UnifiedOrderCredit unifiedOrderCredit : finalUnifiedOrderCreditList) {
                if (unifiedOrderCredit.getId() == null || unifiedOrderCredit.getId() == 0) {
                    unifiedOrderCreditMapper.insertSelective(unifiedOrderCredit);
                }else {
                    unifiedOrderCreditMapperEx.insertSelectiveWithoutReturnId(unifiedOrderCredit);
                }
            }
        }
    }

    /**
     * 处理重推的 已参与对账的京东订单商品
     * @param unifiedOrderEntity
     * @param processUnifiedOrderGoodsList
     * @param finalUnifiedOrderGoodsList
     */
    private void processAlreadyAccountingUnifiedOrderGoods(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderGoods> processUnifiedOrderGoodsList, List<UnifiedOrderGoods> finalUnifiedOrderGoodsList) {
        /**
         * 该商品订单的部分字段的数据可更新，参照结算中心现有的可更新字段（比如：商品名称、平台/商户税务分类编码、结算时间、快递单号等其他字段）；
         * 该商品订单的部分字段的数据不更新（比如：企业ID、供应商ID、销售单价、商品数量、销售总价、成本单价、成本总价、平台&商户税率）；
         * 其与企业和供应商对账状态不更新，保持原状态不变。
         */
        UnifiedOrderGoodsExample          orderGoodsExample4SaveOrUpdate  = new UnifiedOrderGoodsExample();
        orderGoodsExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());
        //结算中心数据库中已存在的商品
        List<UnifiedOrderGoods> existsUnifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(orderGoodsExample4SaveOrUpdate);
        log.info("\n\n\nOrderGoods: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsUnifiedOrderGoodsList),
                AnJsonUtils.toJson(processUnifiedOrderGoodsList)
        );


        // 拿着过来的数据 去 查 数据库的
        for (UnifiedOrderGoods processOrderGoods : processUnifiedOrderGoodsList) {

            // 查询数据库中是否存在
            UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
            unifiedOrderGoodsExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
                    .andOutSnapshotOrderGoodsIdEqualTo(processOrderGoods.getOutSnapshotOrderGoodsId());
            List<UnifiedOrderGoods> findByOutSnapshotIdOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);


            //如果该商品已存在，则更新该商品数据
            if (CollectionUtils.isNotEmpty(findByOutSnapshotIdOrderGoodsList)) {
                UnifiedOrderGoods findedBySnapshotIdOrderGoods = findByOutSnapshotIdOrderGoodsList.get(0);

                partialOverWriteGoodsField(processOrderGoods, findedBySnapshotIdOrderGoods);
                finalUnifiedOrderGoodsList.add(findedBySnapshotIdOrderGoods);
            } else {
                finalUnifiedOrderGoodsList.add(processOrderGoods);
            }
        }
        // 删除后重新插入数据
        unifiedOrderGoodsMapper.deleteByExample(orderGoodsExample4SaveOrUpdate);
        for (UnifiedOrderGoods unifiedOrderGoods : finalUnifiedOrderGoodsList) {
            if (unifiedOrderGoods.getId() == null || unifiedOrderGoods.getId() == 0) {
                unifiedOrderGoodsMapper.insertSelective(unifiedOrderGoods);
            } else {
                unifiedOrderGoodsMapperEx.insertSelectiveWithoutReturnId(unifiedOrderGoods);
            }
        }
        //unifiedOrderGoodsMapperEx.insertBatch(finalUnifiedOrderGoodsList);

        log.info("\n\n\n\nOrderGoods jd Final:\n{}\n\n\n\n", AnJsonUtils.toJson(finalUnifiedOrderGoodsList));

    }

    /**
     * 覆写 - 已参与对账的订单商品，部分更新商品字段
     * @param processOrderGoods
     * @param findedBySnapshotIdOrderGoods
     */
    private void partialOverWriteGoodsField(UnifiedOrderGoods processOrderGoods, UnifiedOrderGoods findedBySnapshotIdOrderGoods) {
        /**
         * 该商品订单的部分字段的数据可更新，参照结算中心现有的可更新字段（比如：商品名称、平台/商户税务分类编码、结算时间、快递单号等其他字段）；
         * 该商品订单的部分字段的数据不更新（比如：企业ID、供应商ID、销售单价、商品数量、销售总价、成本单价、成本总价、平台&商户税率）；
         * 其与企业和供应商对账状态不更新，保持原状态不变。
         */
        findedBySnapshotIdOrderGoods.setOrderSn(processOrderGoods.getOrderSn());

        findedBySnapshotIdOrderGoods.setGoodsName(processOrderGoods.getGoodsName());
        findedBySnapshotIdOrderGoods.setGoodsAlias(processOrderGoods.getGoodsAlias());

        findedBySnapshotIdOrderGoods.setUnit(StrUtil.isBlank(processOrderGoods.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : processOrderGoods.getUnit());

        findedBySnapshotIdOrderGoods.setGoodsParams(processOrderGoods.getGoodsParams());

        // 商户税率编码
        findedBySnapshotIdOrderGoods.setMerchTaxCode(processOrderGoods.getMerchTaxCode());

        // 平台税率编码
        findedBySnapshotIdOrderGoods.setOperationTaxCode(processOrderGoods.getOperationTaxCode());


        findedBySnapshotIdOrderGoods.setCateNameLv1(processOrderGoods.getCateNameLv1());
        findedBySnapshotIdOrderGoods.setCateNameLv2(processOrderGoods.getCateNameLv2());
        findedBySnapshotIdOrderGoods.setCateNameLv3(processOrderGoods.getCateNameLv3());

        findedBySnapshotIdOrderGoods.setSelfOption(processOrderGoods.getSelfOption() == null ? "" : processOrderGoods.getSelfOption());

        findedBySnapshotIdOrderGoods.setUpdateTime(DateUtil.date());
        findedBySnapshotIdOrderGoods.setUpdateUserId(1L);

        //供应商对账状态
        if (CommonAccountingStateEnum.不对账.getKey().equals(findedBySnapshotIdOrderGoods.getAccountingStateSupplier())) {
            findedBySnapshotIdOrderGoods.setAccountingStateSupplier(processOrderGoods.getAccountingStateSupplier());//不对账改为未对账
        }

    }

    /**
     * 覆写 - 已参与对账的订单商品流水，部分更新流水字段
     * @param processOrderCredit
     * @param findedOrderCredit
     */
    private void partialOverWriteCreditField(UnifiedOrderCredit processOrderCredit, UnifiedOrderCredit findedOrderCredit) {
        findedOrderCredit.setOrderSn(processOrderCredit.getOrderSn());

        findedOrderCredit.setCreditType(processOrderCredit.getCreditType());
        findedOrderCredit.setCreditName(processOrderCredit.getCreditName());
        findedOrderCredit.setMemberId(processOrderCredit.getMemberId());
        findedOrderCredit.setPayStatus(processOrderCredit.getPayStatus());
        findedOrderCredit.setPayType(processOrderCredit.getPayType());
    }


    /**
     * 处理重推的 已参与对账的京东订单
     * @param unifiedOrderEntity
     * @param unifiedOrder
     */
    private void processAlreadyAccountingUnifiedOrder(UnifiedOrder unifiedOrderEntity, UnifiedOrder unifiedOrder) {
        /**
         * 该商品订单的部分字段的数据可更新，参照结算中心现有的可更新字段（比如：商品名称、平台/商户税务分类编码、结算时间、快递单号等其他字段）；
         * 该商品订单的部分字段的数据不更新（比如：企业ID、供应商ID、销售单价、商品数量、销售总价、成本单价、成本总价、平台&商户税率）；
         *
         */
        unifiedOrder.setFinishTime(unifiedOrderEntity.getFinishTime());
        unifiedOrder.setAccountingTime(unifiedOrderEntity.getAccountingTime());
        unifiedOrder.setUpdateTime(DateUtil.date());
        unifiedOrder.setExpressSn(unifiedOrderEntity.getExpressSn());
        unifiedOrder.setExpress(unifiedOrderEntity.getExpress()); //快递公司拼音简写 eg：jd
        unifiedOrder.setExpressCompany(unifiedOrderEntity.getExpressCompany());//快递公司名称 eg：京东快递

        if (CommonAccountingStateEnum.不对账.getKey().equals(unifiedOrder.getAccountingStateSupplier())) {
            unifiedOrder.setAccountingStateSupplier(unifiedOrderEntity.getAccountingStateSupplier());//更新订单供应商对账状态
        }
        unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrder);
    }

    /**
     * 处理重推的 未参与对账的京东商品流水
     * @param unifiedOrderEntity
     * @param processUnifiedOrderCreditList
     * @param finalUnifiedOrderCreditList
     */
    private void processUnifiedOrderCreditFromQchjc(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderCredit> processUnifiedOrderCreditList, List<UnifiedOrderCredit> finalUnifiedOrderCreditList) {
        UnifiedOrderCreditExample          orderCreditExample4SaveOrUpdate  = new UnifiedOrderCreditExample();
        orderCreditExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());

        List<UnifiedOrderCredit> existsDatabaseUnifiedOrderCreditList = unifiedOrderCreditMapper.selectByExample(orderCreditExample4SaveOrUpdate);

        log.info("\n\n\nOrderCredit: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsDatabaseUnifiedOrderCreditList),
                AnJsonUtils.toJson(processUnifiedOrderCreditList)
        );


        for (UnifiedOrderCredit processOrderCredit : processUnifiedOrderCreditList) {

            // 新过来的数据在老的是不是存在
            List<UnifiedOrderCredit> findByManyOrderCreditList          = null;

            // 查询条件 如果 goods_id 为 0 条数大于 1 是会有问题 0 默认只有运费 , 如果 附件与赠品过来的情况 就会有问题,具体的问题再写吧
            List<Predicate<UnifiedOrderCredit>> predicatesByMany = new ArrayList<>();
            // 20201016 add start 从数据上看,是会有可能 同样的 orderId 不同的 orderSn
            predicatesByMany.add(
                    r -> r.getOrderSn().equals(processOrderCredit.getOrderSn())
                            && r.getOrderId().equals(processOrderCredit.getOrderId())
                            && r.getGoodsId().equals(processOrderCredit.getGoodsId())
                            && r.getCreditType().equals(processOrderCredit.getCreditType())
                            && r.getCreditName().equals(processOrderCredit.getCreditName())
                            && r.getBalance().compareTo(processOrderCredit.getBalance()) == 0
                            && r.getBatchs().equals(processOrderCredit.getBatchs())
            );
            // 20201016 add end
            // 新过来的数据在老的是不是存在
            findByManyOrderCreditList = AnLamdaUtils.filters(existsDatabaseUnifiedOrderCreditList, predicatesByMany);


            if (CollectionUtils.isNotEmpty(findByManyOrderCreditList)) {

                UnifiedOrderCredit findedOrderCredit = findByManyOrderCreditList.get(0);

                overWriteCreditField(processOrderCredit, findedOrderCredit);

                findedOrderCredit.setUpdateUserId(3L);
                findedOrderCredit.setUpdateTime(DateUtil.date());

                finalUnifiedOrderCreditList.add(findedOrderCredit);
            }
            // 两种情况都不存 才会作为新数据插入
            else {
                finalUnifiedOrderCreditList.add(processOrderCredit);
            }

            unifiedOrderCreditMapper.deleteByExample(orderCreditExample4SaveOrUpdate);
            for (UnifiedOrderCredit unifiedOrderCredit : finalUnifiedOrderCreditList) {
                if (unifiedOrderCredit.getId() == null || unifiedOrderCredit.getId() == 0) {
                    unifiedOrderCreditMapper.insertSelective(unifiedOrderCredit);
                }else {
                    unifiedOrderCreditMapperEx.insertSelectiveWithoutReturnId(unifiedOrderCredit);
                }
            }
        }
    }

    /**
     * 处理重推的 未参与对账的京东订单商品流水
     * @param processOrderCredit
     * @param findedOrderCredit
     */
    private void overWriteCreditField(UnifiedOrderCredit processOrderCredit, UnifiedOrderCredit findedOrderCredit) {
        findedOrderCredit.setOrderSn(processOrderCredit.getOrderSn());

        findedOrderCredit.setCreditType(processOrderCredit.getCreditType());
        findedOrderCredit.setCreditName(processOrderCredit.getCreditName());
        findedOrderCredit.setOutSnapshotOrderCreditId(processOrderCredit.getOutSnapshotOrderCreditId());
        findedOrderCredit.setGoodsId(processOrderCredit.getGoodsId());
        findedOrderCredit.setDailyAccountType(processOrderCredit.getDailyAccountType());
        findedOrderCredit.setBatchs(processOrderCredit.getBatchs());
        findedOrderCredit.setBalance(processOrderCredit.getBalance());
        findedOrderCredit.setEnterpriseId(processOrderCredit.getEnterpriseId());
        findedOrderCredit.setMemberId(processOrderCredit.getMemberId());
        findedOrderCredit.setPayStatus(processOrderCredit.getPayStatus());
        findedOrderCredit.setPayType(processOrderCredit.getPayType());

        // 与企业和供应商对账状态不更新，保持原状态不变；
        //findedOrderCredit.setCreditLockingSupplier(CommonAccountingLockingEnum.正常.getKey());
        //findedOrderCredit.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

        findedOrderCredit.setQchGoodsId(processOrderCredit.getQchGoodsId());
    }

    /**
     * 处理重推的 未参与对账的京东订单商品
     * @param unifiedOrderEntity
     * @param processUnifiedOrderGoodsList
     * @param finalUnifiedOrderGoodsList
     */
    private void processUnifiedOrderGoodsFromQchjc(UnifiedOrder unifiedOrderEntity, List<UnifiedOrderGoods> processUnifiedOrderGoodsList, List<UnifiedOrderGoods> finalUnifiedOrderGoodsList) {
        UnifiedOrderGoodsExample          orderGoodsExample4SaveOrUpdate  = new UnifiedOrderGoodsExample();
        orderGoodsExample4SaveOrUpdate.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn());
        //结算中心数据库中已存在的商品
        List<UnifiedOrderGoods> existsUnifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(orderGoodsExample4SaveOrUpdate);
        log.info("\n\n\nOrderGoods: \n已存在数据 : \n{}\n过来的数据 : \n{}\n\n\n",
                AnJsonUtils.toJson(existsUnifiedOrderGoodsList),
                AnJsonUtils.toJson(processUnifiedOrderGoodsList)
        );


        // 拿着过来的数据 去 查 数据库的
        for (UnifiedOrderGoods processOrderGoods : processUnifiedOrderGoodsList) {

            // 查询数据库中是否存在
            UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
            unifiedOrderGoodsExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
                    .andOutSnapshotOrderGoodsIdEqualTo(processOrderGoods.getOutSnapshotOrderGoodsId());
            List<UnifiedOrderGoods> findByOutSnapshotIdOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);


            //如果该商品已存在，则更新该商品数据
            if (CollectionUtils.isNotEmpty(findByOutSnapshotIdOrderGoodsList)) {
                UnifiedOrderGoods findedBySnapshotIdOrderGoods = findByOutSnapshotIdOrderGoodsList.get(0);

                overWriteGoodsField(processOrderGoods, findedBySnapshotIdOrderGoods);
                finalUnifiedOrderGoodsList.add(findedBySnapshotIdOrderGoods);
            } else {
                finalUnifiedOrderGoodsList.add(processOrderGoods);
            }
        }
        // 删除后重新插入数据
        unifiedOrderGoodsMapper.deleteByExample(orderGoodsExample4SaveOrUpdate);
        for (UnifiedOrderGoods unifiedOrderGoods : finalUnifiedOrderGoodsList) {
            if (unifiedOrderGoods.getId() == null || unifiedOrderGoods.getId() == 0) {
                unifiedOrderGoodsMapper.insertSelective(unifiedOrderGoods);
            } else {
                unifiedOrderGoodsMapperEx.insertSelectiveWithoutReturnId(unifiedOrderGoods);
            }
        }
        //unifiedOrderGoodsMapperEx.insertBatch(finalUnifiedOrderGoodsList);

        log.info("\n\n\n\nOrderGoods jd Final:\n{}\n\n\n\n", AnJsonUtils.toJson(finalUnifiedOrderGoodsList));

    }

    /**
     * 覆写重推的 未参与对账的京东订单商品
     * @param processOrderGoods
     * @param findedBySnapshotIdOrderGoods
     */
    private void overWriteGoodsField(UnifiedOrderGoods processOrderGoods, UnifiedOrderGoods findedBySnapshotIdOrderGoods) {
        findedBySnapshotIdOrderGoods.setOrderSn(processOrderGoods.getOrderSn());

        //与企业和供应商对账状态不更新，保持原状态不变；
        //findedBySnapshotIdOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());
        //findedBySnapshotIdOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

        findedBySnapshotIdOrderGoods.setGoodsName(processOrderGoods.getGoodsName());
        findedBySnapshotIdOrderGoods.setGoodsAlias(processOrderGoods.getGoodsAlias());

        findedBySnapshotIdOrderGoods.setGoodsId(processOrderGoods.getGoodsId());
        findedBySnapshotIdOrderGoods.setOutSnapshotOrderGoodsId(processOrderGoods.getOutSnapshotOrderGoodsId());

        findedBySnapshotIdOrderGoods.setQuantity(processOrderGoods.getQuantity());
        findedBySnapshotIdOrderGoods.setUnit(StrUtil.isBlank(processOrderGoods.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : processOrderGoods.getUnit());
        findedBySnapshotIdOrderGoods.setPrice(processOrderGoods.getPrice());
        findedBySnapshotIdOrderGoods.setCostPrice(processOrderGoods.getCostPrice());

        findedBySnapshotIdOrderGoods.setGoodsParams(processOrderGoods.getGoodsParams());

        //findedBySnapshotIdOrderGoods.setFiscalCode(processOrderGoods.getFiscalCode());
        //findedBySnapshotIdOrderGoods.setTaxCode(processOrderGoods.getTaxCode());
        //findedBySnapshotIdOrderGoods.setTaxRate(processOrderGoods.getTaxRate());

        // 商户税率
        //findedBySnapshotIdOrderGoods.setMerchTaxId(processOrderGoods.getMerchTaxId());
        findedBySnapshotIdOrderGoods.setMerchTaxCode(processOrderGoods.getMerchTaxCode());
        findedBySnapshotIdOrderGoods.setMerchTaxRate(processOrderGoods.getMerchTaxRate());

        // 平台税率
        //findedBySnapshotIdOrderGoods.setOperationTaxId(processOrderGoods.getOperationTaxId());
        findedBySnapshotIdOrderGoods.setOperationTaxCode(processOrderGoods.getOperationTaxCode());
        findedBySnapshotIdOrderGoods.setOperationTaxRate(processOrderGoods.getOperationTaxRate());

        //findedBySnapshotIdOrderGoods.setCateIdLv1(processOrderGoods.getCateIdLv1());
        //findedBySnapshotIdOrderGoods.setCateIdLv1(processOrderGoods.getCateIdLv2());
        //findedBySnapshotIdOrderGoods.setCateIdLv3(processOrderGoods.getCateIdLv3());

        findedBySnapshotIdOrderGoods.setCateNameLv1(processOrderGoods.getCateNameLv1());
        findedBySnapshotIdOrderGoods.setCateNameLv2(processOrderGoods.getCateNameLv2());
        findedBySnapshotIdOrderGoods.setCateNameLv3(processOrderGoods.getCateNameLv3());

        findedBySnapshotIdOrderGoods.setSelfOption(processOrderGoods.getSelfOption() == null ? "" : processOrderGoods.getSelfOption());

        findedBySnapshotIdOrderGoods.setGoodsType(processOrderGoods.getGoodsType());


        findedBySnapshotIdOrderGoods.setUpdateTime(DateUtil.date());
        findedBySnapshotIdOrderGoods.setUpdateUserId(1L);

        findedBySnapshotIdOrderGoods.setQchjcGoodsId(processOrderGoods.getQchjcGoodsId());
    }

    /**
     * 处理中间表存在的京东退单
     *
     * @param qchjcJdOrderParamReceive
     */
//    private void handleExistRefundOrder(QchjcJdOrderParamReceive qchjcJdOrderParamReceive) {
//        //查询正单
//        UnifiedOrderExample unifiedOrderExample = new UnifiedOrderExample();
//        unifiedOrderExample.createCriteria().andOrderSnEqualTo(qchjcJdOrderParamReceive.getRefundOrderSn());
//        List<UnifiedOrder> unifiedOrders = unifiedOrderMapper.selectByExample(unifiedOrderExample);
//        if (CollectionUtils.isEmpty(unifiedOrders) || unifiedOrders.get(0) == null) {
//            throw new OpenApiException(500, "正单不存在，需要先推送正单");
//        }
//
//        //中间表已经存在，直接取中间表id即可，这里不需要更新中间表的数据，因为只需要构造的自增id
//        QchjcOrderEntityExample qchjcOrderEntityExample = new QchjcOrderEntityExample();
//        qchjcOrderEntityExample.createCriteria().andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn());
//        List<QchjcOrderEntity> qchjcOrderEntities = qchjcOrderEntityMapper.selectByExample(qchjcOrderEntityExample);
//        qchjcJdOrderParamReceive.setId(qchjcOrderEntities.get(0).getId());
//        //同样的 取商品的id，如果不存在的商品需要新增
//        List<QchjcJdOrderGoodsParamReceive> orderGoodsSelected = qchjcJdOrderParamReceive.getOrderGoodsSelected();
//        for (QchjcJdOrderGoodsParamReceive qchjcJdOrderGoodsParamReceive : orderGoodsSelected) {
//            QchjcOrderGoodsEntityExample qchjcOrderGoodsEntityExample = new QchjcOrderGoodsEntityExample();
//            qchjcOrderGoodsEntityExample.createCriteria()
//                    .andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn())
//                    .andOutSnapshotOrderGoodsIdEqualTo(qchjcJdOrderGoodsParamReceive.getOutSnapshotOrderGoodsId());
//            List<QchjcOrderGoodsEntity> qchjcOrderGoodsEntities = qchjcOrderGoodsEntityMapper.selectByExample(qchjcOrderGoodsEntityExample);
//            if (CollectionUtils.isNotEmpty(qchjcOrderGoodsEntities) && qchjcOrderGoodsEntities.get(0) != null) {
//                //已存在，直接取id
//                qchjcJdOrderGoodsParamReceive.setId(qchjcOrderGoodsEntities.get(0).getId());
//            }else {
//                //不存在，新增 取id
//                QchjcOrderGoodsEntity orderGoods = convertQchGoodsParam2Entity(qchjcJdOrderGoodsParamReceive, null, qchjcJdOrderParamReceive.getOrderSn());
//                qchjcOrderGoodsEntityMapper.insertSelective(orderGoods);
//                qchjcJdOrderGoodsParamReceive.setId(orderGoods.getId());//回写中间表的id
//            }
//        }
//
//        /**
//         * 构造数据
//         */
//        UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
//        convertQchJdOrderParam2OrderEntity(qchjcJdOrderParamReceive, unifiedOrderEntity);
//        //处理商品
//        List<UnifiedOrderGoods> processUnifiedOrderGoodsList = new ArrayList<>();
//        List<Predicate<QchjcJdOrderGoodsParamReceive>> predicates = new ArrayList<>();
//        predicates.add(r -> null != r.getSellingPrice() && r.getSellingPrice().compareTo(BigDecimal.ZERO) > 0);
//        predicates.add(r -> null != r.getCostPrice() && r.getCostPrice().compareTo(BigDecimal.ZERO) > 0);
//        List<QchjcJdOrderGoodsParamReceive> scoreOrderGoodsReceiveParamFilterList = AnLamdaUtils.filters(orderGoodsSelected, predicates);
//        if (CollectionUtils.isEmpty(scoreOrderGoodsReceiveParamFilterList)) {
//            log.info("scoreOrderGoodsReceiveParamFilterList is empty, orderSn : {}", qchjcJdOrderParamReceive.getOrderSn());
//            throw new OpenApiException(500, "过滤后商品列表为空");
//        }
//        //订单商品vo转换为统一订单商品实体,并构造流水
//        List<UnifiedOrderCredit> processUnifiedOrderCreditList = new ArrayList<>();
//        scoreOrderGoodsReceiveParamFilterList.forEach(goodsParam -> {
//            //转为商品实体
//            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
//            convertQchJdOrderGoodsParam2Entity(goodsParam, unifiedOrderGoods);
//            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
//            processUnifiedOrderGoodsList.add(unifiedOrderGoods);
//            //构造流水
//            UnifiedOrderCredit scoreOrderCredit = new UnifiedOrderCredit();
//            convertQchJdOrderGoodsParam2CreditEntity(goodsParam, scoreOrderCredit, qchjcJdOrderParamReceive);
//            scoreOrderCredit.setOrderSn(unifiedOrderEntity.getOrderSn());
//            processUnifiedOrderCreditList.add(scoreOrderCredit);
//        });
//
//        //判断统一订单是否存在该退单
//        UnifiedOrderExample unifiedOrderExampleRefund = new UnifiedOrderExample();
//        unifiedOrderExampleRefund.createCriteria().andOrderSnEqualTo(qchjcJdOrderParamReceive.getOrderSn());
//        List<UnifiedOrder> unifiedOrdersRefund = unifiedOrderMapper.selectByExample(unifiedOrderExampleRefund);
//
//        if(CollectionUtils.isEmpty(unifiedOrdersRefund) || unifiedOrdersRefund.get(0) == null) {
//            /**
//             * 统一订单不存在，新增
//             */
//            if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {
//                //订单
//                unifiedOrderMapper.insertSelective(unifiedOrderEntity);
//                //商品
//                for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
//                    unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
//                }
//                //流水
//                for (UnifiedOrderCredit unifiedOrderCredit : processUnifiedOrderCreditList) {
//                    unifiedOrderCreditMapper.insert(unifiedOrderCredit);
//                }
//
//                //把退单的sn 更新到 统一订单正单的 refundSn字段
//                UnifiedOrder unifiedOrder = unifiedOrders.get(0);
//                UnifiedOrder updateOrder = new UnifiedOrder();
//                updateOrder.setId(unifiedOrder.getId());
//                updateOrder.setRefundOrderSn(qchjcJdOrderParamReceive.getOrderSn());
//                unifiedOrderMapper.updateByPrimaryKeySelective(updateOrder);
//            }
//        }
//        else {
//            /**
//             * 统一订单存在，更新
//             */
//            UnifiedOrder unifiedOrderRefund = unifiedOrdersRefund.get(0);
//            /**
//             * 判断该订单数据与该企业&供应商对账状态
//             */
//            //判断订单下的商品是否对过账
//            UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
//            unifiedOrderGoodsExample.createCriteria().andOrderSnEqualTo(unifiedOrderRefund.getOrderSn())
//                    .andAccountingStateSupplierEqualTo(CommonAccountingStateEnum.已对账.getKey());
//            List<UnifiedOrderGoods> alreadyAccounting = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);
//            //判断订单下的明细是否已经对过账
//            UnifiedOrderCreditExample unifiedOrderCreditExample = new UnifiedOrderCreditExample();
//            unifiedOrderCreditExample.createCriteria().andOrderSnEqualTo(unifiedOrderEntity.getOrderSn())
//                    .andAccountingStateCustomerEqualTo(CommonAccountingStateEnum.已对账.getKey());
//            List<UnifiedOrderCredit> unifiedOrderCredits = unifiedOrderCreditMapper.selectByExample(unifiedOrderCreditExample);
//
//            if (CollectionUtils.isNotEmpty(alreadyAccounting) || CollectionUtils.isNotEmpty(unifiedOrderCredits)) {
//                /**
//                 * 已经参与对账，部分更新
//                 */
//                //订单
//                processAlreadyAccountingUnifiedOrder(unifiedOrderEntity,unifiedOrderRefund);
//                /**
//                 * 最终入库的商品数据和流水数据
//                 */
//                List<UnifiedOrderGoods> finalUnifiedOrderGoodsList = new ArrayList<>();
//                List<UnifiedOrderCredit> finalUnifiedOrderCreditList = new ArrayList<>();
//                //商品
//                processAlreadyAccountingUnifiedOrderGoods(unifiedOrderEntity, processUnifiedOrderGoodsList,finalUnifiedOrderGoodsList);
//                //流水
//                processAlreadyAccountingUnifiedOrderCredit(unifiedOrderEntity, processUnifiedOrderCreditList,finalUnifiedOrderCreditList);
//
//
//            }else {
//                /**
//                 * 未参与对账，可以全部更新
//                 */
//
//                unifiedOrderEntity.setId(unifiedOrderRefund.getId());
//                unifiedOrderEntity.setUpdateTime(DateUtil.date());
//                //与企业和供应商对账状态不更新，保持原状态不变
//                unifiedOrderEntity.setAccountingStateCustomer(unifiedOrderRefund.getAccountingStateCustomer());
//                unifiedOrderEntity.setAccountingStateSupplier(unifiedOrderRefund.getAccountingStateSupplier());
//                unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrderEntity);
//                /**
//                 * 最终入库的商品数据和流水数据
//                 */
//                List<UnifiedOrderGoods> finalUnifiedOrderGoodsList = new ArrayList<>();
//                List<UnifiedOrderCredit> finalUnifiedOrderCreditList = new ArrayList<>();
//                /**
//                 * 重推商品处理
//                 */
//                processUnifiedOrderGoodsFromQchjc(unifiedOrderEntity, processUnifiedOrderGoodsList,finalUnifiedOrderGoodsList);
//                /**
//                 * 重推流水处理
//                 */
//                processUnifiedOrderCreditFromQchjc(unifiedOrderEntity, processUnifiedOrderCreditList,finalUnifiedOrderCreditList);
//
//            }
//
//
//            //把退单的sn 更新到 统一订单正单的 refundSn字段
//            UnifiedOrder unifiedOrder = unifiedOrders.get(0);
//            UnifiedOrder updateOrder = new UnifiedOrder();
//            updateOrder.setId(unifiedOrder.getId());
//            updateOrder.setRefundOrderSn(qchjcJdOrderParamReceive.getOrderSn());
//            unifiedOrderMapper.updateByPrimaryKeySelective(updateOrder);
//
//        }
//        /**
//         * 处理锁单状态 - 根据售后单的 完成状态
//         */
//        CommonOrderCompletStateEnum commonOrderCompletStateEnum = CommonOrderCompletStateEnum.get(qchjcJdOrderParamReceive.getCompletState());
//        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
//        Date finishTime    = qchjcJdOrderParamReceive.getFinishTime();
//
//        String orderSn = qchjcJdOrderParamReceive.getOrderSn();//退单的sn
//        String refundOrderSn = qchjcJdOrderParamReceive.getRefundOrderSn();//正单的sn
//        handleAccountingLockStatus(refundOrderSn, orderSn, commonOrderCompletStateEnum, callback, finishTime);
//    }


    /**
     * 京东订单转为统一订单实体
     *
     * @param qchjcJdOrderParamReceive
     * @param unifiedOrderEntity
     */
    private void convertQchJdOrderParam2OrderEntity(QchjcJdOrderParamReceive qchjcJdOrderParamReceive, UnifiedOrder unifiedOrderEntity) {
        unifiedOrderEntity.setOrderType(qchjcJdOrderParamReceive.getOrderType());//正单/退单
        unifiedOrderEntity.setOrderSn(qchjcJdOrderParamReceive.getOrderSn());//订单编号
        if (CommonOrderTypeEnum.退单.getKey().equals(qchjcJdOrderParamReceive.getOrderType()) && StringUtils.isNotBlank(qchjcJdOrderParamReceive.getRefundOrderSn())) {
            unifiedOrderEntity.setRefundOrderSn(qchjcJdOrderParamReceive.getRefundOrderSn());//退单时，此字段为正单编号，正单时此字段为空
        }
        unifiedOrderEntity.setOrderSnOutTrade(qchjcJdOrderParamReceive.getOrderSn());//外部订单号

        unifiedOrderEntity.setExpressSn(qchjcJdOrderParamReceive.getExpressSn());//京东子单号
        unifiedOrderEntity.setExpress(qchjcJdOrderParamReceive.getExpress()); //快递公司拼音简写 eg：jd
        unifiedOrderEntity.setExpressCompany(qchjcJdOrderParamReceive.getExpressCompany());//快递公司名称 eg：京东快递


        unifiedOrderEntity.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());//服务编号，固定值
        unifiedOrderEntity.setServiceName(CommonServiceNoEnum.企业商城_侨城汇.getServiceName());

        unifiedOrderEntity.setProjectId(QchjcOrgEnum.CUSTOMER.getOrgId());//项目ID 固定值
        unifiedOrderEntity.setProjectName(QchjcOrgEnum.CUSTOMER.getServiceNoName());//项目名称 固定值
        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getPurchaseVirtId());
        if (qchjcEnterpriseEntity != null) {
            unifiedOrderEntity.setPurchaseVirtId(qchjcEnterpriseEntity.getId());//采购单位ID，中间表id，集采id统一+10万
            unifiedOrderEntity.setPurchaseVirtName(qchjcJdOrderParamReceive.getPurchaseVirtName());//采购单位名称
        } else {
            unifiedOrderEntity.setPurchaseVirtId(0L);//采购单位ID，中间表id，集采id统一+10万
            unifiedOrderEntity.setPurchaseVirtName(qchjcJdOrderParamReceive.getPurchaseVirtName());//采购单位名称
        }

        unifiedOrderEntity.setPurchaseDepartmentName(qchjcJdOrderParamReceive.getPurchaseDepartmentName());//采购单位部门名称

        QchjcUserEntity qchjcUserEntity1 = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getPurchaseUserId());
        if (qchjcUserEntity1 != null) {
            unifiedOrderEntity.setPurchaseUserId(qchjcUserEntity1.getUnifiedId());//采购单位用户ID
        } else {
            unifiedOrderEntity.setPurchaseUserId(0L);//采购单位用户ID
        }
        unifiedOrderEntity.setPurchaseUserName(qchjcJdOrderParamReceive.getPurchaseUserName());//采购单位用户名称
        unifiedOrderEntity.setPurchasePhone(qchjcJdOrderParamReceive.getPurchasePhone());//采购单位用户电话
        QchjcSupplierEntity qchjcSupplierEntity = qchjcSupplierEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getSupplierId());
        if (qchjcSupplierEntity != null) {
            unifiedOrderEntity.setSaleId(qchjcSupplierEntity.getId());//销售单位ID,中间表id，集采id统一+10万
        } else {
            unifiedOrderEntity.setSaleId(0L);//销售单位ID,中间表id，集采id统一+10万
        }
        unifiedOrderEntity.setSaleName(qchjcJdOrderParamReceive.getSupplierName());//销售单位名称

        // 商城 dispatchPrice + grprice = price scoreOrderReceiveParam.getPrice()
        unifiedOrderEntity.setAmount(qchjcJdOrderParamReceive.getOrderAmount());//订单金额
        unifiedOrderEntity.setCostAmount(qchjcJdOrderParamReceive.getOrderCostAmount());//订单成本金额
        /**
         * 20220425修改 集采运费已经拆成商品，运费都填0
         */
        unifiedOrderEntity.setTransportAmount(BigDecimal.ZERO);//运费
        unifiedOrderEntity.setTransportMerchantAssumeAmount(BigDecimal.ZERO);//运费商品承担金额


        // TODO mark by linjinyu at 2022-07-22 10:28:33 - 统一修正 支付方式 支付状态 订单状态 都不定义 start

//        unifiedOrderEntity.setOrderState(qchjcJdOrderParamReceive.getOrderState());//订单状态
//        unifiedOrderEntity.setOrderStateName(qchjcJdOrderParamReceive.getOrderStateName());//订单状态名称
//        unifiedOrderEntity.setPayType(qchjcJdOrderParamReceive.getPayType());
//        unifiedOrderEntity.setPayState(2); // TODO 写死

        unifiedOrderEntity.setOrderState(qchjcJdOrderParamReceive.getOrderState());
        unifiedOrderEntity.setOrderStateName(qchjcJdOrderParamReceive.getOrderStateName());

        unifiedOrderEntity.setPayType(qchjcJdOrderParamReceive.getPayType());
        unifiedOrderEntity.setPayTypeName(qchjcJdOrderParamReceive.getPayTypeName());

        unifiedOrderEntity.setPayState(ObjectUtil.isNull(qchjcJdOrderParamReceive.getPayState()) ? 2 : qchjcJdOrderParamReceive.getPayState());
        unifiedOrderEntity.setPayStateName(qchjcJdOrderParamReceive.getPayStateName());

        // TODO mark by linjinyu at 2022-07-22 10:28:33 - 统一修正 支付方式 支付状态 订单状态 都不定义   end

        unifiedOrderEntity.setCompletState(qchjcJdOrderParamReceive.getCompletState());//订单完成状态

        unifiedOrderEntity.setOrderLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderEntity.setOrderLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        /**
         * 企业对账状态为"不对账"，供应商对账状态为"未对账"
         */
        unifiedOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.不对账.getKey());
        unifiedOrderEntity.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());



        // TODO 写死
        unifiedOrderEntity.setSettlementType(2);
        // TODO 写死
        unifiedOrderEntity.setAppraiseState(2);
        // TODO 写死
        unifiedOrderEntity.setSourceChannel(1);

        unifiedOrderEntity.setOtherParams(qchjcJdOrderParamReceive.getOtherParams());//其他参数

        QchjcUserEntity qchjcUserEntity = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getCreateUserId());
        // 这个是可以用于记录 谁创建的 20200611
        if (qchjcUserEntity != null) {
            unifiedOrderEntity.setCreateUserId(qchjcUserEntity.getUnifiedId());
        } else {
            unifiedOrderEntity.setCreateUserId(0L);
        }
        unifiedOrderEntity.setCreateTime(qchjcJdOrderParamReceive.getCreateTime());

        unifiedOrderEntity.setPayTime(qchjcJdOrderParamReceive.getPayTime());
        unifiedOrderEntity.setSendTime(qchjcJdOrderParamReceive.getSendTime());
        unifiedOrderEntity.setFinishTime(qchjcJdOrderParamReceive.getFinishTime());//完成时间

        // TODO 结算时间逻辑 添加 mark by linjinyu at 20211112
        // |---- 1. kafka 正向通道,触发点 订单已完成 产生 结算时间(订单完成时间填充) right
        // |---- 2. kafka 负向通道,解发点 退单已完成 解锁正负单时 产生结算时间(退单完成时间填充)
        // |---- 3. 供应商结算 未对账商品 list 逻辑 不变(没说明) 看样子是 加了个 结算时间 筛选逻辑
        //if (UnifiedOrderCompletStateEnum.已完成.getKey().equals(unifiedOrderEntity.getCompletState())
        //        && ObjectUtil.isNotNull(unifiedOrderEntity.getFinishTime())) {
        //unifiedOrderEntity.setAccountingTime(unifiedOrderEntity.getFinishTime());
        unifiedOrderEntity.setAccountingTime(qchjcJdOrderParamReceive.getAccountingTime());//结算时间
        //}


        // TODO 写死
        unifiedOrderEntity.setUserType("2");
        // TODO 写死
        unifiedOrderEntity.setUserName("系统");

        unifiedOrderEntity.setUpdateTime(qchjcJdOrderParamReceive.getUpdateTime());

        QchjcUserEntity updateUser = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getUpdateUserId());
        if (updateUser != null) {
            unifiedOrderEntity.setUpdateUserId(updateUser.getUnifiedId());
        } else {
            unifiedOrderEntity.setUpdateUserId(0L);
        }
        // 原本代码也是注释了
//		unifiedOrderEntity.setRecUserId();
        unifiedOrderEntity.setRecUserName(qchjcJdOrderParamReceive.getRecUserName());
        unifiedOrderEntity.setRecUserPhone(qchjcJdOrderParamReceive.getRecUserPhone());
        unifiedOrderEntity.setRecAddress(qchjcJdOrderParamReceive.getRecAddress());

        unifiedOrderEntity.setRemarks(qchjcJdOrderParamReceive.getRemarks());
    }

    /**
     * 京东订单商品转为统一订单商品实体
     *
     * @param goodsParam
     * @param unifiedOrderGoods
     */
    private void convertQchJdOrderGoodsParam2Entity(QchjcJdOrderGoodsParamReceive goodsParam, UnifiedOrderGoods unifiedOrderGoods) {
        if (CommonOrderGoodsTypeEnum.运费.getKey().equals(goodsParam.getGoodsType())) {
            UnifiedServicePartGoodsTransportParam defaultGoodsTransport = unifiedServiceService.getUnifiedServicePartGoodsTransport(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());

            //运费处理
            unifiedOrderGoods.setOrderSn(goodsParam.getOrderSn());
            unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

            unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.不对账.getKey());
            unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

            unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.运费.getKey());
            unifiedOrderGoods.setDirection(goodsParam.getDirection());
            /**
             * goods_id用集采的
             */
            unifiedOrderGoods.setGoodsId(Long.parseLong(goodsParam.getGoodsId()));
            unifiedOrderGoods.setOutSnapshotOrderGoodsId(Long.parseLong(goodsParam.getOutSnapshotOrderGoodsId()));

            unifiedOrderGoods.setGoodsName(CommonOrderGoodsIdEnum.运费.getDesc());

            unifiedOrderGoods.setUnit(CommonOrderGoodsUnitEnum.项.getDesc());
            if (CommonDirectionEnum.正向.getKey().equals(goodsParam.getDirection())) {
                unifiedOrderGoods.setQuantity(1);
            }else {
                unifiedOrderGoods.setQuantity(-1);
            }

            unifiedOrderGoods.setPrice(goodsParam.getSellingPrice());
            unifiedOrderGoods.setCostPrice(goodsParam.getCostPrice());

//			defaultGoodsTransport
            unifiedOrderGoods.setFiscalCode(defaultGoodsTransport.getGoodsTransportFiscalCode());
            unifiedOrderGoods.setTaxCode(defaultGoodsTransport.getGoodsTransportTaxCode());
            unifiedOrderGoods.setTaxRate(defaultGoodsTransport.getGoodsTransportTaxRate());

            // 商户税率
            unifiedOrderGoods.setMerchTaxId(0L);
            unifiedOrderGoods.setMerchTaxCode(goodsParam.getMerchTaxCode());
            unifiedOrderGoods.setMerchTaxRate(goodsParam.getMerchTaxRate());

            // 平台税率
            unifiedOrderGoods.setOperationTaxId(0L);
            unifiedOrderGoods.setOperationTaxCode(goodsParam.getOperationTaxCode());
            unifiedOrderGoods.setOperationTaxRate(goodsParam.getOperationTaxRate());

            unifiedOrderGoods.setCreateTime(DateUtil.date());
            unifiedOrderGoods.setCreateUserId(1L);
            unifiedOrderGoods.setUpdateTime(DateUtil.date());
            unifiedOrderGoods.setUpdateUserId(1L);

        } else {
            unifiedOrderGoods.setGoodsType(goodsParam.getGoodsType());//商品类型
            unifiedOrderGoods.setDirection(goodsParam.getDirection());//商品方向

            unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

            /**
             * 20220425 对账状态标志位增加集采未对账 集采已对账
             */
            unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.不对账.getKey());
            unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());
            /**
             * goods_id用集采的
             */
            unifiedOrderGoods.setGoodsId(Long.parseLong(goodsParam.getGoodsId()));
            unifiedOrderGoods.setOutSnapshotOrderGoodsId(Long.parseLong(goodsParam.getOutSnapshotOrderGoodsId()));

            unifiedOrderGoods.setGoodsName(goodsParam.getGoodsName());
            //if (CommonDirectionEnum.正向.getKey().equals(goodsParam.getDirection())) {
            unifiedOrderGoods.setQuantity(goodsParam.getQuantity());//正单商品数量为正数
            //}else {
            //    unifiedOrderGoods.setQuantity(-goodsParam.getQuantity());//退单的商品数量为负数
            //}
            unifiedOrderGoods.setUnit(StrUtil.isBlank(goodsParam.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : goodsParam.getUnit());
            unifiedOrderGoods.setPrice(goodsParam.getSellingPrice());
            // add costprice 成本价
            unifiedOrderGoods.setCostPrice(goodsParam.getCostPrice());

            unifiedOrderGoods.setGoodsParams(goodsParam.getGoodsParams());//商品参数

            unifiedOrderGoods.setSelfOption(goodsParam.getSelfOption() == null ? "" : goodsParam.getSelfOption());

            /************************************** update by linjinjy 20200727 20200723_林志鹏_税率,退款格式.docx 将要弃用 20210413 mark by linjinyu **************************************/

            //unifiedOrderGoods.setFiscalCode(vo.getFiscalCode());
            //unifiedOrderGoods.setTaxCode(vo.getTaxCode());
            //unifiedOrderGoods.setTaxRate(vo.getTaxRate());

            /************************************** update by linjinjy 20200727 20200723_林志鹏_税率,退款格式.docx 将要弃用 20210413 mark by linjinyu **************************************/


            /****************************************** 税率修改 20210413 mark by linjinyu start ******************************************/

            // 商户税率
            //unifiedOrderGoods.setMerchTaxId(vo.getMerchTaxId());
            unifiedOrderGoods.setMerchTaxCode(goodsParam.getMerchTaxCode());
            unifiedOrderGoods.setMerchTaxRate(goodsParam.getMerchTaxRate());

            // 平台税率
            //unifiedOrderGoods.setOperationTaxId(vo.getOperationTaxId());
            unifiedOrderGoods.setOperationTaxCode(goodsParam.getOperationTaxCode());
            unifiedOrderGoods.setOperationTaxRate(goodsParam.getOperationTaxRate());

            /****************************************** 税率修改 20210413 mark by linjinyu   end ******************************************/


            // 弃 20200904 by linjinyu
            /************************************** update by linjinjy 20200810 20200729_林志鹏_税率,退款格式.docx **************************************/

//		scoreOrderGoodsEntity.setCateName(scoreOrderGoodsReceiveParam.getCateName());

            /************************************** update by linjinjy 20200810 20200729_林志鹏_税率,退款格式.docx **************************************/


            /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

            //unifiedOrderGoods.setCateIdLv1(vo.getCateIdLv1());
            //unifiedOrderGoods.setCateIdLv2(vo.getCateIdLv2());
            //unifiedOrderGoods.setCateIdLv3(vo.getCateIdLv3());
            unifiedOrderGoods.setCateNameLv1(goodsParam.getCateNameLv1());
            unifiedOrderGoods.setCateNameLv2(goodsParam.getCateNameLv2());
            unifiedOrderGoods.setCateNameLv3(goodsParam.getCateNameLv3());

            /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/


            unifiedOrderGoods.setCreateTime(DateUtil.date());
            // TODO 写死
            unifiedOrderGoods.setCreateUserId(1L);
            unifiedOrderGoods.setUpdateTime(DateUtil.date());
            // TODO 写死
            unifiedOrderGoods.setUpdateUserId(1L);
        }
    }

    /**
     * 京东订单商品转为统一订单商品流水信息
     *
     * @param goodsParam
     * @param unifiedOrderCreditEntity
     * @param qchjcJdOrderParamReceive
     */
    private void convertQchJdOrderGoodsParam2CreditEntity(QchjcJdOrderGoodsParamReceive goodsParam, UnifiedOrderCredit unifiedOrderCreditEntity, QchjcJdOrderParamReceive qchjcJdOrderParamReceive) {
        unifiedOrderCreditEntity.setDirection(goodsParam.getDirection());
        //unifiedOrderCreditEntity.setOutSnapshotOrderCreditId(scoreOrderCreditReceiveParam.getOrderCreditId());

        unifiedOrderCreditEntity.setOrderId(qchjcJdOrderParamReceive.getId());//集采的订单id是uuid，这里用中间表id替换
        /**
         * goods_id用集采的
         */
        unifiedOrderCreditEntity.setGoodsId(Long.parseLong(goodsParam.getGoodsId()));

        unifiedOrderCreditEntity.setCreditType(UnifiedOrderCreditTypeDefaultEnum.积分支付.getKey());
        unifiedOrderCreditEntity.setCreditName(UnifiedOrderCreditTypeDefaultEnum.积分支付.getDesc());

        /* 积分变动类型(1充值 2消费 3退款) */
        unifiedOrderCreditEntity.setDailyAccountType(goodsParam.getDirection() == 1 ? 2 : 3);//1-正单 -1退单 ，对应2消费，3退款
        unifiedOrderCreditEntity.setBatchs(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());//固定值
        //if (CommonDirectionEnum.正向.getKey().equals(goodsParam.getDirection())) {
        unifiedOrderCreditEntity.setBalance(goodsParam.getSellingPrice().multiply(new BigDecimal(goodsParam.getQuantity())));
        //} else {
        //    unifiedOrderCreditEntity.setBalance(goodsParam.getSellingPrice().multiply(new BigDecimal(goodsParam.getQuantity())).negate());
        //}

        // TODO 要检查
        QchjcEnterpriseEntity qchjcEnterpriseEntity = qchjcEnterpriseEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getPurchaseVirtId());
        if (qchjcEnterpriseEntity != null) {
            unifiedOrderCreditEntity.setEnterpriseId(qchjcEnterpriseEntity.getId());//所属企业（买家）取中间表id，非统一订单企业表自增id
        } else {
            unifiedOrderCreditEntity.setEnterpriseId(0L);
        }
        QchjcUserEntity qchjcUser = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getPurchaseUserId());
        if (qchjcUser != null) {
            unifiedOrderCreditEntity.setMemberId(qchjcUser.getUnifiedId());//买家id
        } else {
            unifiedOrderCreditEntity.setMemberId(0L);
        }

        unifiedOrderCreditEntity.setPayStatus(1);//固定已支付
        unifiedOrderCreditEntity.setPayType(qchjcJdOrderParamReceive.getPayType());

        unifiedOrderCreditEntity.setCreditLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderCreditEntity.setCreditLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        unifiedOrderCreditEntity.setAccountingStateCustomer(CommonAccountingStateEnum.不对账.getKey());
        unifiedOrderCreditEntity.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

        unifiedOrderCreditEntity.setInvoiceApplyStatus(UnifiedOrderCreditInvoiceApplyStatusEnum.待申请.getKey());
        unifiedOrderCreditEntity.setInvoiceMakeStatus(UnifiedOrderCreditInvoiceMakeStatusEnum.待开票.getKey());
        unifiedOrderCreditEntity.setBackStatus(UnifiedOrderCreditBackAccountStatusEnum.未回款.getKey());


        unifiedOrderCreditEntity.setCreateTime(qchjcJdOrderParamReceive.getCreateTime());
        QchjcUserEntity qchjcCreateUserEntity = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getCreateUserId());
        if (qchjcCreateUserEntity != null) {
            unifiedOrderCreditEntity.setCreateUserId(qchjcCreateUserEntity.getUnifiedId());
        }
        unifiedOrderCreditEntity.setUpdateTime(qchjcJdOrderParamReceive.getUpdateTime());
        QchjcUserEntity qchjcUpdateUserEntity = qchjcUserEntityMapper.selectByOutId(qchjcJdOrderParamReceive.getUpdateUserId());
        if (qchjcUpdateUserEntity != null) {
            unifiedOrderCreditEntity.setUpdateUserId(qchjcUpdateUserEntity.getUnifiedId());
        }
    }

    /**
     * 京东订单参数 转换为 中间表订单实体
     *
     * @param qchjcJdOrderParamReceive
     * @param orderEntity
     * @return
     */
    private QchjcOrderEntity convertQchJdParam2QchEntity(QchjcJdOrderParamReceive qchjcJdOrderParamReceive, QchjcOrderEntity orderEntity) {
        if (orderEntity == null) {
            orderEntity = AnBeanUtils.copy(qchjcJdOrderParamReceive, QchjcOrderEntity.class);
        } else {
            orderEntity = AnBeanUtils.copy(qchjcJdOrderParamReceive, orderEntity);
        }
        orderEntity.setSyncTime(DateUtil.date());
        orderEntity.setServiceNo(CommonServiceNoEnum.企业商城_侨城汇.getServiceNo());
        orderEntity.setAmount(qchjcJdOrderParamReceive.getOrderAmount());
        orderEntity.setSaleId(qchjcJdOrderParamReceive.getSupplierId());
        orderEntity.setSaleName(qchjcJdOrderParamReceive.getSupplierName());
        orderEntity.setCostAmount(qchjcJdOrderParamReceive.getOrderCostAmount());
        orderEntity.setTransportAmount(qchjcJdOrderParamReceive.getTransportAmount());
        orderEntity.setTransportMerchantAssumeAmount(qchjcJdOrderParamReceive.getTransportMerchantAssumeAmount());
        return orderEntity;
    }

    /**
     * 京东订单商品参数 转换为 中间表商品实体
     *
     * @param goodsParam
     * @param qchjcOrderGoodsEntity
     * @param orderSn
     * @return
     */
    private QchjcOrderGoodsEntity convertQchGoodsParam2Entity(QchjcJdOrderGoodsParamReceive goodsParam, QchjcOrderGoodsEntity qchjcOrderGoodsEntity, String orderSn) {
        if (qchjcOrderGoodsEntity == null) {
            qchjcOrderGoodsEntity = AnBeanUtils.copy(goodsParam, QchjcOrderGoodsEntity.class);
        } else {
            qchjcOrderGoodsEntity = AnBeanUtils.copy(goodsParam, qchjcOrderGoodsEntity);
        }
        qchjcOrderGoodsEntity.setOrderSn(orderSn);
        qchjcOrderGoodsEntity.setSyncTime(DateUtil.date());
        return qchjcOrderGoodsEntity;
    }
}
