package com.hzya.frame.plugin.lets.plugin.sales;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.beanutil.BeanUtil;
import com.hzya.frame.plugin.lets.constant.ExportConstant;
import com.hzya.frame.plugin.lets.constant.OverallConstant;
import com.hzya.frame.plugin.lets.constant.ProfilesActiveConstant;
import com.hzya.frame.plugin.lets.dao.*;
import com.hzya.frame.plugin.lets.entity.*;
import com.hzya.frame.plugin.lets.ofs.dao.ITocofsReturngoodsDao;
import com.hzya.frame.plugin.lets.ofs.dao.ITocofsReturngoodsDetailedDao;
import com.hzya.frame.plugin.lets.ofs.entity.TocofsReturngoodsDetailedEntity;
import com.hzya.frame.plugin.lets.ofs.entity.TocofsReturngoodsEntity;
import com.hzya.frame.plugin.lets.ofs.entity.TocofsSaleoutDetailedEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsSoSaleOutVo;
import com.hzya.frame.plugin.lets.queryvo.ExtIntegrationTaskLivingDetailsQueryVo;
import com.hzya.frame.plugin.lets.queryvo.StartAndEndVo;
import com.hzya.frame.plugin.lets.resultvo.CalculateDateVo;
import com.hzya.frame.plugin.lets.u8cdto.*;
import com.hzya.frame.plugin.lets.util.*;
import com.hzya.frame.split.SplitListByCountUtil;
import com.hzya.frame.ttxofs.dto.InterfaceParamDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.DetailsDto;
import com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto;
import com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDto;
import com.hzya.frame.ttxofs.dto.ofssalesordersearch.SaleOrderMessageDto;
import com.hzya.frame.ttxofs.dto.returngoodordersearch.RerturnGoodsOrderSearchData;
import com.hzya.frame.ttxofs.dto.returngoodordersearch.RerturnGoodsOrderSearchDetails;
import com.hzya.frame.ttxofs.dto.returngoodordersearch.RerturnGoodsOrderSearchHeader;
import com.hzya.frame.ttxofs.dto.stock.StockinOrderSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * OFS售后入库单(TOB)生成U8C红字销售订单
 *
 * @author makejava
 * @see SoSaleOutPluginInitializerToB TOB销售
 * @since 2024年8月12日 15:03:51
 */
public class SoSaleReturnPluginInitializerToB extends PluginBaseEntity {

    Logger logger = LoggerFactory.getLogger(SoSaleReturnPluginInitializerToB.class);

    @Autowired
    private IBdCorpDao iBdCorpDao;

    @Autowired
    private IBdInvbasdocDao iBdInvbasdocDao;

    @Override
    public void initialize() {
        logger.info(getPluginLabel() + "執行初始化方法initialize()");
    }

    @Override
    public void destroy() {
        logger.info(getPluginLabel() + "執行銷毀方法destroy()");
    }

    @Override
    public String getPluginId() {
        return "sales.SoSaleReturnPluginInitializerToB";
    }

    @Override
    public String getPluginName() {
        return "OFS售后入库单(TOB)生成U8C红字销售订单";
    }

    @Override
    public String getPluginLabel() {
        return "OFS售后入库单(TOB)生成U8C红字销售订单";
    }

    @Override
    public String getPluginType() {
        return "3";
    }

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) throws Exception {
        long startMillis = System.currentTimeMillis();
        logger.info("executeBusiness方法调用开始：" + getPluginName() + "-插件");

        try {
            String param = String.valueOf(requestJson.get("param"));
            String sceneType = String.valueOf(requestJson.get("sceneType"));//sceneType：stock、tran
            if (ProfilesActiveConstant.TYPE_VBILLCODE.equals(requestJson.get("type"))) {
                //按单号
                if (param != null && !"".equals(param)) {
                    startImplementByCode(param, sceneType);
                }
            } else if (ProfilesActiveConstant.TYPE_TIME_FRAME.equals(requestJson.get("type"))) {
                //前台页面功能日期推送，或者接口调用也行
                Assert.notNull(sceneType, "sceneType参数不能为空");
                Assert.notNull(!"".equals(sceneType), "sceneType参数不能为空");
                String craeteDateStr = computingTime(param);
                if (craeteDateStr != null && !"".equals(craeteDateStr)) {
                    splitDateAndPush(craeteDateStr, sceneType);
                }
            } else {
                if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(PROD_FILED)) {
                    //实时执行，每1分钟调度一次
                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    startImplementByStockTime(startAndEndVo.getStart_time(), startAndEndVo.getEnd_time());
                    startImplementByTradeTime(startAndEndVo.getStart_time(), startAndEndVo.getEnd_time());
                }
            }
        } catch (Exception e) {
            logger.error("executeBusiness方法异常", e);
        }
        long endMillis = System.currentTimeMillis();
        logger.info("executeBusiness方法调用结束：" + getPluginName() + "-插件 执行耗时：{}", (endMillis - startMillis));
        return null;
    }

    @Autowired
    private OfsUnifiedService ofsUnifiedService;

    @Autowired
    private IBdTaxitemsDao iBdTaxitemsDao;

    @Autowired
    private IBdCalbodyDao iBdCalbodyDao;

    @Autowired
    private QueryBdBusitypeUtil queryBdBusitypeUtil;

    @Autowired
    private IBdStordocDao iBdStordocDao;

    @Autowired
    private IBdSalestruDao iBdSalestruDao;

    @Autowired
    private IBdCumandocDao iBdCumandocDao;

    @Autowired
    private IBdDeptdocDao iBdDeptdocDao;

    @Autowired
    private IBdCubasdocDao iBdCubasdocDao;

    @Autowired
    private IBdDefdocDao iBdDefdocDao;

    @Autowired
    private IBdInvmandocDao iBdInvmandocDao;

    @Autowired
    private ITocofsReturngoodsDao iTocofsReturngoodsDao;

    @Autowired
    private ITocofsReturngoodsDetailedDao iTocofsReturngoodsDetailedDao;

    @Autowired
    private AfterSalesOrderUtil afterSalesOrderUtil;

    @Autowired
    private ShopTobOrToCUtil shopTobOrToCUtil;

    @Autowired
    private OffsetTimeTime offsetTimeTime;

    @Autowired
    private IIcGeneralHDao iIcGeneralHDao;

    @Autowired
    private IIcGeneralBDao iIcGeneralBDao;

    @Autowired
    private OfsStandardUtil ofsStandardUtil;

    @Autowired
    private RdclUtil rdclUtil;

    @Autowired
    private ISoSaleDao iSoSaleDao;

    @Autowired
    private ISoSaleorderBDao iSoSaleorderBDao;

    @Autowired
    private ISoSaleinvoiceDao iSoSaleinvoiceDao;

    private static final String STOCK = "stock";

    private static final String TRAN = "tran";

    private static final String PROD_FILED = "prod";

    private static final String VNOTETYPE = "RETURN";

    /**
     * 库存同步，按指定时间拉取
     *
     * @author liuyang
     */
    public void startImplementByStockTime(String startTime, String endTime) {
        long startMillis = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 开始时间：{} 结束时间：{}", startTime, endTime);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Assert.notNull(startTime, "startTime不能为空");
                    Assert.notNull(endTime, "endTime不能为空");
                    //生成一个时间范围
//                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    //2024年8月19日 15:47:51 查询出U8C里标记的店铺TOB属性
                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");

                    List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClosedAt_start(startTime);
                    queryOfsSoSaleOutVo.setClosedAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
                    queryOfsSoSaleOutVo.setInternalInstructionType("RETURN");
//                    queryOfsSoSaleOutVo.setCode("LETS-RE2024081900000001");
                    ofsStandardUtil.queryOfsReturnGoods(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.receipt.search");
                    logger.info("数据返回行数：{}", returnGoodHeaderDetailsDataDtoArrayList.size());
                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        getSetStock(returnGoodHeaderDetailsDataDtoArrayList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplement方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 开始时间：{} 结束时间：{} 耗时：{}", startTime, endTime, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 库存同步，按指定时间拉取
     *
     * @author liuyang
     */
    public void startImplementByTradeTime(String startTime, String endTime) {
        long startMillis = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 开始时间：{} 结束时间：{}", startTime, endTime);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Assert.notNull(startTime, "startTime不能为空");
                    Assert.notNull(endTime, "endTime不能为空");

                    //生成一个时间范围
//                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    //2024年8月19日 15:47:51 查询出U8C里标记的店铺TOB属性
                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");

                    List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setRefundedAt_start(startTime);
                    queryOfsSoSaleOutVo.setRefundedAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
                    queryOfsSoSaleOutVo.setInternalInstructionType("RETURN");
                    queryOfsSoSaleOutVo.setRefundStatus("900");
//                    queryOfsSoSaleOutVo.setCode("LETS-RE2024081900000001");
                    ofsStandardUtil.queryOfsReturnGoods(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.receipt.search");
                    logger.info("数据返回行数：{}", returnGoodHeaderDetailsDataDtoArrayList.size());
                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        getSetTrade(returnGoodHeaderDetailsDataDtoArrayList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplement方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 开始时间：{} 结束时间：{} 耗时：{}", startTime, endTime, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 根据售后入库单单号拉取
     *
     * @author liuyang
     */
    public void startImplementByCode(String code, String sceneType) {
        long startMillis = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 售后入库单号：{}", code);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Assert.notNull(code, "code不能为空");
                    //生成一个时间范围
//                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    //2024年8月19日 15:47:51 查询出U8C里标记的店铺TOB属性
                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");

                    List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//                    queryOfsSoSaleOutVo.setClosedAt_start("2002-01-01 00:00:00");// 2024年8月19日 17:13:35 仅作为接口参数验证，O口头反馈根据单号查询，不会启用时间范围搜索
//                    queryOfsSoSaleOutVo.setClosedAt_end("2002-01-01 23:59:59");
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    //测试
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
                    queryOfsSoSaleOutVo.setCode(code);
                    queryOfsSoSaleOutVo.setInternalInstructionType("RETURN");
                    ofsStandardUtil.queryOfsReturnGoods(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.receipt.search");
                    logger.info("数据返回行数：{}", returnGoodHeaderDetailsDataDtoArrayList.size());
                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        if (sceneType.equals("stock")) {
                            getSetStock(returnGoodHeaderDetailsDataDtoArrayList);
                        } else if (sceneType.equals("tran")) {
                            getSetTrade(returnGoodHeaderDetailsDataDtoArrayList);
                        }
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplement方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("OFS售后入库(TOB)同步U8C销售订单(库存同步) 售后入库单号：{} 耗时：{}", code, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 库存同步：环境预配置
     *
     * @author liuyang
     */
    private void getSetStock(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //保存到mysql
        batchInsert(returnGoodHeaderDetailsDataDtoArrayList);
        //过滤成功的数据
        List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = filterDataStock(returnGoodHeaderDetailsDataDtoArrayList);
        //执行推送主逻辑
        implementStock(stockinOrderList);
    }

    /**
     * 到账完成：环境预配置
     *
     * @author liuyang
     */
    private void getSetTrade(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //保存到mysql
        batchInsert(returnGoodHeaderDetailsDataDtoArrayList);
        //过滤成功的数据
        List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = filterDataTran(returnGoodHeaderDetailsDataDtoArrayList);
        //执行推送主逻辑
        implementSuccessfulTrade(stockinOrderList);
    }

    /**
     * 库存：过滤掉成功的数据
     *
     * @author liuyang
     */
    private List<StockinOrderSearchResponse.StockinOrder> filterDataStock(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //        List<StockinOrderSearchResponse.StockinOrder> headerDetailsDtoList1 = new ArrayList<>();
        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList = new ArrayList<>();
        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
            List<List<StockinOrderSearchResponse.StockinOrder>> splitListByCount = SplitListByCountUtil.splitListByCount(returnGoodHeaderDetailsDataDtoArrayList, 100);
            for (int i = 0; i < splitListByCount.size(); i++) {
                List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = splitListByCount.get(i);
                String idStr = commaConcatenatedPrimaryKeyStock(stockinOrderList);
                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = queryStockTocOutLog(idStr);
                tocofsReturngoodsDetailedEntityList.addAll(tocofsReturngoodsDetailedEntities);
            }
        }
        return filterDataRowsAsPushOrFailedStock(tocofsReturngoodsDetailedEntityList, returnGoodHeaderDetailsDataDtoArrayList);
    }

    /**
     * 筛选出未推送、或者失败的数据行，过滤库存同步业务
     *
     * @param tocofsReturngoodsDetailedEntityList     日志行状态，可能为0
     * @param returnGoodHeaderDetailsDataDtoArrayList 返回结果
     * @author liuyang
     */
    private List<StockinOrderSearchResponse.StockinOrder> filterDataRowsAsPushOrFailedStock(List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList, List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        List<StockinOrderSearchResponse.StockinOrder> targetHeaderDetailsDtoList = new ArrayList<>();

        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
            //字段Y(成功)或者为H(待处理)可以视为成功，完成了小段业务闭环的数据行
            String succeseeY = "Y";
            String succeseeH = "H";
            for (int i = 0; i < returnGoodHeaderDetailsDataDtoArrayList.size(); i++) {
                StockinOrderSearchResponse.StockinOrder stockinOrder = returnGoodHeaderDetailsDataDtoArrayList.get(i);
                StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = stockinOrder.getDetails();

                List<StockinOrderSearchResponse.StockinOrder.StockinB> targetDetails = new ArrayList<>();
                for (int j = 0; j < details.size(); j++) {
                    StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                    Boolean isSuccess = false;
                    String newstate = null;
                    if (tocofsReturngoodsDetailedEntityList != null && tocofsReturngoodsDetailedEntityList.size() > 0) {
                        for (int k = 0; k < tocofsReturngoodsDetailedEntityList.size(); k++) {
                            TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = tocofsReturngoodsDetailedEntityList.get(k);
                            if (tocofsReturngoodsDetailedEntity.getId().equals(stockinB.getId())) {
                                newstate = tocofsReturngoodsDetailedEntity.getNewstate();
                                if (succeseeY.equals(newstate) || succeseeH.equals(newstate)) {
                                    isSuccess = true;
                                }
                            }
                        }
                    }
                    if (!isSuccess) {
                        stockinB.setNewstate(newstate);
                        targetDetails.add(stockinB);
                    }
                }
                if (targetDetails.size() > 0) {
                    //如果明细行中，还存在未推送或者失败的数据，则需要更新明细行
                    stockinOrder.setDetails(targetDetails);
                    targetHeaderDetailsDtoList.add(stockinOrder);
                }
            }
        }
        return targetHeaderDetailsDtoList;
    }

    /**
     * 筛选出未推送、或者失败的数据行，过滤库存同步业务
     *
     * @param tocofsReturngoodsDetailedEntityList     日志行状态
     * @param returnGoodHeaderDetailsDataDtoArrayList 返回结果
     * @author liuyang
     */
    private List<StockinOrderSearchResponse.StockinOrder> filterDataRowsAsPushOrFailedTran(List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList, List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        List<StockinOrderSearchResponse.StockinOrder> targetHeaderDetailsDtoList = new ArrayList<>();

        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
            //字段Y(成功)或者为H(待处理)可以视为成功，完成了小段业务闭环的数据行
            String succeseeY = "Y";
            String succeseeH = "H";
            for (int i = 0; i < returnGoodHeaderDetailsDataDtoArrayList.size(); i++) {
                StockinOrderSearchResponse.StockinOrder stockinOrder = returnGoodHeaderDetailsDataDtoArrayList.get(i);
                StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = stockinOrder.getDetails();

                List<StockinOrderSearchResponse.StockinOrder.StockinB> targetDetails = new ArrayList<>();
                for (int j = 0; j < details.size(); j++) {
                    StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                    Boolean isSuccess = false;
                    String newstate = null;
                    if (tocofsReturngoodsDetailedEntityList != null && tocofsReturngoodsDetailedEntityList.size() > 0) {
                        for (int k = 0; k < tocofsReturngoodsDetailedEntityList.size(); k++) {
                            TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = tocofsReturngoodsDetailedEntityList.get(k);
                            if (tocofsReturngoodsDetailedEntity.getId().equals(stockinB.getId())) {
                                newstate = tocofsReturngoodsDetailedEntity.getNewstate2();
                                if (succeseeY.equals(newstate) || succeseeH.equals(newstate)) {
                                    isSuccess = true;
                                }
                            }
                        }
                    }
                    if (!isSuccess) {
                        stockinB.setNewstate(newstate);
                        targetDetails.add(stockinB);
                    }
                }
                if (targetDetails.size() > 0) {
                    //如果明细行中，还存在未推送或者失败的数据，则需要更新明细行
                    stockinOrder.setDetails(targetDetails);
                    targetHeaderDetailsDtoList.add(stockinOrder);
                }
            }
        }
        return targetHeaderDetailsDtoList;
    }

    /**
     * 批查询toc退货入库日志，查询的量由splitListByCount方法控制
     *
     * @author liuyang
     */
    private List<TocofsReturngoodsDetailedEntity> queryStockTocOutLog(String idStr) throws Exception {
        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = null;
        if (idStr != null && !"".equals(idStr.trim())) {
            TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = new TocofsReturngoodsDetailedEntity();
            tocofsReturngoodsDetailedEntity.setIds(idStr);
            tocofsReturngoodsDetailedEntities = iTocofsReturngoodsDetailedDao.query(tocofsReturngoodsDetailedEntity);
        } else {
            logger.error("idStr为空，无法查询数据！");
        }
        return tocofsReturngoodsDetailedEntities;
    }

    /**
     * 逗号拼接字符串主键，作为批处理的一部分，方便下一步的批量查询操作
     *
     * @author liuyang
     */
    private String commaConcatenatedPrimaryKeyStock(List<StockinOrderSearchResponse.StockinOrder> headerDetailsDtoList2) throws Exception {
        StringBuffer idStr = new StringBuffer();
        if (headerDetailsDtoList2 != null && headerDetailsDtoList2.size() > 0) {
            for (int i = 0; i < headerDetailsDtoList2.size(); i++) {
                StockinOrderSearchResponse.StockinOrder stockinOrder = headerDetailsDtoList2.get(i);
                StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = stockinOrder.getDetails();
                for (int j = 0; j < details.size(); j++) {
                    StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                    Assert.notNull(stockinB.getId(), "O明细主键不能为空！");
                    Assert.state(!"".equals(stockinB.getId()), "O明细主键不能为空！");
                    idStr.append(stockinB.getId());
                    idStr.append(",");
                }
            }
        }
        if (idStr.length() > 0) {
            return idStr.substring(0, idStr.length() - 1);
        }
        return null;
    }

    /**
     * 确认收入：过滤掉成功的数据
     *
     * @author liuyang
     */
    private List<StockinOrderSearchResponse.StockinOrder> filterDataTran(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //        List<StockinOrderSearchResponse.StockinOrder> headerDetailsDtoList1 = new ArrayList<>();
        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList = new ArrayList<>();
        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
            List<List<StockinOrderSearchResponse.StockinOrder>> splitListByCount = SplitListByCountUtil.splitListByCount(returnGoodHeaderDetailsDataDtoArrayList, 100);
            for (int i = 0; i < splitListByCount.size(); i++) {
                List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = splitListByCount.get(i);
                String idStr = commaConcatenatedPrimaryKeyStock(stockinOrderList);
                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = queryStockTocOutLog(idStr);
                tocofsReturngoodsDetailedEntityList.addAll(tocofsReturngoodsDetailedEntities);
            }
        }
        return filterDataRowsAsPushOrFailedTran(tocofsReturngoodsDetailedEntityList, returnGoodHeaderDetailsDataDtoArrayList);
    }

    /**
     * 保存抓取到的数据到mysql底表，如果底表里已经存在，则会忽略
     *
     * @param returnGoodHeaderDetailsDataDtoArrayList 数据行
     */
    private void batchInsert(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
            List<StockinOrderSearchResponse.StockinOrder.StockinH> headerDetailsDtoList1 = new ArrayList<>();
            List<StockinOrderSearchResponse.StockinOrder.StockinB> headerDetailsDtoList2 = new ArrayList<>();
            for (StockinOrderSearchResponse.StockinOrder index : returnGoodHeaderDetailsDataDtoArrayList) {
                StockinOrderSearchResponse.StockinOrder.StockinH header = index.getHeader();// 主表
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = index.getDetails();//明细表
                for (int i = 0; i < details.size(); i++) {
                    StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(i);
                    stockinB.setReturnGoodSearchHeaderDto(header);
                }
                headerDetailsDtoList1.add(header);
                headerDetailsDtoList2.addAll(details);
            }

            //每100作为一个批次插入主表，根据主键（id）判断是否重复，如果重复的，则不进行插入
            List<List<StockinOrderSearchResponse.StockinOrder.StockinH>> lists = SplitListByCountUtil.splitListByCount(headerDetailsDtoList1, 100);
            for (int i = 0; i < lists.size(); i++) {
                List<StockinOrderSearchResponse.StockinOrder.StockinH> stockinHS = lists.get(i);
                List<TocofsReturngoodsEntity> tocofsReturngoodsEntities = copyHeaderDto(stockinHS);
                if (tocofsReturngoodsEntities.size() > 0) {
                    logger.info("TocofsReturngoodsEntity：插入底表{}个对象（表头）", tocofsReturngoodsEntities.size());
                    iTocofsReturngoodsDao.entityInsertOrUpdateBatch(tocofsReturngoodsEntities);
                } else {
                    logger.info("TocofsReturngoodsEntity：没有对象被插入表头底表");
                }
            }

            //插入明细表
            List<List<StockinOrderSearchResponse.StockinOrder.StockinB>> lists1 = SplitListByCountUtil.splitListByCount(headerDetailsDtoList2, 100);
            for (int i = 0; i < lists1.size(); i++) {
                List<StockinOrderSearchResponse.StockinOrder.StockinB> stockinBS = lists1.get(i);
                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = copyDetailsDto(stockinBS);
                if (tocofsReturngoodsDetailedEntities.size() > 0) {
                    logger.info("TocofsReturngoodsDetailedEntity：插入底表{}个对象（表体）", tocofsReturngoodsDetailedEntities.size());
                    iTocofsReturngoodsDetailedDao.entityInsertOrUpdateBatch(tocofsReturngoodsDetailedEntities);
                } else {
                    logger.info("TocofsReturngoodsDetailedEntity：没有对象被插入表头底表");
                }
            }
        } else {
            logger.info("returnGoodHeaderDetailsDataDtoArrayList为空或者原始为零!");
        }
    }

    /**
     * 代码同步逻辑
     *
     * @param returnGoodHeaderDetailsDataDtoList 查询得到的O出库单对象
     * @author liuyang
     */
    private void implementStock(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoList != null) {
            logger.info("TOB售后入库：{}行需要进行数据转换", returnGoodHeaderDetailsDataDtoList.size());
        }
        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            try {
                // 查询基本档案
//                String sceneType = "stock";
                List<OrderToBHeaderDto> orderToBHeaderDtos = queryBasicArchivesStock(returnGoodHeaderDetailsDataDtoList);
                // 查询U8C业务流程
                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
                // 查询销售收发类别
//                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("201");

                for (int i = 0; i < orderToBHeaderDtos.size(); i++) {
                    OrderToBHeaderDto orderOutTobHeaderDto = orderToBHeaderDtos.get(i);
                    StockinOrderSearchResponse.StockinOrder.StockinH header = orderOutTobHeaderDto.getHeader();
                    List<StockinOrderSearchResponse.StockinOrder.StockinB> details = orderOutTobHeaderDto.getDetails();
                    try {
                        //销售公司、发货公司
                        BdCorpEntity bdCorpEntity = orderOutTobHeaderDto.getBdCorpEntity();
                        //发货库存组织
                        BdCalbodyEntity bdCalbodyEntity = orderOutTobHeaderDto.getBdCalbodyEntity();
                        //入库参数
                        BdStordocEntity bdStordocEntity = orderOutTobHeaderDto.getBdStordocEntity();
                        //销售组织
                        BdSalestruEntity bdSalestruEntity = orderOutTobHeaderDto.getBdSalestruEntity();
                        //业务部门
                        BdDeptdocEntity bdDeptdocEntity = orderOutTobHeaderDto.getBdDeptdocEntity();
                        //客商基本档案
                        BdCubasdocEntity bdCubasdocEntity = orderOutTobHeaderDto.getBdCubasdocEntity();
                        //客商基本档案
                        BdCumandocEntity bdCumandocEntity = orderOutTobHeaderDto.getBdCumandocEntity();
                        //发货公司
                        BdCorpEntity deliverGoodsCorp = orderOutTobHeaderDto.getDeliverGoodsCorp();
                        //平台档案
                        BdDefdocEntity platformArchives = orderOutTobHeaderDto.getPlatformArchives();
                        //U8C店铺档案
                        BdDefdocEntity shopArchives = orderOutTobHeaderDto.getShopArchives();
                        //生成业务日期
                        String generateBusinessDate = createGenerateBusinessDate(orderOutTobHeaderDto);
                        //U8C销售订单
                        SoSaleEntity soSaleEntity = orderOutTobHeaderDto.getSoSaleEntity();
                        //OFS销售订单
                        SaleOrderMessageDto saleOrderMessageDto = orderOutTobHeaderDto.getSaleOrderMessageDto();
                        //OFS售后订单
                        RerturnGoodsOrderSearchData ofsRertunOrder1 = orderOutTobHeaderDto.getOfsRertunOrder();
                        //OFS收发类别
                        BdRdclEntity bdRdclEntity = orderOutTobHeaderDto.getBdRdclEntity();

                        SaleorderRequestDto saleorderRequestDto = new SaleorderRequestDto();
                        SaleorderRequestParentDto saleorderRequestParentDto = new SaleorderRequestParentDto();
                        saleorderRequestParentDto.setDbilldate(generateBusinessDate);//单据日期
                        saleorderRequestParentDto.setBretinvflag("Y");//退货标记
                        saleorderRequestParentDto.setCbiztype(bdBusitypeEntity.getPkBusitype());//业务流程
                        saleorderRequestParentDto.setCcalbodyid(bdCalbodyEntity.getPkCalbody());//库存组织
                        saleorderRequestParentDto.setCcustomerid(bdCumandocEntity.getPkCumandoc());//客户=开票单位=收货单位=表体收货单位=收货单位
                        saleorderRequestParentDto.setCdeptid(bdDeptdocEntity.getPkDeptdoc());//部门
                        saleorderRequestParentDto.setCemployeeid(null);//业务员
                        saleorderRequestParentDto.setCoperatorid(OverallConstant.getOverAllValue("u8cApiZdrPK"));//制单人
                        saleorderRequestParentDto.setCreceiptcorpid(bdCumandocEntity.getPkCumandoc());//开票单位
                        saleorderRequestParentDto.setCreceiptcustomerid(bdCumandocEntity.getPkCumandoc());//收货单位
                        saleorderRequestParentDto.setCsalecorpid(bdSalestruEntity.getCsalestruid());//销售组织
                        saleorderRequestParentDto.setCwarehouseid(bdStordocEntity.getPkStordoc());//仓库
                        saleorderRequestParentDto.setDapprovedate(generateBusinessDate);//审核日期
                        saleorderRequestParentDto.setNdiscountrate("100.000000");//整单折扣
                        saleorderRequestParentDto.setPk_corp(bdCorpEntity.getPkCorp());//公司id
                        saleorderRequestParentDto.setVdef17(ProfilesActiveConstant.sourceSystem1);//来源系统

                        //原单单号、原单主键，销售发票就是靠这个字段关联的
                        saleorderRequestParentDto.setVdef19(header.getCode());
                        saleorderRequestParentDto.setVdef20(header.getId());

                        //平台
                        saleorderRequestParentDto.setPk_defdoc2(platformArchives.getPkDefdoc());
                        saleorderRequestParentDto.setVdef2(platformArchives.getDocname());

                        //店铺
                        saleorderRequestParentDto.setPk_defdoc1(shopArchives.getPkDefdoc());
                        saleorderRequestParentDto.setVdef1(shopArchives.getDocname());

                        //收发类别
                        saleorderRequestParentDto.setPk_defdoc3(bdRdclEntity.getPkRdcl());
                        saleorderRequestParentDto.setVdef3(bdRdclEntity.getRdname());

                        saleorderRequestDto.setParentvo(saleorderRequestParentDto);

                        List<SaleorderRequestChildrenDto> saleorderRequestChildrenDtoList = new ArrayList<>();
                        saleorderRequestDto.setChildrenvo(saleorderRequestChildrenDtoList);

                        //把汇总好的出库单明细行合并成一行
                        for (int j = 0; j < details.size(); j++) {
                            StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                            //存货管理档案：取发货公司的存货管理档案
                            BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(stockinB, bdCalbodyEntity.getPkCorp());
                            //存货基础档案
                            BdInvbasdocEntity bdInvbasdocEntity = queryStockBasicArchives(bdInvmandocEntity.getPkInvmandoc(), deliverGoodsCorp.getPkCorp());
                            //根据存货基础档案编码，查询当前存货的税率
                            BdTaxitemsEntity bdTaxitemsEntity1 = queryBdTaxitems(bdInvbasdocEntity.getInvcode());
                            //取对应的售后订单明细，主要是取这个价格
                            RerturnGoodsOrderSearchDetails afterSalesOrder = findAfterSalesOrder(stockinB, ofsRertunOrder1);

                            String tax = "0." + new BigDecimal(bdTaxitemsEntity1.getTaxratio()).stripTrailingZeros().toPlainString();

                            // 如果是海外的店铺，则税率为零
                            String exportVaue = ExportConstant.exportConstant.get(header.getStoreCode());
                            if (exportVaue != null) {
                                tax = "0";
                            }

                            BigDecimal noriginalcurprice = null;//无税单价
                            BigDecimal noriginalcurmny = null;//无税金额
                            BigDecimal noriginalcurtaxprice = null;//含税单价
                            BigDecimal noriginalcursummny = null;//价税合计
                            BigDecimal noriginalcurtaxmny = null;//税额
                            try {
                                Assert.notNull(stockinB.getTotalAmount(), "退货入库单总金额不能为空 明细行对象:{}", JSON.toJSONString(stockinB));
                                Assert.notNull(stockinB.getReceivedQty(), "实收数量不能为空  明细行对象:{}", JSON.toJSONString(stockinB));

                                noriginalcurtaxprice = new BigDecimal(afterSalesOrder.getTotalAmount()).divide(new BigDecimal(stockinB.getReceivedQty()), 20, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP);
                                noriginalcurprice = noriginalcurtaxprice.divide(new BigDecimal(1).add(new BigDecimal(tax)), 20, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP);
                                noriginalcurmny = noriginalcurprice.multiply(new BigDecimal(stockinB.getReceivedQty())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                noriginalcursummny = noriginalcurtaxprice.multiply(new BigDecimal(stockinB.getReceivedQty())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                noriginalcurtaxmny = noriginalcursummny.subtract(noriginalcurmny).setScale(2, BigDecimal.ROUND_HALF_UP);
                            } catch (Exception e) {
                                logger.error("TOB金额计算错误", e);
                                Assert.state(false, "TOB金额计算错误，原因：{}", e.getMessage());
                            }

                            //判断是否为赠品
                            Boolean isblargessflag = false;
                            if (noriginalcursummny.longValue() == 0) {
                                isblargessflag = true;
                            }

                            SaleorderRequestChildrenDto saleorderRequestChildrenDto = new SaleorderRequestChildrenDto();
                            saleorderRequestChildrenDto.setBlargessflag(isblargessflag);//是否赠品
                            saleorderRequestChildrenDto.setCadvisecalbodyid(bdCalbodyEntity.getPkCalbody());//发货库存组织
                            saleorderRequestChildrenDto.setCbodywarehouseid(bdStordocEntity.getPkStordoc());//发货仓库
                            saleorderRequestChildrenDto.setCconsigncorpid(deliverGoodsCorp.getPkCorp());//发货公司
                            saleorderRequestChildrenDto.setCcurrencytypeid("00010000000000000001");//币种
                            saleorderRequestChildrenDto.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());//存货id
                            saleorderRequestChildrenDto.setCreceiptcorpid(bdCumandocEntity.getPkCumandoc());//收货单位
                            saleorderRequestChildrenDto.setDconsigndate(generateBusinessDate);//计划发货日期
                            saleorderRequestChildrenDto.setDdeliverdate(generateBusinessDate);//	要求收货日期
                            saleorderRequestChildrenDto.setNexchangeotobrate("1.00000000");//折本汇率
                            saleorderRequestChildrenDto.setNitemdiscountrate("100.000000");//单品折扣
                            saleorderRequestChildrenDto.setNnumber("-" + stockinB.getReceivedQty());//数量
                            saleorderRequestChildrenDto.setNoriginalcurdiscountmny("0");//折扣额
                            saleorderRequestChildrenDto.setNoriginalcurmny("-" + noriginalcurmny.stripTrailingZeros().toPlainString());//无税金额
//                            saleorderRequestChildrenDto.setNoriginalcurnetprice(noriginalcurprice.stripTrailingZeros().toPlainString());//无税净价
//                            saleorderRequestChildrenDto.setNoriginalcurprice(noriginalcurprice.stripTrailingZeros().toPlainString());//无税单价
                            saleorderRequestChildrenDto.setNoriginalcursummny("-" + noriginalcursummny.stripTrailingZeros().toPlainString());//价税合计
                            saleorderRequestChildrenDto.setNoriginalcurtaxmny("-" + noriginalcurtaxmny.stripTrailingZeros().toPlainString());//税额
                            saleorderRequestChildrenDto.setNoriginalcurtaxnetprice(noriginalcurtaxprice.stripTrailingZeros().toPlainString());//含税净价
                            saleorderRequestChildrenDto.setNoriginalcurtaxprice(noriginalcurtaxprice.stripTrailingZeros().toPlainString());//含税单价
                            saleorderRequestChildrenDto.setNtaxrate(new BigDecimal(bdTaxitemsEntity1.getTaxratio()).stripTrailingZeros().toPlainString());//税率
                            saleorderRequestChildrenDto.setVdef20(stockinB.getId());//原单明细主键
                            saleorderRequestChildrenDtoList.add(saleorderRequestChildrenDto);
                        }
                        //记录成功
                        //销售订单单据推送到u8c
                        List<SaleorderRequestDto> saleorderRequestDtoList = new ArrayList<>();
                        saleorderRequestDtoList.add(saleorderRequestDto);

                        Boolean aBoolean = checkTobOrder(header.getId(), header.getCode());
                        if (!aBoolean) {
                            logger.error("经过SQL查询判断，在U8C(红字)销售订单不存在OFS入库单号为：{} OFS入库主键为：{}的单据，将调用U8C接口执行推送！", header.getCode(), header.getId());
                            Map<String, List<SaleorderRequestDto>> stringStringMap = new HashMap<>();
                            stringStringMap.put("saleorder", saleorderRequestDtoList);
                            SoSaleResultRootDto soSaleResultRootDto = sendU8CTOCOrder(JSON.toJSONString(stringStringMap));
                            String vreceiptcode = null;
                            String csaleid = null;
                            String pk_corp = null;
                            if (soSaleResultRootDto != null) {
                                SoSaleResultHeadDto parentvo = soSaleResultRootDto.getParentvo();
                                List<SoSaleResultBodyDto> childrenvo = soSaleResultRootDto.getChildrenvo();
                                vreceiptcode = parentvo.getVreceiptcode();
                                csaleid = parentvo.getCsaleid();
                                pk_corp = parentvo.getPk_corp();
                            }
                            logger.info("TOB红字销售订单编号：{} 销售订单主键：{} 销售公司：{}", vreceiptcode, csaleid, pk_corp);
                            //记录成功
                            updateSuccessOrFail1(details, "Y", "success", vreceiptcode, csaleid);
                        } else {
                            logger.error("经过SQL查询判断，在U8C(红字)销售订单存在OFS入库单号为：{} OFS入库主键为：{}的单据，为了避免造成单据重复，不推送到U8C！", header.getCode(), header.getId());
                        }
                    } catch (Exception e) {
                        logger.error("TOB售后收入推送U8C失败", e);
                        //记录失败
                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        updateSuccessOrFail1(details, "N", message, null, null);
                    }
                }
            } catch (Exception e) {
                logger.error("TOB外层转换逻辑抛出异常", e);
            }
        }
    }

    /**
     * 2024年7月31日 10:34:09
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDate(OrderToBHeaderDto orderOutTobHeaderDto) {
        if (orderOutTobHeaderDto != null && orderOutTobHeaderDto.getHeader() != null && orderOutTobHeaderDto.getHeader().getCheckInFrom() != null) {
            StockinOrderSearchResponse.StockinOrder.StockinH header = orderOutTobHeaderDto.getHeader();
            String checkInFrom = header.getCheckInFrom();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(checkInFrom);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("业务日期生成失败", e);
            }
            return businessFormat;
        } else {
            logger.error("生成出库日期失败，或者checkInFrom为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            Assert.state(false, "生成出库日期失败，或者checkInFrom为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            return null;
        }
    }

    /**
     * 库存同步，档案转换
     *
     * @author liuyang
     */
    private List<OrderToBHeaderDto> queryBasicArchivesStock(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoList != null) {
            logger.info("库存同步：需要把OFS档案转换为U8C档案的O数据条数：{}", returnGoodHeaderDetailsDataDtoList.size());
        }
        List<OrderToBHeaderDto> orderToBHeaderDtoArrayList = new ArrayList<>();
        List<ErrorHeaderDetailsDtoDtoV2> errorHeaderDetailsDtoDtoList = new ArrayList<>();

        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            for (int i = 0; i < returnGoodHeaderDetailsDataDtoList.size(); i++) {
                StockinOrderSearchResponse.StockinOrder stockinOrder = returnGoodHeaderDetailsDataDtoList.get(i);
                StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = stockinOrder.getDetails();

                try {
                    //查询售后订单
                    RerturnGoodsOrderSearchData ofsRertunOrder = afterSalesOrderUtil.getOfsRertunOrder(header.getRefOrderCode());
                    Assert.notNull(ofsRertunOrder, "无法查询到OFS售后订单 编码：{}", header.getRefOrderCode());

                    //查询销售订单
                    SaleOrderMessageDto saleOrderMessageDto = null;
                    try {
                        saleOrderMessageDto = afterSalesOrderUtil.getOfsOrder(ofsRertunOrder.getHeader().getRefOrderCode());
                    } catch (Exception e) {
                        logger.error("查询出售后订单错误，失败原因：{}", e.getMessage());
                        Assert.state(false, "查询出售后订单错误，失败原因：{}", e.getMessage());
                    }

                    if (saleOrderMessageDto == null) {
                        Assert.state(false, "没有匹配到售后订单，系统业务无法完成");
                    }
                    HeaderDto header1 = saleOrderMessageDto.getData().get(0).getHeader();
                    String memberId = header1.getMemberId();
                    //TODO 会员id
//                    memberId = "GYS00002";
                    Assert.notNull(memberId, "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");
                    Assert.state(!"".equals(memberId.trim()), "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");

                    //查询对应的收发类别
                    if (header1.getSubOrderType() == null || "".equals(header1.getSubOrderType().trim())) {
                        header1.setSubOrderType("SALES");
                    }
                    BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject(header1.getSubOrderType());
                    Assert.notNull(bdRdclEntity, "根据收发类别编码：{} 无法匹配到U8C收发类别");

                    // 销售公司、发货公司
                    String companyCode = header.getCompanyCode();
                    //TODO 测试
//                    companyCode = "SHLZ";
                    Assert.notNull(companyCode, "O表头公司不能为空");
                    BdCorpEntity bdCorpEntity = new BdCorpEntity();
                    bdCorpEntity.setDr(0);
                    bdCorpEntity.setDataSourceCode("lets_u8c");
                    bdCorpEntity.setUnitcode(companyCode);
                    List<BdCorpEntity> bdCorpEntityList = iBdCorpDao.query(bdCorpEntity);
                    if (bdCorpEntityList.size() == 0) {
                        Assert.state(false, "根据O货主编码{}，无法匹配到U8C销售公司", companyCode);
                    } else if (bdCorpEntityList.size() >= 2) {
                        Assert.state(false, "根据O货主编码{}，匹配到U8C销售公司{}个", companyCode, bdCorpEntityList.size());
                    }

                    // 发货库存组织
                    BdCalbodyEntity bdCalbodyEntity = new BdCalbodyEntity();
                    bdCalbodyEntity.setDr(0);
                    bdCalbodyEntity.setDataSourceCode("lets_u8c");
                    bdCalbodyEntity.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    List<BdCalbodyEntity> bdCalbodyEntities = iBdCalbodyDao.query(bdCalbodyEntity);
                    if (bdCalbodyEntities.size() == 0) {
                        Assert.state(false, "根据U8C发货公司{}，无法匹配到U8C发货库存组织", bdCorpEntityList.get(0).getPkCorp());
                    } else if (bdCalbodyEntities.size() >= 2) {
                        Assert.state(false, "根据U8C发货公司{}，匹配到U8C发货库存组织{}个", bdCorpEntityList.get(0).getPkCorp(), bdCalbodyEntities.size());
                    }

                    // 仓库
                    String facilityCode = header.getFacilityCode();
                    Assert.notNull(facilityCode, "O售后入库单仓库facilityCode字段不能为空");
                    BdStordocEntity bdStordocEntity = new BdStordocEntity();
                    bdStordocEntity.setDr(0L);
                    bdStordocEntity.setDataSourceCode("lets_u8c");
                    bdStordocEntity.setPkCalbody(bdCalbodyEntities.get(0).getPkCalbody());
                    bdStordocEntity.setStorcode(facilityCode);
                    List<BdStordocEntity> bdStordocEntityList = iBdStordocDao.query(bdStordocEntity);
                    if (bdStordocEntityList.size() == 0) {
                        Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，无法匹配到U8C仓库", facilityCode, bdCalbodyEntities.get(0).getPkCalbody());
                    } else if (bdStordocEntityList.size() >= 2) {
                        Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，匹配到U8C仓库多个", facilityCode, bdCalbodyEntities.get(0).getPkCalbody());
                    }

                    //销售组织
                    //2024年8月13日 10:35:05 已经和佳妮在微信确认，U8C销售公司编码与U8C销售组织编码保持一致，因此通过销售公司编码匹配
                    BdSalestruEntity bdSalestruEntity = new BdSalestruEntity();
                    bdSalestruEntity.setDr(0);
                    bdSalestruEntity.setDataSourceCode("lets_u8c");
                    bdSalestruEntity.setVsalestrucode(bdCorpEntityList.get(0).getUnitcode());
                    List<BdSalestruEntity> bdSalestruEntityList = iBdSalestruDao.query(bdSalestruEntity);
                    if (bdSalestruEntityList.size() == 0) {
                        Assert.state(false, "根据U8C销售公司编码：{}，无法匹配到U8C销售组织", bdCorpEntityList.get(0).getUnitcode());
                    } else if (bdSalestruEntityList.size() >= 2) {
                        Assert.state(false, "根据U8C销售公司编码：{}，无法匹配到U8C销售组织", bdCorpEntityList.get(0).getUnitcode());
                    }

                    //业务部门
                    //2024年8月14日 10:38:37 已经和佳妮确认
                    String deptName = "其他部门";
                    BdDeptdocEntity bdDeptdocEntity = new BdDeptdocEntity();
                    bdDeptdocEntity.setDataSourceCode("lets_u8c");
                    bdDeptdocEntity.setDr(0);
                    bdDeptdocEntity.setDeptname(deptName);
                    bdDeptdocEntity.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    List<BdDeptdocEntity> bdDeptdocEntityList = iBdDeptdocDao.query(bdDeptdocEntity);
                    if (bdDeptdocEntityList.size() == 0) {
                        Assert.state(false, "根据部门名称：{} 公司id：{}，无法匹配到U8C销售组织", deptName, bdCorpEntityList.get(0).getPkCorp());
                    } else if (bdDeptdocEntityList.size() >= 2) {
                        Assert.state(false, "根据部门名称：{} 公司id：{}，匹配到U8C销售组织{}个", deptName, bdCorpEntityList.get(0).getPkCorp());
                    }

                    //客商基本档案
//                    String custName = "天猫intoyou旗舰店-自营";
                    BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
                    bdCubasdocEntity.setDataSourceCode("lets_u8c");
                    bdCubasdocEntity.setDr(0L);
                    bdCubasdocEntity.setDef1(memberId);
                    List<BdCubasdocEntity> bdCubasdocEntityList = iBdCubasdocDao.query(bdCubasdocEntity);
                    if (bdCubasdocEntityList == null || bdCubasdocEntityList.size() == 0) {
                        Assert.state(false, "根据OFS会员id{}，无法查询到U8C客商基本档案", memberId);
                    } else if (bdCubasdocEntityList.size() >= 2) {
                        Assert.state(false, "根据OFS会员id{}，无法查询到U8C客商基本档案", memberId);
                    }

                    //客商管理档案
                    BdCumandocEntity bdCumandocEntity1 = new BdCumandocEntity();
                    bdCumandocEntity1.setDataSourceCode("lets_u8c");
                    bdCumandocEntity1.setDr(0L);
                    bdCumandocEntity1.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    bdCumandocEntity1.setPkCubasdoc(bdCubasdocEntityList.get(0).getPkCubasdoc());
                    bdCumandocEntity1.setCustflags(ProfilesActiveConstant.CUSTOMER);
                    List<BdCumandocEntity> bdCumandocEntityList = iBdCumandocDao.query(bdCumandocEntity1);
                    if (bdCumandocEntityList == null || bdCumandocEntityList.size() == 0) {
                        Assert.state(false, "根据客商基本档案主键{}，没有办法查询到客商管理档案", bdCubasdocEntityList.get(0).getPkCubasdoc());
                    }

                    //查找平台
//                    String platformZdyId = "0001A210000000000JUD";
                    String platformZdyId = OverallConstant.getOverAllValue("u8c自定义项档案-平台主键");
                    String sourcePlatformCode = header.getSourcePlatformCode();
                    BdDefdocEntity bdDefdocEntity = new BdDefdocEntity();
                    bdDefdocEntity.setPkDefdoclist(platformZdyId);
                    bdDefdocEntity.setDr(0);
                    bdDefdocEntity.setDataSourceCode("lets_u8c");
                    bdDefdocEntity.setDoccode(sourcePlatformCode);
                    List<BdDefdocEntity> bdDefdocEntityList = iBdDefdocDao.query(bdDefdocEntity);
                    if (bdDefdocEntityList.size() == 0) {
                        Assert.state(false, "根据O平台编码{}，无法匹配到U8C平台自定义档案 自定义档案主键:{}", sourcePlatformCode, platformZdyId);
                    } else if (bdDefdocEntityList.size() >= 2) {
                        Assert.state(false, "根据O平台编码{}，无法匹配到U8C平台自定义档案 自定义档案主键:{}", sourcePlatformCode, platformZdyId);
                    }

                    //查询U8C店铺档案
//                    String platformZdyId2 = "0001A210000000000XZX";
                    String platformZdyId2 = OverallConstant.getOverAllValue("u8c自定义项档案-店铺主键");
                    String ofsStoreCode = header.getStoreCode();
                    BdDefdocEntity bdDefdocEntity2 = new BdDefdocEntity();
                    bdDefdocEntity2.setPkDefdoclist(platformZdyId2);
                    bdDefdocEntity2.setDr(0);
                    bdDefdocEntity2.setDataSourceCode("lets_u8c");
                    bdDefdocEntity2.setDoccode(ofsStoreCode);
                    List<BdDefdocEntity> bdDefdocEntityList2 = iBdDefdocDao.query(bdDefdocEntity2);
                    if (bdDefdocEntityList2.size() == 0) {
                        Assert.state(false, "根据O店铺编码{}，无法匹配到U8C店铺自定义档案 自定义档案主键:{}", ofsStoreCode, platformZdyId);
                    } else if (bdDefdocEntityList2.size() >= 2) {
                        Assert.state(false, "根据O店铺编码{}，无法匹配到U8C店铺自定义档案 自定义档案主键:{}", ofsStoreCode, platformZdyId);
                    }

                    OrderToBHeaderDto orderOutTobHeaderDto = new OrderToBHeaderDto();
                    orderOutTobHeaderDto.setBdCorpEntity(bdCorpEntityList.get(0));
                    orderOutTobHeaderDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
                    orderOutTobHeaderDto.setBdStordocEntity(bdStordocEntityList.get(0));
                    orderOutTobHeaderDto.setBdSalestruEntity(bdSalestruEntityList.get(0));
                    orderOutTobHeaderDto.setBdDeptdocEntity(bdDeptdocEntityList.get(0));
                    orderOutTobHeaderDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
                    orderOutTobHeaderDto.setBdCubasdocEntity(bdCubasdocEntityList.get(0));
                    orderOutTobHeaderDto.setDeliverGoodsCorp(bdCorpEntityList.get(0));
                    orderOutTobHeaderDto.setPlatformArchives(bdDefdocEntityList.get(0));
                    orderOutTobHeaderDto.setShopArchives(bdDefdocEntityList2.get(0));
                    orderOutTobHeaderDto.setSaleOrderMessageDto(saleOrderMessageDto);
                    orderOutTobHeaderDto.setOfsRertunOrder(ofsRertunOrder);
                    orderOutTobHeaderDto.setBdRdclEntity(bdRdclEntity);

                    orderOutTobHeaderDto.setHeader(header);
                    orderOutTobHeaderDto.setDetails(details);

                    orderToBHeaderDtoArrayList.add(orderOutTobHeaderDto);
                } catch (Exception e) {
                    logger.error("档案转换失败", e);

                    //失败
                    String message = e.getMessage();
                    if (message == null) {
                        message = "未知错误";
                    }
                    ErrorHeaderDetailsDtoDtoV2 errorHeaderDetailsDtoDto = new ErrorHeaderDetailsDtoDtoV2();
                    errorHeaderDetailsDtoDto.setNewPushDate(getNewDateStr());
                    errorHeaderDetailsDtoDto.setNewTransmitInfo(message);
                    errorHeaderDetailsDtoDto.setNewstate("N");
                    errorHeaderDetailsDtoDto.setHeader(header);
                    errorHeaderDetailsDtoDto.setDetails(details);
                    errorHeaderDetailsDtoDtoList.add(errorHeaderDetailsDtoDto);
                }
            }
            //成功
        } else {
            logger.info("queryBasicArchives方法对应的returnGoodHeaderDetailsDataDtoList.size为0");
        }
        if (errorHeaderDetailsDtoDtoList.size() > 0) {
            updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryStock(errorHeaderDetailsDtoDtoList);
        }
        return orderToBHeaderDtoArrayList;
    }

    /**
     * 交易成功档案查询，档案转换
     *
     * @param returnGoodHeaderDetailsDataDtoList 查询出来的售后入库单数据
     * @author liuyang
     */
    private List<OrderToBHeaderDto> queryBasicArchivesTran(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) {
        if (returnGoodHeaderDetailsDataDtoList != null) {
            logger.info("确认收入：需要把OFS档案转换为U8C档案的O数据条数：{}", returnGoodHeaderDetailsDataDtoList.size());
        }
        List<OrderToBHeaderDto> orderToBHeaderDtoArrayList = new ArrayList<>();
        List<ErrorHeaderDetailsDtoDtoV2> errorHeaderDetailsDtoDtoList = new ArrayList<>();

        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            for (int i = 0; i < returnGoodHeaderDetailsDataDtoList.size(); i++) {
                StockinOrderSearchResponse.StockinOrder stockinOrder = returnGoodHeaderDetailsDataDtoList.get(i);
                StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
                List<StockinOrderSearchResponse.StockinOrder.StockinB> details = stockinOrder.getDetails();

                try {
                    //查询OFS售后订单
                    RerturnGoodsOrderSearchData ofsRertunOrder = afterSalesOrderUtil.getOfsRertunOrder(header.getRefOrderCode());
                    Assert.notNull(ofsRertunOrder, "无法查询到OFS售后订单 编码：{}", header.getRefOrderCode());

                    //查询OFS销售订单
                    SaleOrderMessageDto saleOrderMessageDto = null;
                    try {
                        saleOrderMessageDto = afterSalesOrderUtil.getOfsOrder(ofsRertunOrder.getHeader().getRefOrderCode());
                    } catch (Exception e) {
                        logger.error("查询出售后订单错误，失败原因：{}", e.getMessage());
                        Assert.state(false, "查询出售后订单错误，失败原因：{}", e.getMessage());
                    }

                    if (saleOrderMessageDto == null) {
                        Assert.state(false, "没有匹配到售后订单，系统业务无法完成");
                    }
                    HeaderDto header1 = saleOrderMessageDto.getData().get(0).getHeader();
                    String memberId = header1.getMemberId();
                    //TODO 测试
//                    memberId = "GYS00002";
                    Assert.notNull(memberId, "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");
                    Assert.state(!"".equals(memberId.trim()), "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");

                    //查询对应的收发类别
                    if (header1.getSubOrderType() == null || "".equals(header1.getSubOrderType().trim())) {
                        header1.setSubOrderType("SALES");
                    }
                    BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject(header1.getSubOrderType());
                    Assert.notNull(bdRdclEntity, "根据收发类别编码：{} 无法匹配到U8C收发类别");

                    //2024年8月30日 10:57:29 查询对应的U8C销售订单，注意要把编码和主键一起查询，O主键导入到U8C中，对于U8C来说可能会重复
                    SoSaleEntity soSaleEntity = new SoSaleEntity();
                    soSaleEntity.setDr(0L);
                    soSaleEntity.setDataSourceCode("lets_u8c");
                    soSaleEntity.setVdef19(header.getCode());
                    soSaleEntity.setVdef20(header.getId());
                    soSaleEntity.setBretinvflag("Y");//仅查询红字销售订单
                    List<SoSaleEntity> soSaleEntityList = iSoSaleDao.query(soSaleEntity);
                    if (soSaleEntityList == null || soSaleEntityList.size() == 0) {
                        Assert.state(false, "根据O售后入库单主键：{} 单号：{} 无法匹配到U8C红字销售订单(传到U8C可能失败了！bretinvflag=Ys)", header.getId(), header.getCode());
                    } else if (soSaleEntityList.size() >= 2) {
                        Assert.state(false, "根据O出库单主键：{} 单号：{} 匹配到{}个U8C销售订单", header.getId(), header.getCode(), soSaleEntityList.size());
                    }

                    //查询销售订单明细行表体
                    SoSaleorderBEntity soSaleorderBEntity = new SoSaleorderBEntity();
                    soSaleorderBEntity.setDr(0L);
                    soSaleorderBEntity.setCsaleid(soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    soSaleorderBEntity.setDataSourceCode("lets_u8c");
                    List<SoSaleorderBEntity> soSaleorderBEntityList = iSoSaleorderBDao.query(soSaleorderBEntity);
                    if (soSaleorderBEntityList == null || soSaleorderBEntityList.size() == 0) {
                        Assert.state(false, "根据O销售订单主键：{}，无法匹配到U8C销售订单明细行(传到U8C可能失败了！)", soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    } else if (soSaleorderBEntityList.size() >= 2) {
                        Assert.state(false, "根据O销售订单主键：{}，无法匹配到U8C销售订单明细行(传到U8C可能失败了！)", soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    }

                    //查询U8C销售订单对应的销售出库单表头
                    IcGeneralHEntity icGeneralHEntity = new IcGeneralHEntity();
                    icGeneralHEntity.setCsourcebillhid(soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    icGeneralHEntity.setDr(0);
                    icGeneralHEntity.setDataSourceCode("lets_u8c");
                    List<IcGeneralHEntity> icGeneralHEntityList = iIcGeneralHDao.query(icGeneralHEntity);
                    if (icGeneralHEntityList == null || icGeneralHEntityList.size() == 0) {
                        Assert.state(false, "根据U8C销售订单表头id:{}，无法查询到销售出库单", soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    } else if (icGeneralHEntityList.size() >= 2) {
                        Assert.state(false, "根据U8C销售订单表头id:{}，查询到{}个销售出库单", soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid(), icGeneralHEntityList.size());
                    }

                    //查询U8C销售订单对应的销售出库单表体
                    IcGeneralBEntity icGeneralBEntity = new IcGeneralBEntity();
                    icGeneralBEntity.setCsourcebillhid(soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    icGeneralBEntity.setDr(0);
                    icGeneralBEntity.setDataSourceCode("lets_u8c");
                    List<IcGeneralBEntity> icGeneralBEntityList = iIcGeneralBDao.query(icGeneralBEntity);
                    if (icGeneralBEntityList == null || icGeneralBEntityList.size() == 0) {
                        Assert.state(false, "根据U8C销售订单表头id:{}，无法查询到销售出库单明细行", soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    }

                    //2024年8月30日 11:09:32 查询U8C销售订单执行情况明细表，主要是带出U8C销售订单表体的自定义项
                    SoSaleorderBEntity soSaleorderBEntity1 = new SoSaleorderBEntity();
                    soSaleorderBEntity1.setCsaleid(soSaleEntityList.get(soSaleEntityList.size() - 1).getCsaleid());
                    List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos = iSoSaleorderBDao.queryErrorDetailsId(soSaleorderBEntity1);
                    if (extIntegrationTaskLivingDetailsQueryVos == null || extIntegrationTaskLivingDetailsQueryVos.size() == 0) {
                        Assert.state(false, "根据销售订单主键：{}，无法匹配到销售订单执行情况明细");
                    }

                    // 销售公司、发货公司
                    String companyCode = header.getCompanyCode();
                    //TODO 测试
//                    companyCode = "SHLZ";
                    Assert.notNull(companyCode, "O表头公司不能为空");
                    BdCorpEntity bdCorpEntity = new BdCorpEntity();
                    bdCorpEntity.setDr(0);
                    bdCorpEntity.setDataSourceCode("lets_u8c");
                    bdCorpEntity.setUnitcode(companyCode);
                    List<BdCorpEntity> bdCorpEntityList = iBdCorpDao.query(bdCorpEntity);
                    if (bdCorpEntityList.size() == 0) {
                        Assert.state(false, "根据O货主编码{}，无法匹配到U8C销售公司", companyCode);
                    } else if (bdCorpEntityList.size() >= 2) {
                        Assert.state(false, "根据O货主编码{}，匹配到U8C销售公司{}个", companyCode, bdCorpEntityList.size());
                    }

                    // 发货库存组织
                    BdCalbodyEntity bdCalbodyEntity = new BdCalbodyEntity();
                    bdCalbodyEntity.setDr(0);
                    bdCalbodyEntity.setDataSourceCode("lets_u8c");
                    bdCalbodyEntity.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    List<BdCalbodyEntity> bdCalbodyEntities = iBdCalbodyDao.query(bdCalbodyEntity);
                    if (bdCalbodyEntities.size() == 0) {
                        Assert.state(false, "根据U8C发货公司{}，无法匹配到U8C发货库存组织", bdCorpEntityList.get(0).getPkCorp());
                    } else if (bdCalbodyEntities.size() >= 2) {
                        Assert.state(false, "根据U8C发货公司{}，匹配到U8C发货库存组织{}个", bdCorpEntityList.get(0).getPkCorp(), bdCalbodyEntities.size());
                    }

                    // 仓库
                    String facilityCode = header.getFacilityCode();
                    Assert.notNull(facilityCode, "O售后入库单仓库facilityCode字段不能为空");
                    BdStordocEntity bdStordocEntity = new BdStordocEntity();
                    bdStordocEntity.setDr(0L);
                    bdStordocEntity.setDataSourceCode("lets_u8c");
                    bdStordocEntity.setPkCalbody(bdCalbodyEntities.get(0).getPkCalbody());
                    bdStordocEntity.setStorcode(facilityCode);
                    List<BdStordocEntity> bdStordocEntityList = iBdStordocDao.query(bdStordocEntity);
                    if (bdStordocEntityList.size() == 0) {
                        Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，无法匹配到U8C仓库", facilityCode, bdCalbodyEntities.get(0).getPkCalbody());
                    } else if (bdStordocEntityList.size() >= 2) {
                        Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，匹配到U8C仓库多个", facilityCode, bdCalbodyEntities.get(0).getPkCalbody());
                    }

                    //销售组织
                    //2024年8月13日 10:35:05 已经和佳妮在微信确认，U8C销售公司编码与U8C销售组织编码保持一致，因此通过销售公司编码匹配
                    BdSalestruEntity bdSalestruEntity = new BdSalestruEntity();
                    bdSalestruEntity.setDr(0);
                    bdSalestruEntity.setDataSourceCode("lets_u8c");
                    bdSalestruEntity.setVsalestrucode(bdCorpEntityList.get(0).getUnitcode());
                    List<BdSalestruEntity> bdSalestruEntityList = iBdSalestruDao.query(bdSalestruEntity);
                    if (bdSalestruEntityList.size() == 0) {
                        Assert.state(false, "根据U8C销售公司编码：{}，无法匹配到U8C销售组织", bdCorpEntityList.get(0).getUnitcode());
                    } else if (bdSalestruEntityList.size() >= 2) {
                        Assert.state(false, "根据U8C销售公司编码：{}，无法匹配到U8C销售组织", bdCorpEntityList.get(0).getUnitcode());
                    }

                    //业务部门
                    //2024年8月14日 10:38:37 已经和佳妮确认
                    String deptName = "其他部门";
                    BdDeptdocEntity bdDeptdocEntity = new BdDeptdocEntity();
                    bdDeptdocEntity.setDataSourceCode("lets_u8c");
                    bdDeptdocEntity.setDr(0);
                    bdDeptdocEntity.setDeptname(deptName);
                    bdDeptdocEntity.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    List<BdDeptdocEntity> bdDeptdocEntityList = iBdDeptdocDao.query(bdDeptdocEntity);
                    if (bdDeptdocEntityList.size() == 0) {
                        Assert.state(false, "根据部门名称：{} 公司id：{}，无法匹配到U8C销售组织", deptName, bdCorpEntityList.get(0).getPkCorp());
                    } else if (bdDeptdocEntityList.size() >= 2) {
                        Assert.state(false, "根据部门名称：{} 公司id：{}，匹配到U8C销售组织{}个", deptName, bdCorpEntityList.get(0).getPkCorp());
                    }

                    //客商基本档案
                    BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
                    bdCubasdocEntity.setDataSourceCode("lets_u8c");
                    bdCubasdocEntity.setDr(0L);
                    bdCubasdocEntity.setDef1(memberId);
                    List<BdCubasdocEntity> bdCubasdocEntityList = iBdCubasdocDao.query(bdCubasdocEntity);
                    if (bdCubasdocEntityList == null || bdCubasdocEntityList.size() == 0) {
                        Assert.state(false, "根据OFS会员id{}，无法查询到U8C客商基本档案", memberId);
                    } else if (bdCubasdocEntityList.size() >= 2) {
                        Assert.state(false, "根据OFS会员id{}，无法查询到U8C客商基本档案", memberId);
                    }

                    //客商管理档案
                    BdCumandocEntity bdCumandocEntity1 = new BdCumandocEntity();
                    bdCumandocEntity1.setDataSourceCode("lets_u8c");
                    bdCumandocEntity1.setDr(0L);
                    bdCumandocEntity1.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    bdCumandocEntity1.setPkCubasdoc(bdCubasdocEntityList.get(0).getPkCubasdoc());
                    bdCumandocEntity1.setCustflags(ProfilesActiveConstant.CUSTOMER);
                    List<BdCumandocEntity> bdCumandocEntityList = iBdCumandocDao.query(bdCumandocEntity1);
                    if (bdCumandocEntityList == null || bdCumandocEntityList.size() == 0) {
                        Assert.state(false, "根据客商基本档案主键{}，没有办法查询到客商管理档案", bdCubasdocEntityList.get(0).getPkCubasdoc());
                    }

                    //查找平台
//                    String platformZdyId = "0001A210000000000JUD";
                    String platformZdyId = OverallConstant.getOverAllValue("u8c自定义项档案-平台主键");
                    String sourcePlatformCode = header.getSourcePlatformCode();
                    BdDefdocEntity bdDefdocEntity = new BdDefdocEntity();
                    bdDefdocEntity.setPkDefdoclist(platformZdyId);
                    bdDefdocEntity.setDr(0);
                    bdDefdocEntity.setDataSourceCode("lets_u8c");
                    bdDefdocEntity.setDoccode(sourcePlatformCode);
                    List<BdDefdocEntity> bdDefdocEntityList = iBdDefdocDao.query(bdDefdocEntity);
                    if (bdDefdocEntityList.size() == 0) {
                        Assert.state(false, "根据O平台编码{}，无法匹配到U8C平台自定义档案 自定义档案主键:{}", sourcePlatformCode, platformZdyId);
                    } else if (bdDefdocEntityList.size() >= 2) {
                        Assert.state(false, "根据O平台编码{}，无法匹配到U8C平台自定义档案 自定义档案主键:{}", sourcePlatformCode, platformZdyId);
                    }

                    //查询U8C店铺档案
//                    String platformZdyId2 = "0001A210000000000XZX";
                    String platformZdyId2 = OverallConstant.getOverAllValue("u8c自定义项档案-店铺主键");
                    String ofsStoreCode = header.getStoreCode();
                    BdDefdocEntity bdDefdocEntity2 = new BdDefdocEntity();
                    bdDefdocEntity2.setPkDefdoclist(platformZdyId2);
                    bdDefdocEntity2.setDr(0);
                    bdDefdocEntity2.setDataSourceCode("lets_u8c");
                    bdDefdocEntity2.setDoccode(ofsStoreCode);
                    List<BdDefdocEntity> bdDefdocEntityList2 = iBdDefdocDao.query(bdDefdocEntity2);
                    if (bdDefdocEntityList2.size() == 0) {
                        Assert.state(false, "根据O店铺编码{}，无法匹配到U8C店铺自定义档案 自定义档案主键:{}", ofsStoreCode, platformZdyId);
                    } else if (bdDefdocEntityList2.size() >= 2) {
                        Assert.state(false, "根据O店铺编码{}，无法匹配到U8C店铺自定义档案 自定义档案主键:{}", ofsStoreCode, platformZdyId);
                    }

                    //2024年8月28日 11:01:07 查询对应的U8C销售订单
//                    SoSaleEntity soSaleEntity = new SoSaleEntity();
//                    soSaleEntity.setDr(0L);
//                    soSaleEntity.setDataSourceCode("lets_u8c");
//                    soSaleEntity.setVdef19(header.getCode());
//                    soSaleEntity.setVdef20(header.getId());
//                    List<SoSaleEntity> soSaleEntityList = iSoSaleDao.query(soSaleEntity);
//                    if (soSaleEntityList == null || soSaleEntityList.size() == 0) {
//                        Assert.state(false, "根据O出库单主键：{} 单号：{} 无法匹配到U8C销售订单(传到U8C可能失败了！)", header.getId(), header.getCode());
//                    } else if (soSaleEntityList.size() >= 2) {
//                        Assert.state(false, "根据O出库单主键：{} 单号：{} 匹配到{}个U8C销售订单", header.getId(), header.getCode(), soSaleEntityList.size());
//                    }

                    OrderToBHeaderDto orderOutTobHeaderDto = new OrderToBHeaderDto();
                    orderOutTobHeaderDto.setBdCorpEntity(bdCorpEntityList.get(0));
                    orderOutTobHeaderDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
                    orderOutTobHeaderDto.setBdStordocEntity(bdStordocEntityList.get(0));
                    orderOutTobHeaderDto.setBdSalestruEntity(bdSalestruEntityList.get(0));
                    orderOutTobHeaderDto.setBdDeptdocEntity(bdDeptdocEntityList.get(0));
                    orderOutTobHeaderDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
                    orderOutTobHeaderDto.setBdCubasdocEntity(bdCubasdocEntityList.get(0));
                    orderOutTobHeaderDto.setDeliverGoodsCorp(bdCorpEntityList.get(0));
                    orderOutTobHeaderDto.setPlatformArchives(bdDefdocEntityList.get(0));
                    orderOutTobHeaderDto.setShopArchives(bdDefdocEntityList2.get(0));
                    orderOutTobHeaderDto.setSaleOrderMessageDto(saleOrderMessageDto);
                    orderOutTobHeaderDto.setSoSaleEntity(soSaleEntityList.get(0));
                    orderOutTobHeaderDto.setIcGeneralHEntity(icGeneralHEntityList.get(0));
                    orderOutTobHeaderDto.setIcGeneralBEntityList(icGeneralBEntityList);
                    orderOutTobHeaderDto.setSoSaleorderBEntityList(soSaleorderBEntityList);
                    orderOutTobHeaderDto.setExtIntegrationTaskLivingDetailsQueryVos(extIntegrationTaskLivingDetailsQueryVos);
                    orderOutTobHeaderDto.setOfsRertunOrder(ofsRertunOrder);
                    orderOutTobHeaderDto.setBdRdclEntity(bdRdclEntity);

                    orderOutTobHeaderDto.setHeader(header);
                    orderOutTobHeaderDto.setDetails(details);

                    BeanUtil.copyPropertiesV2(header, orderOutTobHeaderDto);
                    orderToBHeaderDtoArrayList.add(orderOutTobHeaderDto);
                } catch (Exception e) {
                    logger.error("TOB退货确认收入", e);

                    //失败
                    String message = e.getMessage();
                    if (message == null) {
                        message = "未知错误";
                    }
                    ErrorHeaderDetailsDtoDtoV2 errorHeaderDetailsDtoDto = new ErrorHeaderDetailsDtoDtoV2();
                    errorHeaderDetailsDtoDto.setNewPushDate2(getNewDateStr());
                    errorHeaderDetailsDtoDto.setNewTransmitInfo2(message);
                    errorHeaderDetailsDtoDto.setNewstate2("N");
                    errorHeaderDetailsDtoDto.setHeader(header);
                    errorHeaderDetailsDtoDto.setDetails(details);
                    errorHeaderDetailsDtoDtoList.add(errorHeaderDetailsDtoDto);
                }
            }
        } else {
            logger.info("queryBasicArchives方法对应的returnGoodHeaderDetailsDataDtoList.size为0");
        }
        if (errorHeaderDetailsDtoDtoList.size() > 0) {
            updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryTran(errorHeaderDetailsDtoDtoList);
        }
        return orderToBHeaderDtoArrayList;
    }

    /**
     * bean copy
     * 2024年8月15日 14:19:36
     */
    private List<TocofsReturngoodsEntity> copyHeaderDto(List<StockinOrderSearchResponse.StockinOrder.StockinH> stockinHS) {
        List<TocofsReturngoodsEntity> tocofsReturngoodsEntityArrayList = new ArrayList<>();
        if (stockinHS != null && stockinHS.size() > 0) {
            for (int i = 0; i < stockinHS.size(); i++) {
                StockinOrderSearchResponse.StockinOrder.StockinH stockinH = stockinHS.get(i);

                TocofsReturngoodsEntity tocofsReturngoodsEntity = new TocofsReturngoodsEntity();
                BeanUtil.copyPropertiesV2(stockinH, tocofsReturngoodsEntity);
                tocofsReturngoodsEntityArrayList.add(tocofsReturngoodsEntity);
            }
        } else {
            logger.info("需要复制{}个bean对象(O表头)", stockinHS.size());
        }
        return tocofsReturngoodsEntityArrayList;
    }

    /**
     * bean copy
     * 2024年8月15日 14:24:38
     */
    private List<TocofsReturngoodsDetailedEntity> copyDetailsDto(List<StockinOrderSearchResponse.StockinOrder.StockinB> stockinBS) {
        List<TocofsReturngoodsDetailedEntity> tocofsSaleoutDetailedEntityArrayList = new ArrayList<>();
        if (stockinBS != null && stockinBS.size() > 0) {
            for (int i = 0; i < stockinBS.size(); i++) {
                StockinOrderSearchResponse.StockinOrder.StockinB stockinB = stockinBS.get(i);

                //明细行中引用的表头
                StockinOrderSearchResponse.StockinOrder.StockinH returnGoodSearchHeaderDto = stockinB.getReturnGoodSearchHeaderDto();

                TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = new TocofsReturngoodsDetailedEntity();
//                tocofsReturngoodsDetailedEntity.setBusinessType("TOB_RETURN");
                //处理填充额外字段
                BeanUtil.copyPropertiesV2(stockinB, tocofsReturngoodsDetailedEntity);
                createPrimaryKeyAndBusinessDateAndBusinessType(tocofsReturngoodsDetailedEntity, returnGoodSearchHeaderDto);
                tocofsSaleoutDetailedEntityArrayList.add(tocofsReturngoodsDetailedEntity);
            }
        } else {
            logger.info("需要复制{}个bean对象(O表体)", tocofsSaleoutDetailedEntityArrayList.size());
        }
        return tocofsSaleoutDetailedEntityArrayList;
    }

    /**
     * 2024年8月6日 10:59:03 查询U8C业务流程
     *
     * @author liuyang
     */
    private BdBusitypeEntity u8cOperationFlow() throws Exception {
        //查询业务流程
        //2024年8月6日 11:33:07 具体的业务流程名称，还需要实施提供
        String processName = "TOB销售";
        BdBusitypeEntity bdBusitypeEntity = queryBdBusitypeUtil.queryBdBusitype(processName);
        Assert.notNull(bdBusitypeEntity, "根据业务流程名称({})没有查询到业务流程", processName);
        return bdBusitypeEntity;
    }

    /**
     * 查询存货管理档案
     *
     * @param pkCorp     发货公司主键
     * @param detailsDto 出库单存货明细行
     * @author liuyang
     */
    private BdInvmandocEntity queryInventoryMan(StockinOrderSearchResponse.StockinOrder.StockinB detailsDto, String pkCorp) throws Exception {
        Assert.notNull(detailsDto, "sonDetailsDto不能为空");
        Assert.notNull(detailsDto.getSkuCode(), "O存货商家编码不能为空");
        Assert.notNull(pkCorp, "发货公司主键不能为空");

        BdInvmandocEntity bdInvmandocEntity = new BdInvmandocEntity();
        bdInvmandocEntity.setInvcode(detailsDto.getSkuCode());
        bdInvmandocEntity.setPkCorp(pkCorp);
        List<BdInvmandocEntity> bdInvmandocEntity2 = iBdInvmandocDao.queryBdInvmandocByInvcodeList(bdInvmandocEntity);
        if (bdInvmandocEntity2.size() == 0) {
            Assert.state(false, "根据O商家编码：{} U8C发货公司主键：{}没有查询到存货管理档案", detailsDto.getSkuCode(), pkCorp);
        } else if (bdInvmandocEntity2.size() >= 2) {
            Assert.state(false, "根据O商家编码：{} U8C发货公司主键：{}没有查询到存货管理档案", detailsDto.getSkuCode(), pkCorp);
        }
        return bdInvmandocEntity2.get(0);
    }

    /**
     * 2024年8月7日 10:25:29
     * 查询基础档案，根据公司、管理档案主键查询
     *
     * @author liuyang
     */
    private BdInvbasdocEntity queryStockBasicArchives(String pkInvmandoc, String pkCorp) throws Exception {
        Assert.notNull(pkInvmandoc, "存货管理档案不能为空");
        Assert.notNull(pkCorp, "公司档案不能为空");

        BdInvbasdocEntity bdInvbasdocEntity = new BdInvbasdocEntity();
        bdInvbasdocEntity.setPk_invmandoc(pkInvmandoc);
        bdInvbasdocEntity.setPk_corp(pkCorp);
        List<BdInvbasdocEntity> bdInvbasdocEntity2 = iBdInvbasdocDao.queryBdInvbasdocByPkInvmandocV2(bdInvbasdocEntity);
        if (bdInvbasdocEntity2.size() == 0) {
            Assert.state(false, "根据存货管理档案主键{}和公司档案主键{}没有查询到U8C基础档案", pkInvmandoc, pkCorp);
        } else if (bdInvbasdocEntity2.size() >= 2) {
            Assert.state(false, "根据存货管理档案主键{}和公司档案主键{}没有查询到U8C基础档案", pkInvmandoc, pkCorp);
        }
        return bdInvbasdocEntity2.get(0);
    }

    /**
     * 2024年8月7日 14:58:34
     * 查询税目档案
     *
     * @author liuyang
     */
    private BdTaxitemsEntity queryBdTaxitems(String invcode) throws Exception {
        Assert.notNull(invcode, "存货编码不能为空");

        BdTaxitemsEntity bdTaxitemsEntity = new BdTaxitemsEntity();
        bdTaxitemsEntity.setInvcode(invcode);
        List<BdTaxitemsEntity> bdTaxitemsEntityList = iBdTaxitemsDao.queryBdInvbasdocByInvcodeV2(bdTaxitemsEntity);
        if (bdTaxitemsEntityList.size() == 0) {
            Assert.state(false, "根据存货编码{}没有查询到U8C税目档案", invcode);
        } else if (bdTaxitemsEntityList.size() >= 2) {
            Assert.state(false, "根据存货编码{}没有查询到U8C税目档案", invcode);
        }
        return bdTaxitemsEntityList.get(0);
    }

    /**
     * 2024年8月8日 10:54:48
     * 推送U8C销售订单方法
     *
     * @author liuyang
     */
    public SoSaleResultRootDto sendU8CTOCOrder(String param) {
        long startLong = System.currentTimeMillis();
        logger.info("TOB推送开始，推送参数：" + param + ",U8C_URL:" + OverallConstant.getOverAllValue("u8c_url"));
        String apiCode = "8000370006";
        String result = HttpRequest.post(OverallConstant.getOverAllValue("u8c_url")).header("appId", OverallConstant.getOverAllValue("appId"))//头信息，多个头信息多次调用此方法即可
                .header("usercode", OverallConstant.getOverAllValue("u8cApiUsercodePK")).header("password", OverallConstant.getOverAllValue("u8cApiPasswordPK")).header("system", OverallConstant.getOverAllValue("u8cApiSystemPK")).header("trantype", OverallConstant.getOverAllValue("u8cApiTrantypePK")).header("apiCode", apiCode)//头信息，多个头信息多次调用此方法即可
                .header("publicKey", OverallConstant.getOverAllValue("publicKey"))//头信息，多个头信息多次调用此方法即可
                .header("secretKey", OverallConstant.getOverAllValue("secretKey"))//头信息，多个头信息多次调用此方法即可
                .body(param)//表单内容
                .timeout(600000)//超时，毫秒
                .execute().body();
        logger.info("TOB推送结束，返回参数：" + result);
        long endLong = System.currentTimeMillis();
        logger.info("TOB接口请求耗时：" + (endLong - startLong));

        JSONObject jsonObject = JSON.parseObject(result);
        result = String.valueOf(jsonObject.get("attribute"));

        boolean isSuccess = false;
        SoSaleResultRootDto soSaleResultRootDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                soSaleResultRootDto = resultDataHandle(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "TOB业务O出库单推送U8C销售订单失败 接口返回结果：{}", result);
        }
        return soSaleResultRootDto;
    }

    /**
     * 返回结果解析处理，在确认了success后调用
     *
     * @author liuyang
     */
    private SoSaleResultRootDto resultDataHandle(String resultData) {
        try {
            if (resultData != null && !"".equals(resultData)) {
                if (resultData.contains("[")) {
                    resultData = resultData.substring(1, resultData.length() - 1);
                }
                return JSON.parseObject(resultData, SoSaleResultRootDto.class);
            }
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }

    /**
     * 返回结果解析处理，在确认了success后调用
     *
     * @author liuyang
     */
    private SaleinvoiceDto resultDataHandleV2(String resultData) {
        try {
            if (resultData != null && !"".equals(resultData)) {
                if (resultData.contains("[")) {
                    resultData = resultData.substring(1, resultData.length() - 1);
                }
                return JSON.parseObject(resultData, SaleinvoiceDto.class);
            }
        } catch (Exception e) {
//            e.printStackTrace();
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }

    /**
     * 填充主表主键、业务日期、业务类型
     * 2024年8月15日 17:31:54
     */
    private void createPrimaryKeyAndBusinessDateAndBusinessType(TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity, StockinOrderSearchResponse.StockinOrder.StockinH returnGoodSearchHeaderDto) {
        if (tocofsReturngoodsDetailedEntity != null && returnGoodSearchHeaderDto != null) {
            //主表主键
            if (returnGoodSearchHeaderDto.getId() != null) {
                tocofsReturngoodsDetailedEntity.setMaintableid(returnGoodSearchHeaderDto.getId());
            }
            //业务日期-入库时间
            if (returnGoodSearchHeaderDto.getCheckInFrom() != null) {
                tocofsReturngoodsDetailedEntity.setBusinessdate(returnGoodSearchHeaderDto.getCheckInFrom());
            }
            //业务日期-退款完成时间
            if (returnGoodSearchHeaderDto.getRefundedAt() != null) {
                tocofsReturngoodsDetailedEntity.setRefundedat(returnGoodSearchHeaderDto.getRefundedAt());
            }
            //业务类型
            tocofsReturngoodsDetailedEntity.setBusinesstype("TOB_RETURN");
        }
    }

    /**
     * 交易成功，代码同步逻辑
     *
     * @param returnGoodHeaderDetailsDataDtoList 查询得到的O出库单对象
     * @author liuyang
     */
    private void implementSuccessfulTrade(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoList != null) {
            logger.info("TOB售后入库退货到账完成：{}行需要进行数据转换", returnGoodHeaderDetailsDataDtoList.size());
        }
        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            try {
                //转换基本档案
//                String sceneType = "tran";
                List<OrderToBHeaderDto> orderToBHeaderDtos = queryBasicArchivesTran(returnGoodHeaderDetailsDataDtoList);
                //查询U8C业务流程
                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
                //查询销售收发类别
//                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("201");

                logger.info("TOB销售业务退货到账成功同步，档案转换成功对应的数量：{}行需要进行数据转换", orderToBHeaderDtos.size());
                logger.info("TOB销售发票业务流程编码：{}", bdBusitypeEntity.getBusicode());
                for (int i = 0; i < orderToBHeaderDtos.size(); i++) {
                    OrderToBHeaderDto orderOutTobHeaderDto = orderToBHeaderDtos.get(i);
                    StockinOrderSearchResponse.StockinOrder.StockinH header = orderOutTobHeaderDto.getHeader();
                    List<StockinOrderSearchResponse.StockinOrder.StockinB> details = orderOutTobHeaderDto.getDetails();

                    try {
                        //销售公司、发货公司
                        BdCorpEntity bdCorpEntity = orderOutTobHeaderDto.getBdCorpEntity();
                        //发货库存组织
                        BdCalbodyEntity bdCalbodyEntity = orderOutTobHeaderDto.getBdCalbodyEntity();
                        //入库仓库
                        BdStordocEntity bdStordocEntity = orderOutTobHeaderDto.getBdStordocEntity();
                        //销售组织
                        BdSalestruEntity bdSalestruEntity = orderOutTobHeaderDto.getBdSalestruEntity();
                        //业务部门
                        BdDeptdocEntity bdDeptdocEntity = orderOutTobHeaderDto.getBdDeptdocEntity();
                        //客商基本档案
                        BdCubasdocEntity bdCubasdocEntity = orderOutTobHeaderDto.getBdCubasdocEntity();
                        //客商管理档案
                        BdCumandocEntity bdCumandocEntity = orderOutTobHeaderDto.getBdCumandocEntity();
                        //发货公司
                        BdCorpEntity deliverGoodsCorp = orderOutTobHeaderDto.getDeliverGoodsCorp();
                        //平台档案
                        BdDefdocEntity platformArchives = orderOutTobHeaderDto.getPlatformArchives();
                        //生成业务日期
                        String successfulTradeDate = createSuccessFulTradeDate(orderOutTobHeaderDto);
                        //店铺
                        BdDefdocEntity shopArchives = orderOutTobHeaderDto.getShopArchives();
                        //U8C销售订单
                        SoSaleEntity soSaleEntity = orderOutTobHeaderDto.getSoSaleEntity();
                        //U8C销售订单明细行
                        List<SoSaleorderBEntity> soSaleorderBEntityList = orderOutTobHeaderDto.getSoSaleorderBEntityList();
                        //U8C销售出库单
                        IcGeneralHEntity icGeneralHEntity = orderOutTobHeaderDto.getIcGeneralHEntity();
                        //U8C销售出库单明细行
                        List<IcGeneralBEntity> icGeneralBEntityList = orderOutTobHeaderDto.getIcGeneralBEntityList();
                        //U8C销售订单执行情况明细表
                        List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos = orderOutTobHeaderDto.getExtIntegrationTaskLivingDetailsQueryVos();
                        //OFS销售订单
                        SaleOrderMessageDto saleOrderMessageDto = orderOutTobHeaderDto.getSaleOrderMessageDto();
                        //OFS售后订单
                        RerturnGoodsOrderSearchData ofsRertunOrder = orderOutTobHeaderDto.getOfsRertunOrder();
                        //OFS收发类别
                        BdRdclEntity bdRdclEntity = orderOutTobHeaderDto.getBdRdclEntity();

                        //红字销售发票表头
                        SalesInvoiceHeadDto salesInvoiceHeadDto = new SalesInvoiceHeadDto();
                        salesInvoiceHeadDto.setCbiztype(bdBusitypeEntity.getPkBusitype());
                        salesInvoiceHeadDto.setCcalbodyid(bdCalbodyEntity.getPkCalbody());
                        salesInvoiceHeadDto.setCoperatorid(OverallConstant.getOverAllValue("u8cApiZdrPK"));//制单人
                        salesInvoiceHeadDto.setCreceiptcorpid(bdCumandocEntity.getPkCumandoc());
                        salesInvoiceHeadDto.setCsalecorpid(bdSalestruEntity.getCsalestruid());
                        salesInvoiceHeadDto.setPk_corp(bdCorpEntity.getPkCorp());
                        salesInvoiceHeadDto.setDbilldate(successfulTradeDate);
                        salesInvoiceHeadDto.setFinvoicetype("1");//不传默认为1
                        salesInvoiceHeadDto.setCdeptid(bdDeptdocEntity.getPkDeptdoc());//部门
                        salesInvoiceHeadDto.setCwarehouseid(bdStordocEntity.getPkStordoc());//仓库
                        salesInvoiceHeadDto.setCdispatcherid(bdRdclEntity.getPkRdcl());//收发类别
                        salesInvoiceHeadDto.setCreceiptcustomerid(bdCumandocEntity.getPkCumandoc());//收货单位
                        salesInvoiceHeadDto.setCreceipttype("32");//单据类型
                        salesInvoiceHeadDto.setDmakedate(successfulTradeDate);//制单日期
                        salesInvoiceHeadDto.setNdiscountrate("100");//整单折扣
                        salesInvoiceHeadDto.setDapprovedate(successfulTradeDate);//审批日期
                        salesInvoiceHeadDto.setVnote(VNOTETYPE);
                        salesInvoiceHeadDto.setVdef17(ProfilesActiveConstant.sourceSystem1);
                        salesInvoiceHeadDto.setVdef19(header.getCode());
                        salesInvoiceHeadDto.setVdef20(header.getId());
                        //平台
                        salesInvoiceHeadDto.setPk_defdoc2(platformArchives.getPkDefdoc());
                        salesInvoiceHeadDto.setVdef2(platformArchives.getDocname());
                        //店铺
                        salesInvoiceHeadDto.setPk_defdoc1(shopArchives.getPkDefdoc());
                        salesInvoiceHeadDto.setVdef1(shopArchives.getDocname());

                        List<SalesInvoiceBodyDto> salesInvoiceBodyDtoList = new ArrayList<>();
                        for (int j = 0; j < details.size(); j++) {
                            StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                            //存货管理档案：取发货公司的存货管理档案
                            BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(stockinB, bdCalbodyEntity.getPkCorp());
                            //存货基础档案
                            BdInvbasdocEntity bdInvbasdocEntity = queryStockBasicArchives(bdInvmandocEntity.getPkInvmandoc(), deliverGoodsCorp.getPkCorp());
                            //根据存货基础档案编码，查询当前存货的税率
                            BdTaxitemsEntity bdTaxitemsEntity1 = queryBdTaxitems(bdInvbasdocEntity.getInvcode());
                            //2024年8月30日 11:20:08 查找对应的售后订单的明细行，主要取价格
                            RerturnGoodsOrderSearchDetails afterSalesOrder = findAfterSalesOrder(stockinB, ofsRertunOrder);
                            //查找来源单据，销售发票的来源单据为销售出库单
                            IcGeneralBEntity sourceDocuments = findSourceDocuments(header, stockinB, soSaleorderBEntityList, icGeneralBEntityList, extIntegrationTaskLivingDetailsQueryVos);
                            //查找来源销售订单明细行
                            SoSaleorderBEntity sourceDocumentsV2 = findSourceDocumentsV2(header, stockinB, soSaleorderBEntityList, extIntegrationTaskLivingDetailsQueryVos);

                            BigDecimal noriginalcurtaxprice = null;//含税单价
                            try {
                                noriginalcurtaxprice = new BigDecimal(afterSalesOrder.getTotalAmount()).divide(new BigDecimal(stockinB.getReceivedQty()), 20, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP);
                            } catch (Exception e) {
                                logger.error("含税单价金额计算失败！", e);
                                Assert.state(false, "含税单价金额计算失败 原因：{}", e.getMessage());
                            }

                            Boolean isblargessflag = false;
                            if (noriginalcurtaxprice == null) {
                                isblargessflag = true;
                            }

                            SalesInvoiceBodyDto salesInvoiceBodyDto = new SalesInvoiceBodyDto();
                            salesInvoiceBodyDto.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());
                            salesInvoiceBodyDto.setCupreceipttype("4C");
                            salesInvoiceBodyDto.setCupsourcebillcode(soSaleEntity.getVreceiptcode());
                            salesInvoiceBodyDto.setNnumber("-" + stockinB.getReceivedQty());
                            salesInvoiceBodyDto.setNoriginalcurtaxprice(noriginalcurtaxprice.stripTrailingZeros().toPlainString());//含税单价
                            salesInvoiceBodyDto.setNtaxrate(new BigDecimal(bdTaxitemsEntity1.getTaxratio()).stripTrailingZeros().toPlainString());//税率
                            salesInvoiceBodyDto.setBlargessflag(isblargessflag);
                            salesInvoiceBodyDto.setCoriginalbillcode(soSaleEntity.getVreceiptcode());//源头单据号
                            salesInvoiceBodyDto.setCsourcebillbodyid(sourceDocumentsV2.getCorderBid());//源头单据明细行主键 (数据字典上是来源单据明细行主键，实际上是源头)
                            salesInvoiceBodyDto.setCsourcebillid(soSaleEntity.getCsaleid());//源头单据主表主键（数据字典上是来源单据主表主键，实际上是源头）
                            salesInvoiceBodyDto.setCupsourcebillbodyid(sourceDocuments.getCgeneralbid());//上层来源明细行主键
                            salesInvoiceBodyDto.setCupsourcebillcode(icGeneralHEntity.getVbillcode());//直接来源单据号
                            salesInvoiceBodyDto.setCupsourcebillid(icGeneralHEntity.getCgeneralhid());//来源主表主键
                            salesInvoiceBodyDtoList.add(salesInvoiceBodyDto);
                        }
                        SalesInvoiceDto salesInvoiceDto = new SalesInvoiceDto();
                        salesInvoiceDto.setParentvo(salesInvoiceHeadDto);
                        salesInvoiceDto.setChildrenvo(salesInvoiceBodyDtoList);

                        List<SalesInvoiceDto> salesInvoiceDtoList = new ArrayList<>();
                        salesInvoiceDtoList.add(salesInvoiceDto);

                        Map<String, List<SalesInvoiceDto>> stringListMap = new HashMap<>();
                        stringListMap.put("billvos", salesInvoiceDtoList);

                        //推送到U8C生成销售发票
                        Boolean aBoolean = checkTobSalesInvoice(header.getId(), header.getCode());
                        if (!aBoolean) {
                            logger.error("经过SQL查询判断，在U8C红字销售发票中不存在OFS入库单号为：{} OFS入库主键为：{}的单据，将调用U8C接口执行推送！", header.getCode(), header.getId());
                            SaleinvoiceDto saleinvoiceDto = sendU8CTOCSoSaleinvoiceB(JSON.toJSONString(stringListMap));
                            String vreceiptcode = null;
                            String csaleid = null;
                            String pk_corp = null;
                            if (saleinvoiceDto != null && saleinvoiceDto.getParentvo() != null && saleinvoiceDto.getChildrenvo() != null) {
                                SaleinvoiceHeadDto parentvo = saleinvoiceDto.getParentvo();
                                List<SaleinvoiceBodyDto> childrenvo = saleinvoiceDto.getChildrenvo();
                                vreceiptcode = parentvo.getVreceiptcode();
                                csaleid = parentvo.getCsaleid();
                                pk_corp = parentvo.getPk_corp();
                            }
                            logger.info("TOB销售发票(红字)生成成功 编码：{} 主键：{} 发票公司：{}", vreceiptcode, csaleid, pk_corp);
                            //记录成功
                            updateSuccessOrFail2(details, "Y", "success", vreceiptcode, csaleid);
                        } else {
                            logger.error("经过SQL查询判断，在U8C红字销售发票中已经存在OFS入库单号为：{} OFS入库主键为：{}的单据，为了避免造成单据重复，不推送到U8C！", header.getCode(), header.getId());
                        }
                    } catch (Exception e) {
                        logger.error("TOB售后到账完成推送U8C抛出异常", e);
                        // 记录失败
                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        updateSuccessOrFail2(details, "N", message, null, null);
                    }
                }
            } catch (Exception e) {
                logger.error("TOB外层转换逻辑抛出异常", e);
            }
        }
    }

    /**
     * 2024年8月28日 17:17:33
     * 生成业务日期，以交易成功时间作为业务日期
     *
     * @author liuyang
     */
    private String createSuccessFulTradeDate(OrderToBHeaderDto orderOutTobHeaderDto) {
        if (orderOutTobHeaderDto != null && orderOutTobHeaderDto.getHeader() != null && orderOutTobHeaderDto.getHeader().getRefundedAt() != null) {
            StockinOrderSearchResponse.StockinOrder.StockinH header = orderOutTobHeaderDto.getHeader();
            String refundedAt = header.getRefundedAt();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(refundedAt);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("refundedAt业务日期生成失败", e);
                Assert.state(false, "refundedAt业务日期生成失败不能为空");
            }
            return businessFormat;
        } else {
            logger.error("生成出库日期失败，或者refundedAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            Assert.state(false, "生成出库日期失败，或者refundedAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            return null;
        }
    }

    /**
     * 2024年8月30日 11:29:24
     * 推送U8C销售发票
     *
     * @author liuyang
     */
    public SaleinvoiceDto sendU8CTOCSoSaleinvoiceB(String param) throws Exception {
        long startLong = System.currentTimeMillis();
        logger.info("TOB销售发票推送开始，推送参数：" + param + ",U8C_URL:" + OverallConstant.getOverAllValue("u8c_url"));
        String apiCode = "8000370057";
        String result = HttpRequest.post(OverallConstant.getOverAllValue("u8c_url")).header("appId", OverallConstant.getOverAllValue("appId"))//头信息，多个头信息多次调用此方法即可
                .header("usercode", OverallConstant.getOverAllValue("u8cApiUsercodePK")).header("password", OverallConstant.getOverAllValue("u8cApiPasswordPK")).header("system", OverallConstant.getOverAllValue("u8cApiSystemPK")).header("trantype", OverallConstant.getOverAllValue("u8cApiTrantypePK")).header("apiCode", apiCode)//头信息，多个头信息多次调用此方法即可
                .header("publicKey", OverallConstant.getOverAllValue("publicKey"))//头信息，多个头信息多次调用此方法即可
                .header("secretKey", OverallConstant.getOverAllValue("secretKey"))//头信息，多个头信息多次调用此方法即可
                .body(param)//表单内容
                .timeout(600000)//超时，毫秒
                .execute().body();
        //2024年8月29日 17:56:50 如果http请求超时，则会抛给上层方法，上层方法会完成异常的捕捉
        logger.info("TOB销售发票推送结束，返回参数：" + result);
        long endLong = System.currentTimeMillis();
        logger.info("TOB销售发票接口请求耗时：" + (endLong - startLong));

        JSONObject jsonObject = JSON.parseObject(result);
        result = String.valueOf(jsonObject.get("attribute"));

        boolean isSuccess = false;
        SaleinvoiceDto soSaleResultRootDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                soSaleResultRootDto = resultDataHandleV2(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "TOB业务O出库单推送U8C销售发票失败 接口返回结果：{}", result);
        }
        return soSaleResultRootDto;
    }

    /**
     * 通过售后入库单明细行，查找售后订单明细行
     *
     * @param stockinB       售后订单明细行
     * @param ofsRertunOrder OFS售后订单
     * @author liuyang
     */
    private RerturnGoodsOrderSearchDetails findAfterSalesOrder(StockinOrderSearchResponse.StockinOrder.StockinB stockinB, RerturnGoodsOrderSearchData ofsRertunOrder) {
        Assert.notNull(stockinB, "stockinB不能为空！");
        Assert.notNull(ofsRertunOrder, "saleOrderMessageDto不能为空！");

        Assert.notNull(ofsRertunOrder.getHeader(), "售后订表头不能为空！");
        Assert.notNull(ofsRertunOrder.getDetails(), "售后订单表头");
        RerturnGoodsOrderSearchHeader header = ofsRertunOrder.getHeader();
        List<RerturnGoodsOrderSearchDetails> details1 = ofsRertunOrder.getDetails();
        if (details1 == null || details1.size() == 0) {
            Assert.state(false, "售后订单明细行不能为空，size不能为0！");
        }
        for (int i = 0; i < details1.size(); i++) {
            RerturnGoodsOrderSearchDetails rerturnGoodsOrderSearchDetails = details1.get(i);
            if (rerturnGoodsOrderSearchDetails.getId().equals(stockinB.getRefOrderDetailId())) {
                return rerturnGoodsOrderSearchDetails;
            }
        }
        Assert.state(false, "通过售后入库单号({})无法匹配到售后订单", stockinB.getId());
        return null;
    }

    /**
     * 查找来源单据,销售发票的来源单据为销售出库单，生成TOB销售订单时，明细行传O的明细行主键，查找逻辑
     * O明细行主键 -> 定位到U8C销售订单明细行 -> 销售出库单明细行
     *
     * @param header                                  O表头明细行
     * @param stockinB                                O明细行
     * @param soSaleorderBEntityList                  U8C销售订单明细集合
     * @param icGeneralBEntityList                    U8C销售出库单明细集合
     * @param extIntegrationTaskLivingDetailsQueryVos U8C销售订单执行情况明细表
     * @author liuyang
     */
    private IcGeneralBEntity findSourceDocuments(StockinOrderSearchResponse.StockinOrder.StockinH header, StockinOrderSearchResponse.StockinOrder.StockinB stockinB, List<SoSaleorderBEntity> soSaleorderBEntityList, List<IcGeneralBEntity> icGeneralBEntityList, List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos) {
        Assert.notNull(header, "header不能为空");
        Assert.notNull(stockinB, "detailsDto不能为空");
        Assert.notNull(soSaleorderBEntityList, "soSaleorderBEntityList不能为空");
        Assert.notNull(icGeneralBEntityList, "icGeneralBEntityList不能为空");
        Assert.notNull(extIntegrationTaskLivingDetailsQueryVos, "extIntegrationTaskLivingDetailsQueryVos不能为空");

        ExtIntegrationTaskLivingDetailsQueryVo targetExtIntegrationTaskLivingDetailsQueryVo = null;
        for (int i = 0; i < extIntegrationTaskLivingDetailsQueryVos.size(); i++) {
            ExtIntegrationTaskLivingDetailsQueryVo extIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVos.get(i);
            if (extIntegrationTaskLivingDetailsQueryVo.getVdef20().equals(stockinB.getId())) {
                targetExtIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVo;
            }
        }
        Assert.notNull(targetExtIntegrationTaskLivingDetailsQueryVo, "无法匹配到销售订单执行情况明细行，O明细行主键", stockinB.getId());

        SoSaleorderBEntity targetSoSaleorderBEntity = null;
        for (int i = 0; i < soSaleorderBEntityList.size(); i++) {
            SoSaleorderBEntity soSaleorderBEntity = soSaleorderBEntityList.get(i);
            if (targetExtIntegrationTaskLivingDetailsQueryVo.getCsale_bid().equals(soSaleorderBEntity.getCorderBid())) {
                targetSoSaleorderBEntity = soSaleorderBEntity;
            }
        }
        Assert.notNull(targetSoSaleorderBEntity, "根据O出库单明细主键:{}，无法匹配到U8C销售订单明细行");

        for (int i = 0; i < icGeneralBEntityList.size(); i++) {
            IcGeneralBEntity icGeneralBEntity = icGeneralBEntityList.get(i);
            if (icGeneralBEntity.getCsourcebillbid().equals(targetSoSaleorderBEntity.getCorderBid())) {
                return icGeneralBEntity;
            }
        }
        Assert.state(false, "根据销售订单明细行主键：{} 无法匹配到销售出库单明细行", targetSoSaleorderBEntity.getCorderBid());
        return null;
    }

    /**
     * 查找销售订单明细行
     *
     * @param header                 O表头明细行
     * @param stockinB               O明细行
     * @param soSaleorderBEntityList U8C销售订单明细集合
     * @author liuyang
     */
    private SoSaleorderBEntity findSourceDocumentsV2(StockinOrderSearchResponse.StockinOrder.StockinH header, StockinOrderSearchResponse.StockinOrder.StockinB stockinB, List<SoSaleorderBEntity> soSaleorderBEntityList, List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos) {
        Assert.notNull(header, "header不能为空");
        Assert.notNull(stockinB, "stockinB不能为空");
        Assert.notNull(soSaleorderBEntityList, "soSaleorderBEntityList不能为空");
        Assert.notNull(extIntegrationTaskLivingDetailsQueryVos, "extIntegrationTaskLivingDetailsQueryVos不能为空!");

        ExtIntegrationTaskLivingDetailsQueryVo targetExtIntegrationTaskLivingDetailsQueryVo = null;
        for (int i = 0; i < extIntegrationTaskLivingDetailsQueryVos.size(); i++) {
            ExtIntegrationTaskLivingDetailsQueryVo extIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVos.get(i);
            if (extIntegrationTaskLivingDetailsQueryVo.getVdef20().equals(stockinB.getId())) {
                targetExtIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVo;
            }
        }
        Assert.notNull(targetExtIntegrationTaskLivingDetailsQueryVo, "无法匹配到销售订单执行情况明细行，O明细行主键", stockinB.getId());

        SoSaleorderBEntity targetSoSaleorderBEntity = null;
        for (int i = 0; i < soSaleorderBEntityList.size(); i++) {
            SoSaleorderBEntity soSaleorderBEntity = soSaleorderBEntityList.get(i);
            if (targetExtIntegrationTaskLivingDetailsQueryVo.getCsale_bid().equals(soSaleorderBEntity.getCorderBid())) {
                targetSoSaleorderBEntity = soSaleorderBEntity;
            }
        }
        Assert.notNull(targetSoSaleorderBEntity, "根据O出库单明细主键:{}，无法匹配到U8C销售订单明细行");
        return targetSoSaleorderBEntity;
    }

    private static final Object checkTobOrderLock = new Object();

    /**
     * 验证TOB销售订单，是否已经生成，如果已经生成，则返回true,否则返回false
     *
     * @param ofsId   ofs主键
     * @param ofsCode ofs编码
     * @author liuyang
     */
    private Boolean checkTobOrder(String ofsId, String ofsCode) throws Exception {
        Assert.notNull(ofsId, "ofsId不能为空");
        Assert.notNull(ofsCode, "ofsCode不能为空");
        synchronized (checkTobOrderLock) {
            SoSaleEntity soSaleEntity = new SoSaleEntity();
            soSaleEntity.setDr(0L);
            soSaleEntity.setDataSourceCode("lets_u8c");
            soSaleEntity.setVdef19(ofsCode);
            soSaleEntity.setVdef20(ofsId);
            soSaleEntity.setBretinvflag("Y");//仅查询销售订单
            List<SoSaleEntity> soSaleEntityList = iSoSaleDao.query(soSaleEntity);
            if (soSaleEntityList.size() > 0) {
                SoSaleEntity soSaleEntity1 = soSaleEntityList.get(0);
                logger.error("OFS销售出库单主键：{} OFS销售出库单编码：{} 该单据在U8C已经存在U8C销售订单，并且销售订单编码为：{} 对应的公司为：{}", ofsId, ofsCode, soSaleEntity1.getVreceiptcode(), soSaleEntity1.getPkCorp());
                return true;
            }
            return false;
        }
    }

    private static final Object checkTobSalesInvoiceLock = new Object();

    /**
     * 验证TOB销售发票，是否已经生成，仅验证负数的发票是否存在！
     *
     * @param ofsId   ofs销售出库单主键
     * @param ofsCode ofs销售出库单编码
     * @author liuyang
     */
    private Boolean checkTobSalesInvoice(String ofsId, String ofsCode) throws Exception {
        Assert.notNull(ofsId, "ofsId不能为空");
        Assert.notNull(ofsCode, "ofsCode不能为空");
        synchronized (checkTobSalesInvoiceLock) {
            SoSaleinvoiceEntity soSaleinvoiceEntity = new SoSaleinvoiceEntity();
            soSaleinvoiceEntity.setDr("0");
            soSaleinvoiceEntity.setVdef19(ofsCode);
            soSaleinvoiceEntity.setVdef20(ofsId);
            soSaleinvoiceEntity.setDataSourceCode("lets_u8c");
            soSaleinvoiceEntity.setVnote(VNOTETYPE);
            List<SoSaleinvoiceEntity> soSaleinvoiceEntityList = iSoSaleinvoiceDao.query(soSaleinvoiceEntity);
            if (soSaleinvoiceEntityList != null && soSaleinvoiceEntityList.size() > 0) {
                SoSaleinvoiceEntity soSaleinvoiceEntity1 = soSaleinvoiceEntityList.get(0);
                logger.error("OFS销售出库单主键：{} OFS销售出库单编码：{} 该单据在U8C已经存在U8C销售发票，并且销售发票编码为：{} 对应的公司为：{}", ofsId, ofsCode, soSaleinvoiceEntity1.getVreceiptcode(), soSaleinvoiceEntity1.getPkCorp());
                return true;
            }
        }
        return false;
    }

    /**
     * 计算时间间隔
     *
     * @author liuyang
     */
    public String computingTime(String param) {
        if (param != null && !"".equals(param)) {
            String[] split = param.split("/");
            if (!(split.length == 2)) {
                Assert.state(false, "传递的日期格式不完整 格式参考：2024-04-01/2024-04-30");
            }

            LocalDate startDate = LocalDate.parse(split[0]);
            LocalDate endDate = LocalDate.parse(split[1]);

            List<String> stringArrayList = new ArrayList<>();
            List<String> dateRange = getDateRange(startDate, endDate);
            if (dateRange != null && dateRange.size() > 0) {
                for (int i = 0; i < dateRange.size(); i++) {
                    String dateStr = dateRange.get(i);
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(dateStr);
                    stringBuffer.append(" 00:00:00");
                    stringBuffer.append(",");
                    stringBuffer.append(dateStr);
                    stringBuffer.append(" 23:59:59");
                    stringArrayList.add(stringBuffer.toString());
                }
            }
            String collectDateStr = stringArrayList.stream().collect(Collectors.joining("*"));
            logger.info("类型：time_frame 生成的日期范围：" + collectDateStr);
            return collectDateStr;
        }
        return null;
    }

    /**
     * 计算日期范围
     *
     * @author liuyang
     */
    private List<String> getDateRange(LocalDate startDate, LocalDate endDate) {
        List<String> dateRange = new ArrayList<>();
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dateRange.add(currentDate.format(DateTimeFormatter.ISO_DATE));
            currentDate = currentDate.plusDays(1);
        }
        return dateRange;
    }

    /**
     * 分割日期之后，再进行推送
     *
     * @param param     日期参数
     * @param sceneType 场景类型 TOB库存、TOB确认收入
     * @author liuyang
     */
    public void splitDateAndPush(String param, String sceneType) throws Exception {
        try {
            Assert.notNull(param, "param不能为空!");
            Assert.state(!"".equals(param), "param不能为空！");

            Assert.notNull(sceneType, "sceneType不能为空！");
            Assert.state(!"".equals(sceneType), "sceneType不能为空！");

            if (param.contains("*")) {
                String[] params = param.split("\\*");
                if (params.length > 0) {
                    for (int i = 0; i < params.length; i++) {
                        String indexStr = params[i];
                        String[] split = indexStr.split(",");
                        logger.info("splitDateAndPush方法正在执行主要的逻辑 开始时间：{} 结束时间：{}", split[0], split[1]);
                        if (sceneType.equals(STOCK)) {
                            startImplementByStockTime(split[0], split[1]);
                        } else if (sceneType.equals(TRAN)) {
                            startImplementByTradeTime(split[0], split[1]);
                        }
                    }
                }
            } else {
                String[] split = param.split(",");
                logger.info("splitDateAndPush方法正在执行主要的逻辑 开始时间：{} 结束时间：{}", split[0], split[1]);
                if (sceneType.equals(STOCK)) {
                    startImplementByStockTime(split[0], split[1]);
                } else if (sceneType.equals(TRAN)) {
                    startImplementByTradeTime(split[0], split[1]);
                }
            }
        } catch (Exception e) {
            logger.error("记录splitDateAndPush方法抛出的异常", e);
        }
    }

    /**
     * 处理TOC-库存同步的成功、失败错误逻辑
     *
     * @author liuyang
     */
    private void updateSuccessOrFail1(List<StockinOrderSearchResponse.StockinOrder.StockinB> sonDetailsDtoList, String newstate, String newTransmitInfo, String newsystemnumber, String newsystemprimary) {
        if (newTransmitInfo != null && !"".equals(newTransmitInfo.trim()) && newTransmitInfo.length() >= 400) {
            newTransmitInfo = newTransmitInfo.substring(0, 400);
        }

        String finalNewTransmitInfo = newTransmitInfo;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String successY = "Y";
                    if (sonDetailsDtoList != null && sonDetailsDtoList.size() > 0) {
                        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityArrayList = new ArrayList<>();
                        for (int i = 0; i < sonDetailsDtoList.size(); i++) {
                            StockinOrderSearchResponse.StockinOrder.StockinB stockinB = sonDetailsDtoList.get(i);

                            TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = new TocofsReturngoodsDetailedEntity();
                            tocofsReturngoodsDetailedEntity.setId(stockinB.getId());
                            tocofsReturngoodsDetailedEntity.setNewpushdate(getNewDateStr());
                            tocofsReturngoodsDetailedEntity.setNewtransmitinfo(finalNewTransmitInfo);
                            tocofsReturngoodsDetailedEntity.setNewstate(newstate);
                            if (successY.equals(newstate)) {
                                tocofsReturngoodsDetailedEntity.setNewsystemnumber(newsystemnumber);
                                tocofsReturngoodsDetailedEntity.setNewsystemprimary(newsystemprimary);
                            }
                            tocofsReturngoodsDetailedEntityArrayList.add(tocofsReturngoodsDetailedEntity);
                        }

                        //以50行为一个批次，推送到Mysql
                        if (tocofsReturngoodsDetailedEntityArrayList.size() > 0) {
                            List<List<TocofsReturngoodsDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsReturngoodsDetailedEntityArrayList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = splitListByCount.get(i);
                                iTocofsReturngoodsDetailedDao.entityInsertOrUpdateBatchByTobRerturnStock(tocofsReturngoodsDetailedEntities);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("TOC库存同步日志，抛出异常", e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("updateSuccessOrFail1方法现场抛出异常", e);
        }
    }

    /**
     * 生成当前日期
     *
     * @author liuyang
     */
    private String getNewDateStr() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }

    /**
     * 处理TOC-库存同步的成功、失败错误逻辑
     *
     * @author liuyang
     */
    private void updateSuccessOrFail2(List<StockinOrderSearchResponse.StockinOrder.StockinB> sonDetailsDtoList, String newstate, String newTransmitInfo, String newsystemnumber, String newsystemprimary) {
        if (newTransmitInfo != null && !"".equals(newTransmitInfo.trim()) && newTransmitInfo.length() >= 400) {
            newTransmitInfo = newTransmitInfo.substring(0, 400);
        }

        String finalNewTransmitInfo = newTransmitInfo;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String successY = "Y";
                    if (sonDetailsDtoList != null && sonDetailsDtoList.size() > 0) {
                        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityArrayList = new ArrayList<>();
                        for (int i = 0; i < sonDetailsDtoList.size(); i++) {
                            StockinOrderSearchResponse.StockinOrder.StockinB stockinB = sonDetailsDtoList.get(i);

                            TocofsReturngoodsDetailedEntity tocofsReturngoodsDetailedEntity = new TocofsReturngoodsDetailedEntity();
                            tocofsReturngoodsDetailedEntity.setId(stockinB.getId());
                            tocofsReturngoodsDetailedEntity.setNewpushdate2(getNewDateStr());
                            tocofsReturngoodsDetailedEntity.setNewtransmitinfo2(finalNewTransmitInfo);
                            tocofsReturngoodsDetailedEntity.setNewstate2(newstate);
                            if (successY.equals(newstate)) {
                                tocofsReturngoodsDetailedEntity.setNewsystemnumber2(newsystemnumber);
                                tocofsReturngoodsDetailedEntity.setNewsystemprimary2(newsystemprimary);
                            }
                            tocofsReturngoodsDetailedEntityArrayList.add(tocofsReturngoodsDetailedEntity);
                        }

                        //以50行为一个批次，推送到Mysql
                        if (tocofsReturngoodsDetailedEntityArrayList.size() > 0) {
                            List<List<TocofsReturngoodsDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsReturngoodsDetailedEntityArrayList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntities = splitListByCount.get(i);
                                iTocofsReturngoodsDetailedDao.entityInsertOrUpdateBatchByTobRerturnTran(tocofsReturngoodsDetailedEntities);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("TOC库存同步日志，抛出异常", e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("updateSuccessOrFail2方法现场抛出异常", e);
        }
    }

    /**
     * 批量修改成功、或者失败，适合档案查询的部分
     *
     * @author liuyang
     */
    private void updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryStock(List<ErrorHeaderDetailsDtoDtoV2> errorHeaderDetailsDtoDtoList) throws Exception {
        Assert.notNull(errorHeaderDetailsDtoDtoList, "errorHeaderDetailsDtoDtoList不能为空！");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (errorHeaderDetailsDtoDtoList != null && errorHeaderDetailsDtoDtoList.size() > 0) {
                        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < errorHeaderDetailsDtoDtoList.size(); i++) {
                            ErrorHeaderDetailsDtoDtoV2 errorHeaderDetailsDtoDtoV2 = errorHeaderDetailsDtoDtoList.get(i);
                            StockinOrderSearchResponse.StockinOrder.StockinH header = errorHeaderDetailsDtoDtoV2.getHeader();
                            List<StockinOrderSearchResponse.StockinOrder.StockinB> details = errorHeaderDetailsDtoDtoV2.getDetails();

                            String newstate = errorHeaderDetailsDtoDtoV2.getNewstate();
                            String newPushDate = errorHeaderDetailsDtoDtoV2.getNewPushDate();
                            String newTransmitInfo = errorHeaderDetailsDtoDtoV2.getNewTransmitInfo();

                            //如果报错内容太长了，则仅保留500个长度
                            if (newTransmitInfo != null && !"".equals(newTransmitInfo.trim()) && newTransmitInfo.length() >= 400) {
                                newTransmitInfo = newTransmitInfo.substring(0, 400);
                            }

                            for (int j = 0; j < details.size(); j++) {
                                StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);

                                TocofsReturngoodsDetailedEntity tocofsSaleoutDetailedEntity = new TocofsReturngoodsDetailedEntity();
                                tocofsSaleoutDetailedEntity.setId(stockinB.getId());
                                tocofsSaleoutDetailedEntity.setNewpushdate(newPushDate);
                                tocofsSaleoutDetailedEntity.setNewtransmitinfo(newTransmitInfo);
                                tocofsSaleoutDetailedEntity.setNewstate(newstate);
                                tocofsSaleoutDetailedEntity.setNewsystemnumber(null);
                                tocofsSaleoutDetailedEntity.setNewsystemprimary(null);
                                tocofsReturngoodsDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                            }
                        }

                        //以50行为一个批次更新状态
                        if (tocofsReturngoodsDetailedEntityList.size() > 0) {
                            List<List<TocofsReturngoodsDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsReturngoodsDetailedEntityList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList1 = splitListByCount.get(i);
                                iTocofsReturngoodsDetailedDao.entityInsertOrUpdateBatchByTobRerturnStockV2(tocofsReturngoodsDetailedEntityList1);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("TOB填充出库明细日志抛出异常", e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiry方法现场抛出异常", e);
        }
    }


    /**
     * 批量修改成功、或者失败，适合档案查询的部分
     *
     * @author liuyang
     */
    private void updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryTran(List<ErrorHeaderDetailsDtoDtoV2> errorHeaderDetailsDtoDtoList) {
        Assert.notNull(errorHeaderDetailsDtoDtoList, "errorHeaderDetailsDtoDtoList不能为空！");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (errorHeaderDetailsDtoDtoList != null && errorHeaderDetailsDtoDtoList.size() > 0) {
                        List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < errorHeaderDetailsDtoDtoList.size(); i++) {
                            ErrorHeaderDetailsDtoDtoV2 errorHeaderDetailsDtoDtoV2 = errorHeaderDetailsDtoDtoList.get(i);
                            StockinOrderSearchResponse.StockinOrder.StockinH header = errorHeaderDetailsDtoDtoV2.getHeader();
                            List<StockinOrderSearchResponse.StockinOrder.StockinB> details = errorHeaderDetailsDtoDtoV2.getDetails();

                            String newstate = errorHeaderDetailsDtoDtoV2.getNewstate2();
                            String newPushDate = errorHeaderDetailsDtoDtoV2.getNewPushDate2();
                            String newTransmitInfo = errorHeaderDetailsDtoDtoV2.getNewTransmitInfo2();

                            //如果报错内容太长了，则仅保留500个长度
                            if (newTransmitInfo != null && !"".equals(newTransmitInfo.trim()) && newTransmitInfo.length() >= 400) {
                                newTransmitInfo = newTransmitInfo.substring(0, 400);
                            }

                            for (int j = 0; j < details.size(); j++) {
                                StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);

                                TocofsReturngoodsDetailedEntity tocofsSaleoutDetailedEntity = new TocofsReturngoodsDetailedEntity();
                                tocofsSaleoutDetailedEntity.setId(stockinB.getId());
                                tocofsSaleoutDetailedEntity.setNewpushdate2(newPushDate);
                                tocofsSaleoutDetailedEntity.setNewtransmitinfo2(newTransmitInfo);
                                tocofsSaleoutDetailedEntity.setNewstate2(newstate);
                                tocofsSaleoutDetailedEntity.setNewsystemnumber2(null);
                                tocofsSaleoutDetailedEntity.setNewsystemprimary2(null);
                                tocofsReturngoodsDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                            }
                        }

                        //以50行为一个批次更新状态
                        if (tocofsReturngoodsDetailedEntityList.size() > 0) {
                            List<List<TocofsReturngoodsDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsReturngoodsDetailedEntityList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsReturngoodsDetailedEntity> tocofsReturngoodsDetailedEntityList1 = splitListByCount.get(i);
                                iTocofsReturngoodsDetailedDao.entityInsertOrUpdateBatchByTobRerturnTranV2(tocofsReturngoodsDetailedEntityList1);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("TOB填充出库明细日志抛出异常", e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiry方法现场抛出异常", e);
        }
    }


}