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.ITocofsSaleoutDao;
import com.hzya.frame.plugin.lets.ofs.dao.ITocofsSaleoutDetailedDao;
import com.hzya.frame.plugin.lets.ofs.entity.TocofsSaleoutDetailedEntity;
import com.hzya.frame.plugin.lets.ofs.entity.TocofsSaleoutEntity;
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.u8cdto.*;
import com.hzya.frame.plugin.lets.util.*;
import com.hzya.frame.split.SplitListByCountUtil;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.DetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDto;
import com.hzya.frame.ttxofs.dto.ofssalesordersearch.SaleOrderMessageDto;
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 com.hzya.frame.plugin.lets.plugin.sales.SoSaleReturnPluginInitializerToB TOB退货
 * @since 2024年8月12日 15:03:51
 */
public class SoSaleOutPluginInitializerToB extends PluginBaseEntity {

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

    @Autowired
    private IBdCorpDao iBdCorpDao;

    @Autowired
    private IBdInvbasdocDao iBdInvbasdocDao;

    @Autowired
    private ISoSaleDao iSoSaleDao;

    @Autowired
    private ISoSaleorderBDao iSoSaleorderBDao;

    @Autowired
    private OffsetTimeTime offsetTimeTime;

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

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

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

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

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

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

    private static final String STOCK = "stock";

    private static final String TRAN = "tran";

    private static final String PROD_FILED = "prod";

    @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"))) {
                //按单号
                Assert.notNull(sceneType, "sceneType参数不能为空");
                Assert.notNull(!"".equals(sceneType), "sceneType参数不能为空");
                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());
                    startImplementByTranTime(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 ITocofsSaleoutDao iTocofsSaleoutDao;

    @Autowired
    private ITocofsSaleoutDetailedDao iTocofsSaleoutDetailedDao;

    @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 AfterSalesOrderUtil afterSalesOrderUtil;

    @Autowired
    private ShopTobOrToCUtil shopTobOrToCUtil;

    @Autowired
    private OfsStandardUtil ofsStandardUtil;

    @Autowired
    private RdclUtil rdclUtil;

    @Autowired
    private IIcGeneralHDao iIcGeneralHDao;

    @Autowired
    private IIcGeneralBDao iIcGeneralBDao;

    @Autowired
    private ISoSaleinvoiceDao iSoSaleinvoiceDao;

    private static final String VNOTETYPE = "SALE";

    /**
     * 库存同步，按指定时间拉取
     *
     * @author liuyang
     */
    public void startImplementByStockTime(String startTime, String endTime) {
        long startMillis = System.currentTimeMillis();
        String threadNameStr = StrUtil.format("OFS销售出库(TOB)同步U8C销售订单开始 同步日期：{} 汇总维度：{}", startTime, endTime);
        logger.info(threadNameStr);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Assert.notNull(startTime, "出库开始时间不能为空");
                    Assert.notNull(endTime, "出库结束时间不能为空");

//                    CalculateDateVo calculateDateVo = DateStrUtil.calculateCalculateEntireDayPeriod(dateStr);
                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");

                    List<HeaderDetailsDto> headerDetailsDtoList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setShipAt_start(startTime);
                    queryOfsSoSaleOutVo.setShipAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setInternalInstructionType("SALES");
//                    queryOfsSoSaleOutVo.setCompanyCode("SHLZ");
                    queryOfsSoSaleOutVo.setStatus(900L);
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
//                    queryOfsSoSaleOutVo.setCode("LETS-SH2024010200000004");
                    ofsStandardUtil.queryOfsSaleOrder(queryOfsSoSaleOutVo, headerDetailsDtoList, 1L, "ofs.shipment.search");
                    logger.info("数据返回行数：{}", headerDetailsDtoList.size());
                    if (headerDetailsDtoList.size() > 0) {
                        getSetStock(headerDetailsDtoList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplementByStockTime方法抛出异常", e);
                }
            }
        }, threadNameStr);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endMillis = System.currentTimeMillis();
        String threadNameEnd = StrUtil.format("OFS销售出库(TOB)同步U8C销售订单结束 同步日期：{} 汇总维度：{} 耗时：{}", startTime, endTime, (endMillis - startMillis));
        logger.info(threadNameEnd);
    }

    /**
     * 交易成功同步，按指定时间拉取
     *
     * @author liuyang
     */
    public void startImplementByTranTime(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, "交易开始时间不能为空");
                    Assert.notNull(endTime, "交易结束时间不能为空");

                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");

                    List<HeaderDetailsDto> headerDetailsDtoList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//                    queryOfsSoSaleOutVo.setShipAt_start(startTime);
//                    queryOfsSoSaleOutVo.setShipAt_end(endTime);
                    queryOfsSoSaleOutVo.setTradeSuccessAt_start(startTime);
                    queryOfsSoSaleOutVo.setTradeSuccessAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setInternalInstructionType("SALES");
                    queryOfsSoSaleOutVo.setSourceOrderStatus("TRADE_FINISHED");//交易成功状态
//                    queryOfsSoSaleOutVo.setStatus(900L);
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
                    ofsStandardUtil.queryOfsSaleOrder(queryOfsSoSaleOutVo, headerDetailsDtoList, 1L, "ofs.shipment.search");
                    logger.info("数据返回行数：{}", headerDetailsDtoList.size());
                    if (headerDetailsDtoList.size() > 0) {
                        getSetStockTran(headerDetailsDtoList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplementByTranTime方法抛出异常", 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, "出库单单不能为空");
                    String tobShop = shopTobOrToCUtil.getCommaShop("TOB");
                    logger.info("TOB-OFS店铺编码：{}", tobShop);

                    List<HeaderDetailsDto> headerDetailsDtoList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setInternalInstructionType("SALES");
                    //2024年8月30日 10:41:55 如果按编码查询，是否应该考虑仅查询已发货的数据？
                    queryOfsSoSaleOutVo.setStatus(900L);
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setStoreCode(tobShop);
                    queryOfsSoSaleOutVo.setCode(code);
                    ofsStandardUtil.queryOfsSaleOrder(queryOfsSoSaleOutVo, headerDetailsDtoList, 1L, "ofs.shipment.search");
                    logger.info("根据单据号查询：数据返回行数：{}", headerDetailsDtoList.size());
                    if (headerDetailsDtoList.size() > 0) {
                        if (sceneType.equals("stock")) {
                            getSetStock(headerDetailsDtoList);
                        } else if (sceneType.equals("tran")) {
                            getSetStockTran(headerDetailsDtoList);
                        }
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplementByCode方法抛出异常", 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);
    }

    /**
     * 出库完成
     */
    private void getSetStock(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        //保存到mysql
        batchInsert(headerDetailsDtoList);
        //过滤成功的数据
        List<HeaderDetailsDto> headerDetailsDtos = filterDataStock(headerDetailsDtoList);
        //执行推送主逻辑
        implementStock(headerDetailsDtos);
    }

    /**
     * 交易成功
     */
    private void getSetStockTran(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        //保存到mysql
        batchInsert(headerDetailsDtoList);
        //过滤成功的数据
        List<HeaderDetailsDto> headerDetailsDtos = filterDataTran(headerDetailsDtoList);
        //执行主推送逻辑
        implementSuccessfulTrade(headerDetailsDtos);
    }

    /**
     * 库存同步，过滤掉成功的数据
     *
     * @author liuyang
     */
    private List<HeaderDetailsDto> filterDataStock(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        //        List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> headerDetailsDtoList1 = new ArrayList<>();
        List<TocofsSaleoutDetailedEntity> allTocofsSaleoutDetailedEntityList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            List<List<HeaderDetailsDto>> splitListByCount = SplitListByCountUtil.splitListByCount(headerDetailsDtoList, 100);
            for (int i = 0; i < splitListByCount.size(); i++) {
                List<HeaderDetailsDto> headerDetailsDtoList2 = splitListByCount.get(i);
                String idStr = commaConcatenatedPrimaryKeyStock(headerDetailsDtoList2);
                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = queryStockTocOutLog(idStr);
                allTocofsSaleoutDetailedEntityList.addAll(tocofsSaleoutDetailedEntityList);
            }
        }
        return filterDataRowsAsPushOrFailedStock(allTocofsSaleoutDetailedEntityList, headerDetailsDtoList);
    }

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

                    idStr.append(detailsDto.getId());
                    idStr.append(",");
                }
            }
        }
        if (idStr.length() > 0) {
            return idStr.substring(0, idStr.length() - 1);
        }
        return null;
    }

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

    /**
     * 筛选出未推送、或者失败的数据行
     *
     * @param allTocofsSaleoutDetailedEntityList 日志行状态
     * @param headerDetailsDtoList               返回结果
     * @author liuyang
     */
    private List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> filterDataRowsAsPushOrFailedStock(List<TocofsSaleoutDetailedEntity> allTocofsSaleoutDetailedEntityList, List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> targetHeaderDetailsDtoList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            //字段Y(成功)或者为H(待处理)可以视为成功，完成了小段业务闭环的数据行
            String succeseeY = "Y";
            String succeseeH = "H";
            for (int i = 0; i < headerDetailsDtoList.size(); i++) {
                HeaderDetailsDto headerDetailsDto = headerDetailsDtoList.get(i);
                HeaderDto header = headerDetailsDto.getHeader();
                List<DetailsDto> details = headerDetailsDto.getDetails();

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

    /**
     * 确认收入，过滤掉成功的数据
     *
     * @author liuyang
     */
    private List<HeaderDetailsDto> filterDataTran(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        List<TocofsSaleoutDetailedEntity> allTocofsSaleoutDetailedEntityList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            List<List<HeaderDetailsDto>> splitListByCount = SplitListByCountUtil.splitListByCount(headerDetailsDtoList, 100);
            for (int i = 0; i < splitListByCount.size(); i++) {
                List<HeaderDetailsDto> headerDetailsDtoList2 = splitListByCount.get(i);
                String idStr = commaConcatenatedPrimaryKeyStock(headerDetailsDtoList2);
                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = queryStockTocOutLog(idStr);
                allTocofsSaleoutDetailedEntityList.addAll(tocofsSaleoutDetailedEntityList);
            }
        }
        return filterDataRowsAsPushOrFailedTran(allTocofsSaleoutDetailedEntityList, headerDetailsDtoList);
    }

    /**
     * 筛选出未推送、或者失败的数据行
     *
     * @param allTocofsSaleoutDetailedEntityList 日志行状态
     * @param headerDetailsDtoList               返回结果
     * @author liuyang
     */
    private List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> filterDataRowsAsPushOrFailedTran(List<TocofsSaleoutDetailedEntity> allTocofsSaleoutDetailedEntityList, List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> targetHeaderDetailsDtoList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            //字段Y(成功)或者为H(待处理)可以视为成功，完成了小段业务闭环的数据行
            String succeseeY = "Y";
            String succeseeH = "H";
            for (int i = 0; i < headerDetailsDtoList.size(); i++) {
                HeaderDetailsDto headerDetailsDto = headerDetailsDtoList.get(i);
                HeaderDto header = headerDetailsDto.getHeader();
                List<DetailsDto> details = headerDetailsDto.getDetails();

                List<DetailsDto> targetDetails = new ArrayList<>();
                for (int j = 0; j < details.size(); j++) {
                    DetailsDto detailsDto = details.get(j);

                    Boolean isSuccess = false;
                    String newstate4 = null;
                    if (allTocofsSaleoutDetailedEntityList != null && allTocofsSaleoutDetailedEntityList.size() > 0) {
                        for (int k = 0; k < allTocofsSaleoutDetailedEntityList.size(); k++) {
                            TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = allTocofsSaleoutDetailedEntityList.get(k);
                            if (tocofsSaleoutDetailedEntity.getId().equals(detailsDto.getId())) {
                                newstate4 = tocofsSaleoutDetailedEntity.getNewstate4();
                                //验证交易成功(红)是否成功、(销售)交易成功(蓝)是否成功 两者如果都成功，则过滤掉，如果其中一个不能成功，则还是需要进行补推！
                                //验证红或蓝单据是否推送成功的代码，在implementTran中实现
                                if ((succeseeY.equals(newstate4) || succeseeH.equals(newstate4))) {
                                    isSuccess = true;
                                }
                            }
                        }
                    }
                    if (!isSuccess) {
                        //拷贝推送状态参数，方便推送是进行判断
                        detailsDto.setNewState4(newstate4);
                        targetDetails.add(detailsDto);
                    }
                }
                if (targetDetails.size() > 0) {
                    //如果明细行中，还存在未推送或者失败的数据，则需要更新明细行
                    headerDetailsDto.setDetails(targetDetails);
                    targetHeaderDetailsDtoList.add(headerDetailsDto);
                }
            }
        }
        return targetHeaderDetailsDtoList;
    }

    /**
     * 保存抓取到的数据到mysql底表，如果底表里已经存在，则会忽略
     *
     * @param headerDetailsDtoList 数据行
     */
    private void batchInsert(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            List<HeaderDto> headerDetailsDtoList1 = new ArrayList<>();
            List<DetailsDto> headerDetailsDtoList2 = new ArrayList<>();

            for (HeaderDetailsDto index : headerDetailsDtoList) {
                HeaderDto header = index.getHeader();// 主表
                List<DetailsDto> details = index.getDetails();//明细表

                for (int i = 0; i < details.size(); i++) {
                    DetailsDto detailsDto = details.get(i);
                    detailsDto.setHeaderDto(header);
                }

                headerDetailsDtoList1.add(header);
                headerDetailsDtoList2.addAll(details);
            }

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

            //插入明细表
            List<List<DetailsDto>> detailsDtoList = SplitListByCountUtil.splitListByCount(headerDetailsDtoList2, 100);
            for (int i = 0; i < detailsDtoList.size(); i++) {
                List<DetailsDto> detailsDtos = detailsDtoList.get(i);
                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntities = copyDetailsDto(detailsDtos);
                if (tocofsSaleoutDetailedEntities.size() > 0) {
                    logger.info("TOBofsSaleoutDetailedEntities：插入底表{}个对象（表体）", tocofsSaleoutDetailedEntities.size());
                    iTocofsSaleoutDetailedDao.entityInsertOrUpdateBatch(tocofsSaleoutDetailedEntities);
                } else {
                    logger.info("TOBofsSaleoutDetailedEntities：没有对象被插入表头底表");
                }
            }
        }
    }

//    public void queryOfsSaleOrder() throws Exception {
//        QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//        queryOfsSoSaleOutVo.setCreated_start("2024-07-05 16:38:00");
//        queryOfsSoSaleOutVo.setCreated_end("2024-07-05 16:40:30");
//        queryOfsSoSaleOutVo.setClientCode("LETS");
////        queryOfsSoSaleOutVo.setInternalInstructionType("SALES");
//        queryOfsSoSaleOutVo.setCompanyCode("SHLZ");
////        queryOfsSoSaleOutVo.setStatus(900L);
//        queryOfsSoSaleOutVo.setPageNo(1L);
//        queryOfsSoSaleOutVo.setPageSize(50L);
//        queryOfsSoSaleOutVo.setCode("LETS-SH2024070500000003");
//
//        InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
//        interfaceParamDto.setApi("ofs.shipment.search");
//        interfaceParamDto.setData(JSON.toJSONString(queryOfsSoSaleOutVo));
//        SaleOutReturnMessageDto saleOutReturnMessageDto = (SaleOutReturnMessageDto) ofsUnifiedService.unified(interfaceParamDto);
//        System.out.println(saleOutReturnMessageDto);
//    }

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

                for (int i = 0; i < orderOutTobHeaderDtos.size(); i++) {
                    OrderOutTobHeaderDto orderOutTobHeaderDto = orderOutTobHeaderDtos.get(i);
                    HeaderDto header = orderOutTobHeaderDto.getHeader();
                    List<DetailsDto> 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 generateBusinessDate = createGenerateBusinessDate(orderOutTobHeaderDto);
                        //店铺
                        BdDefdocEntity shopArchives = orderOutTobHeaderDto.getShopArchives();
                        //收发类别
                        BdRdclEntity bdRdclEntity = orderOutTobHeaderDto.getBdRdclEntity();

                        SaleorderRequestDto saleorderRequestDto = new SaleorderRequestDto();
                        SaleorderRequestParentDto saleorderRequestParentDto = new SaleorderRequestParentDto();
                        saleorderRequestParentDto.setDbilldate(generateBusinessDate);//单据日期
                        saleorderRequestParentDto.setBretinvflag("N");//退货标记
                        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++) {
                            DetailsDto detailsDto = details.get(j);
                            //存货管理档案：取发货公司的存货管理档案
                            BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(detailsDto, bdCalbodyEntity.getPkCorp(), bdCorpEntity.getUnitname());
                            //存货基础档案
                            BdInvbasdocEntity bdInvbasdocEntity = queryStockBasicArchives(bdInvmandocEntity.getPkInvmandoc(), deliverGoodsCorp.getPkCorp());
                            //根据存货基础档案编码，查询当前存货的税率
                            BdTaxitemsEntity bdTaxitemsEntity1 = queryBdTaxitems(bdInvbasdocEntity.getInvcode());

                            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 {
                                noriginalcurtaxprice = new BigDecimal(detailsDto.getTotalPayAmount()).divide(new BigDecimal(detailsDto.getShipQty()), 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(detailsDto.getShipQty())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                noriginalcursummny = noriginalcurtaxprice.multiply(new BigDecimal(detailsDto.getShipQty())).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.setCbodywarehousecode(bdStordocEntity.getStorcode());//发货仓库编码：这个字段不需要给openapi接口，而是提供给下游方法使用
                            saleorderRequestChildrenDto.setCconsigncorpid(deliverGoodsCorp.getPkCorp());//发货公司
                            saleorderRequestChildrenDto.setCcurrencytypeid("00010000000000000001");//币种
                            saleorderRequestChildrenDto.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());//存货id
                            saleorderRequestChildrenDto.setCinventorycode(bdInvbasdocEntity.getInvcode());//存货编码
                            saleorderRequestChildrenDto.setCreceiptcorpid(bdCumandocEntity.getPkCumandoc());//收货单位
                            saleorderRequestChildrenDto.setDconsigndate(generateBusinessDate);//计划发货日期
                            saleorderRequestChildrenDto.setDdeliverdate(generateBusinessDate);//要求收货日期
                            saleorderRequestChildrenDto.setNexchangeotobrate("1.00000000");//折本汇率
                            saleorderRequestChildrenDto.setNitemdiscountrate("100.000000");//单品折扣
                            saleorderRequestChildrenDto.setNnumber(detailsDto.getShipQty());//数量
                            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());//税率
                            //2024年8月30日 10:52:55 抛出异常pk_defxxx长度不够的问题，已经提交给总部
                            //TODO 先不传，抛出长度异常，后续再改
//                            saleorderRequestChildrenDto.setVdef19(header.getCode());//原单单号
                            saleorderRequestChildrenDto.setVdef20(detailsDto.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());
                        } else {
                            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 pk_corp = null;
                            String csaleid = null;
                            //成功
                            if (soSaleResultRootDto != null) {
                                SoSaleResultHeadDto parentvo = soSaleResultRootDto.getParentvo();
                                List<SoSaleResultBodyDto> childrenvo = soSaleResultRootDto.getChildrenvo();

                                vreceiptcode = parentvo.getVreceiptcode();
                                pk_corp = parentvo.getPk_corp();
                                csaleid = parentvo.getCsaleid();
                            }
                            logger.info("TOB销售订单编号：{} 主键：{} 公司：{}", vreceiptcode, csaleid, pk_corp);
                            //记录成功
                            updateSuccessOrFail2(details, "Y", "success", vreceiptcode, csaleid);
                        }
                    } catch (Exception e) {
                        logger.error("推送TOB销售订单失败", e);
                        //记录失败
                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        updateSuccessOrFail2(details, "N", message, null, null);
                    }
                }
            } catch (Exception e) {
                logger.error("TOB业务转换成U8C对象过程中、或者单据推送到U8C出现异常！", e);
                //记录失败
            }
        }
    }

    /**
     * 2024年7月31日 10:34:09
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDate(OrderOutTobHeaderDto orderOutTobHeaderDto) {
        if (orderOutTobHeaderDto != null && orderOutTobHeaderDto.getHeader() != null && orderOutTobHeaderDto.getHeader().getShipAt() != null) {
            HeaderDto header = orderOutTobHeaderDto.getHeader();
            String shipAt = header.getShipAt();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(shipAt);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("业务日期生成失败", e);
                Assert.state(false, "业务日期生成失败，抛出异常：" + e.getMessage());
            }
            logger.info("TOB库存同步业务，生成的业务日期：{}", businessFormat);
            return businessFormat;
        } else {
            logger.error("生成出库日期失败，或者shipAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            Assert.state(false, "生成出库日期失败，或者shipAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            return null;
        }
    }

    /**
     * 2024年7月31日 10:34:09
     * 生成业务日期，以交易成功时间作为业务日期
     *
     * @author liuyang
     */
    private String createSuccessFulTradeDate(OrderOutTobHeaderDto orderOutTobHeaderDto) throws Exception {
        //测试
//        orderOutTobHeaderDto.getHeader().setTradeSuccessAt("2024-09-12");
        if (orderOutTobHeaderDto != null && orderOutTobHeaderDto.getHeader() != null && orderOutTobHeaderDto.getHeader().getTradeSuccessAt() != null) {
            HeaderDto header = orderOutTobHeaderDto.getHeader();
            String shipAt = header.getTradeSuccessAt();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(shipAt);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("tradeSuccessAt业务日期生成失败", e);
                Assert.state(false, "业务日期生成失败，抛出异常：" + e.getMessage());
            }
            logger.info("TOB销售发票业务，生成的的业务日期为：{}", businessFormat);
            return businessFormat;
        } else {
            logger.error("生成发票业务日期失败，或者tradeSuccessAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            Assert.state(false, "生成发票业务日期失败，或者tradeSuccessAt为空! json：{}", JSON.toJSON(orderOutTobHeaderDto));
            return null;
        }
    }

    /**
     * 库存类-档案转换
     *
     * @author liuyang
     */
    private List<OrderOutTobHeaderDto> queryBasicArchives(List<HeaderDetailsDto> headerDetailsDtoList) {
        if (headerDetailsDtoList != null) {
            logger.info("库存同步：需要把OFS档案转换为U8C档案的O数据条数：{}", headerDetailsDtoList.size());
        }
        List<OrderOutTobHeaderDto> orderOutTobHeaderDtoArrayList = new ArrayList<>();
        List<ErrorHeaderDetailsDtoDto> errorHeaderDetailsDtoDtoList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            try {
                //查询对应的OFS销售订单
//                List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto> headerDetailsDtos = queryOfsOrder(headerDetailsDtoList);
//                findMatchingOfsOrder(headerDetailsDtos, headerDetailsDtoList);

                for (int i = 0; i < headerDetailsDtoList.size(); i++) {
                    HeaderDetailsDto headerDetailsDto = headerDetailsDtoList.get(i);
                    HeaderDto header = headerDetailsDto.getHeader();
                    List<DetailsDto> details = headerDetailsDto.getDetails();

                    try {
//                        Assert.notNull(header.getHeaderDetailsDto(), "OFS销售销售不能为空!");
//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto headerDetailsDto1 = header.getHeaderDetailsDto();
//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDto header2 = headerDetailsDto1.getHeader();

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

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

                        //如果没有O单据名称，则默认为「销售」
                        if (header1.getSubOrderType() == null || "".equals(header1.getSubOrderType().trim())) {
                            header1.setSubOrderType("SALES");
                        }
                        //查询对应的收发类别
                        BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject(header1.getSubOrderType());
                        Assert.notNull(bdRdclEntity, "根据收发类别编码：{} 无法匹配到U8C收发类别");

                        // 销售公司、发货公司
//                    header.setCompanyCode("SHLZ");
                        String companyCode = header.getCompanyCode();
                        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(), bdCorpEntityList.get(0).getUnitname());
                        } else if (bdStordocEntityList.size() >= 2) {
                            Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，匹配到U8C仓库多个 仓库编码:{} 组织机构主键：{} 公司名称：{}", facilityCode, bdCalbodyEntities.get(0).getPkCalbody(), bdCorpEntityList.get(0).getUnitname());
                        }

                        //销售组织
                        //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());
                        }

                        //客商基本档案
                        //查询OFS对应的销售订单，得到会员id
//                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//                    queryOfsSoSaleOutVo.setCode();
//                    SaleOrderMessageDto ofsOrder = getOfsOrder(queryOfsSoSaleOutVo, 1L);

//                    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.setCustflags(ProfilesActiveConstant.CUSTOMER);
                        bdCumandocEntity1.setPkCubasdoc(bdCubasdocEntityList.get(0).getPkCubasdoc());
                        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 = 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);
                        }

                        OrderOutTobHeaderDto orderOutTobHeaderDto = new OrderOutTobHeaderDto();
                        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.setBdRdclEntity(bdRdclEntity);

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

                        BeanUtil.copyPropertiesV2(header, orderOutTobHeaderDto);
                        orderOutTobHeaderDtoArrayList.add(orderOutTobHeaderDto);
                        //档案转换成功
                    } catch (Exception e) {
                        logger.error("TOB档案转换失败", e);
                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        //失败，只记录失败
                        ErrorHeaderDetailsDtoDto errorHeaderDetailsDtoDto = new ErrorHeaderDetailsDtoDto();
                        errorHeaderDetailsDtoDto.setNewPushDate(getNewDateStr());
                        errorHeaderDetailsDtoDto.setNewTransmitInfo(message);
                        errorHeaderDetailsDtoDto.setNewstate("N");
                        errorHeaderDetailsDtoDto.setHeader(header);
                        errorHeaderDetailsDtoDto.setDetails(details);
                        errorHeaderDetailsDtoDtoList.add(errorHeaderDetailsDtoDto);
                    }
                }
            } catch (Exception e) {
                logger.error("OFS销售出库单关联查询U8C档案失败", e);
            }
        } else {
            logger.info("queryBasicArchives方法对应的headerDetailsDtoList.size为0");
        }

        //批量把错误写入到日志信息表
        if (errorHeaderDetailsDtoDtoList.size() > 0) {
            updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryStock(errorHeaderDetailsDtoDtoList);
        }
        return orderOutTobHeaderDtoArrayList;
    }

    /**
     * bean copy
     * 2024年7月31日 10:34:09
     */
    private List<TocofsSaleoutEntity> copyHeaderDto(List<HeaderDto> headerDtoList) {
        List<TocofsSaleoutEntity> tocofsSaleoutEntityList = new ArrayList<>();
        if (headerDtoList != null && headerDtoList.size() > 0) {
            for (int i = 0; i < headerDtoList.size(); i++) {
                HeaderDto headerDto = headerDtoList.get(i);
                TocofsSaleoutEntity tocofsSaleoutEntity = new TocofsSaleoutEntity();
//                BeanUtils.copyProperties(headerDto, tocofsSaleoutEntity);
                BeanUtil.copyPropertiesV2(headerDto, tocofsSaleoutEntity);
                tocofsSaleoutEntityList.add(tocofsSaleoutEntity);
            }
        }
        return tocofsSaleoutEntityList;
    }

    /**
     * bean copy
     * 2024年8月2日 16:04:11
     */
    private List<TocofsSaleoutDetailedEntity> copyDetailsDto(List<DetailsDto> detailsDtos) {
        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityArrayList = new ArrayList<>();
        if (detailsDtos != null && detailsDtos.size() > 0) {
            for (int i = 0; i < detailsDtos.size(); i++) {
                DetailsDto detailsDto = detailsDtos.get(i);
                TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
//                tocofsSaleoutDetailedEntity.setBusinessType("TOB_ORDER");
//                BeanUtils.copyProperties(detailsDto, tocofsSaleoutDetailedEntity);
                BeanUtil.copyPropertiesV2(detailsDto, tocofsSaleoutDetailedEntity);
                //补充一些业务字段
                createPrimaryKeyAndBusinessDateAndBusinessType(tocofsSaleoutDetailedEntity, detailsDto);
                tocofsSaleoutDetailedEntityArrayList.add(tocofsSaleoutDetailedEntity);
            }
        }
        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(DetailsDto detailsDto, String pkCorp, String corpName) 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, corpName);
        } else if (bdInvmandocEntity2.size() >= 2) {
            Assert.state(false, "根据O商家编码：{} U8C发货公司主键：{} 发货公司名称：{} 没有查询到存货管理档案", detailsDto.getSkuCode(), pkCorp, corpName);
        }
        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, bdTaxitemsEntityList.size());
        }
        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 saleinvoiceDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                saleinvoiceDto = resultDataHandleV2(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "TOB业务O出库单推送U8C销售订单失败 接口返回结果：{}", result);
        }
        return saleinvoiceDto;
    }

    /**
     * 返回结果解析处理，在确认了success后调用
     *
     * @author liuyang
     */
    private SaleinvoiceDto resultDataHandle(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) {
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }

    /**
     * 返回结果解析处理，在确认了success后调用
     *
     * @author liuyang
     */
    private SoSaleResultRootDto resultDataHandleV2(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) {
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }

    /**
     * 查询OFS销售订单
     *
     * @author liuyang
     */
//    public SaleOrderMessageDto getOfsOrder(QueryOfsSoSaleOutVo queryOfsSoSaleOutVo, Long pageNo) throws Exception {
//        Long pageSize = 200L;
//        queryOfsSoSaleOutVo.setPageNo(pageNo);
//        queryOfsSoSaleOutVo.setPageSize(pageSize);
//
//        InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
//        interfaceParamDto.setApi("ofs.salesOrder.search");
//        interfaceParamDto.setData(JSON.toJSONString(queryOfsSoSaleOutVo));
//        SaleOrderMessageDto saleOrderMessageDto = (SaleOrderMessageDto) ofsUnifiedService.unified(interfaceParamDto);
//        return saleOrderMessageDto;
//    }

    /**
     * 2024年8月15日 17:08:42
     * 填充主表主键、业务日期、业务类型
     */
    private void createPrimaryKeyAndBusinessDateAndBusinessType(TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity, DetailsDto detailsDto) {
        if (tocofsSaleoutDetailedEntity != null && detailsDto != null && detailsDto.getHeaderDto() != null) {
            HeaderDto headerDto = detailsDto.getHeaderDto();

            if (headerDto.getId() != null) {
                tocofsSaleoutDetailedEntity.setMaintableid(headerDto.getId());//主表主键
            }
            if (headerDto.getShipAt() != null) {
                tocofsSaleoutDetailedEntity.setBusinessdate(headerDto.getShipAt());//业务日期-出库日期
            }
            if (headerDto.getTradeSuccessAt() != null) {
                tocofsSaleoutDetailedEntity.setSuccessfultradedate(headerDto.getTradeSuccessAt());//业务日期-交易时间
            }
            tocofsSaleoutDetailedEntity.setBusinesstype("TOB_ORDER");//业务类型
        } else {
            logger.info("createPrimaryKeyAndBusinessDateAndBusinessType方法存在false！");
        }
    }

    /**
     * 档案转换(销售发票)
     *
     * @author liuyang
     */
    private List<OrderOutTobHeaderDto> queryBasicArchivesSaleinvoice(List<HeaderDetailsDto> headerDetailsDtoList) {
        if (headerDetailsDtoList != null) {
            logger.info("库存同步：需要把OFS档案转换为U8C档案的O数据条数：{}", headerDetailsDtoList.size());
        }
        List<OrderOutTobHeaderDto> orderOutTobHeaderDtoArrayList = new ArrayList<>();
        List<ErrorHeaderDetailsDtoDto> errorHeaderDetailsDtoDtoList = new ArrayList<>();
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            try {
                for (int i = 0; i < headerDetailsDtoList.size(); i++) {
                    HeaderDetailsDto headerDetailsDto = headerDetailsDtoList.get(i);
                    HeaderDto header = headerDetailsDto.getHeader();
                    List<DetailsDto> details = headerDetailsDto.getDetails();

                    try {
                        //根据OFS销售出库单，查询得到OFS销售订单
                        SaleOrderMessageDto saleOrderMessageDto = null;
                        try {
                            saleOrderMessageDto = afterSalesOrderUtil.getOfsOrder(header.getRefOrderCode());
                        } catch (Exception e) {
                            logger.error("查询销售订单错误，失败原因：{}", e.getMessage());
                            Assert.state(false, "查询销售订单错误，失败原因：{}", e.getMessage());
                        }
                        if (saleOrderMessageDto == null) {
                            Assert.state(false, "根据单号：{},没有匹配到销售订单，系统业务无法完成", header.getRefOrderCode());
                        }

                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDto header1 = saleOrderMessageDto.getData().get(0).getHeader();
                        String memberId = header1.getMemberId();
                        // 测试
//                        memberId = "hzz";
                        Assert.notNull(memberId, "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");
                        Assert.state(!"".equals(memberId.trim()), "TOB销售订单(OFS)表头会员id不能为空，否则无法匹配U8C客商档案！");

//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto headerDetailsDto1 = header.getHeaderDetailsDto();
//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDto header2 = headerDetailsDto1.getHeader();
                        //如果没有O单据名称，则默认为「销售」
                        if (header1.getSubOrderType() == null || "".equals(header1.getSubOrderType().trim())) {
                            header1.setSubOrderType("SALES");
                        }

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

                        //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());
                        soSaleEntity.setBretinvflag("N");//仅查询销售订单
                        List<SoSaleEntity> soSaleEntityList = iSoSaleDao.query(soSaleEntity);
                        if (soSaleEntityList == null || soSaleEntityList.size() == 0) {
                            Assert.state(false, "根据O出库单主键：{} 单号：{} 无法匹配到U8C销售订单(传到U8C可能失败了！bretinvflag=N)", 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());
                        }

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

                        //查询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, "根据销售订单主键：{}，无法匹配到销售订单执行情况明细");
                        }

                        // 销售公司、发货公司
//                    header.setCompanyCode("SHLZ");
                        String companyCode = header.getCompanyCode();
                        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(), bdCorpEntityList.get(0).getUnitname());
                        } else if (bdStordocEntityList.size() >= 2) {
                            Assert.state(false, "根据O仓库编码+U8C发货库存组织主键，匹配到U8C仓库多个 仓库编码:{} 组织机构主键：{} 公司名称：{}", facilityCode, bdCalbodyEntities.get(0).getPkCalbody(), bdCorpEntityList.get(0).getUnitname());
                        }

                        //销售组织
                        //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());
                        }

                        //客商基本档案
                        //查询OFS对应的销售订单，得到会员id
//                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//                    queryOfsSoSaleOutVo.setCode();
//                    SaleOrderMessageDto ofsOrder = getOfsOrder(queryOfsSoSaleOutVo, 1L);

//                    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.setCustflags(ProfilesActiveConstant.CUSTOMER);
                        bdCumandocEntity1.setPkCubasdoc(bdCubasdocEntityList.get(0).getPkCubasdoc());
                        List<BdCumandocEntity> bdCumandocEntityList = iBdCumandocDao.query(bdCumandocEntity1);
                        if (bdCumandocEntityList == null || bdCumandocEntityList.size() == 0) {
                            Assert.state(false, "根据客商基本档案主键{}，无法匹配到客商管理档案", bdCubasdocEntityList.get(0).getPkCubasdoc());
                        } else if (bdCumandocEntityList.size() >= 2) {
                            Assert.state(false, "根据客商基本档案主键{}，匹配到{}哥客商管理档案", bdCubasdocEntityList.get(0).getPkCubasdoc(), bdCumandocEntityList.size());
                        }

                        //查找平台
//                        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);
                        }

                        OrderOutTobHeaderDto orderOutTobHeaderDto = new OrderOutTobHeaderDto();
                        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(soSaleEntityList.size() - 1));
                        orderOutTobHeaderDto.setIcGeneralHEntity(icGeneralHEntityList.get(0));
                        orderOutTobHeaderDto.setIcGeneralBEntityList(icGeneralBEntityList);
                        orderOutTobHeaderDto.setSoSaleorderBEntityList(soSaleorderBEntityList);
                        orderOutTobHeaderDto.setExtIntegrationTaskLivingDetailsQueryVos(extIntegrationTaskLivingDetailsQueryVos);
                        orderOutTobHeaderDto.setBdRdclEntity(bdRdclEntity);

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

                        BeanUtil.copyPropertiesV2(header, orderOutTobHeaderDto);
                        orderOutTobHeaderDtoArrayList.add(orderOutTobHeaderDto);
                        //成功，进入下一个环节
                    } catch (Exception e) {
                        logger.error("TOB档案转换失败", e);
                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        //失败，只记录失败
                        ErrorHeaderDetailsDtoDto errorHeaderDetailsDtoDto = new ErrorHeaderDetailsDtoDto();
                        errorHeaderDetailsDtoDto.setDef5(getNewDateStr());//推送时间
                        errorHeaderDetailsDtoDto.setDef6(message);//报错详情
                        errorHeaderDetailsDtoDto.setNewstate4("N");//交易成功-红
                        errorHeaderDetailsDtoDto.setHeader(header);
                        errorHeaderDetailsDtoDto.setDetails(details);
                        errorHeaderDetailsDtoDtoList.add(errorHeaderDetailsDtoDto);
                    }
                }
            } catch (Exception e) {
                logger.error("OFS销售出库单关联查询U8C档案失败", e);
            }
        } else {
            logger.info("queryBasicArchives方法对应的headerDetailsDtoList.size为0");
        }
        //批量把错误写入到日志信息表
        if (errorHeaderDetailsDtoDtoList.size() > 0) {
            updateFailOrSuccessTocofsSaleoutDetailedArchiveInquiryTran(errorHeaderDetailsDtoDtoList);
        }
        return orderOutTobHeaderDtoArrayList;
    }

    /**
     * TOB交易成功的销售出库单，关联原销售出库单，生成销售发票
     *
     * @author liuyang
     */
    private void implementSuccessfulTrade(List<HeaderDetailsDto> headerDetailsDtoList) throws Exception {
        if (headerDetailsDtoList != null) {
            logger.info("TOB销售业务交易成功同步：{}行需要进行数据转换", headerDetailsDtoList.size());
        }
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            //转换基本档案
            List<OrderOutTobHeaderDto> orderOutTobHeaderDtos = queryBasicArchivesSaleinvoice(headerDetailsDtoList);
            //查询U8C业务流程
            BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
            //查询销售收发类别
//            BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("201");

            logger.info("TOB销售业务交易成功同步，档案转换成功对应的数量：{}行需要进行数据转换", orderOutTobHeaderDtos.size());
            logger.info("TOB销售发票业务流程编码：{}", bdBusitypeEntity.getBusicode());
            for (int i = 0; i < orderOutTobHeaderDtos.size(); i++) {
                OrderOutTobHeaderDto orderOutTobHeaderDto = orderOutTobHeaderDtos.get(i);
                HeaderDto header = orderOutTobHeaderDto.getHeader();
                List<DetailsDto> 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();
                    //收发类别
                    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++) {
                        DetailsDto detailsDto = details.get(j);
                        //存货管理档案：取发货公司的存货管理档案
                        BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(detailsDto, bdCalbodyEntity.getPkCorp(), bdCorpEntity.getUnitname());
                        //存货基础档案
                        BdInvbasdocEntity bdInvbasdocEntity = queryStockBasicArchives(bdInvmandocEntity.getPkInvmandoc(), deliverGoodsCorp.getPkCorp());
                        //根据存货基础档案编码，查询当前存货的税率
                        BdTaxitemsEntity bdTaxitemsEntity1 = queryBdTaxitems(bdInvbasdocEntity.getInvcode());
                        //查找来源单据，销售发票的来源单据为销售出库单
                        IcGeneralBEntity sourceDocuments = findSourceDocuments(header, detailsDto, soSaleorderBEntityList, icGeneralBEntityList, extIntegrationTaskLivingDetailsQueryVos);
                        //查找来源销售订单明细行
                        SoSaleorderBEntity sourceDocumentsV2 = findSourceDocumentsV2(header, detailsDto, soSaleorderBEntityList, extIntegrationTaskLivingDetailsQueryVos);

                        BigDecimal noriginalcurtaxprice = null;//含税单价
                        try {
                            noriginalcurtaxprice = new BigDecimal(detailsDto.getTotalPayAmount()).divide(new BigDecimal(detailsDto.getShipQty()), 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.longValue() == 0) {
                            isblargessflag = true;
                        }

                        SalesInvoiceBodyDto salesInvoiceBodyDto = new SalesInvoiceBodyDto();
                        salesInvoiceBodyDto.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());
                        salesInvoiceBodyDto.setCupreceipttype("4C");//来源单据类型
                        salesInvoiceBodyDto.setCupsourcebillcode(icGeneralHEntity.getVbillcode());//来源单据号
                        salesInvoiceBodyDto.setNnumber(detailsDto.getShipQty());
                        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());//来源主表主键
//                        salesInvoiceBodyDto.setCbodywarehouseid("1009A2100000000002BV");//附表仓库
//                        salesInvoiceBodyDto.setCcurrencytypeid("00010000000000000001");//原币
//                        salesInvoiceBodyDto.setCcustomerid("0001A210000000002Q1E");//订单客户
//                        salesInvoiceBodyDto.setCinvbasdocid("0001A210000000001GF0");//存货档案主键
//                        salesInvoiceBodyDto.setCquoteunitid("0001A210000000000EYM");//报价计量单位
//                        salesInvoiceBodyDto.setCreceiptcorpid("0001A210000000002Q1E");//收货单位
//                        salesInvoiceBodyDto.setCreceipttype("30");//来源单据类型
//                        salesInvoiceBodyDto.setCsaleid("1009A2100000000004WK");//销售主表id
//                        salesInvoiceBodyDto.setCunitid("0001A210000000000EYM");//主计量单位
//                        salesInvoiceBodyDto.setCupsourcebillbodyid("1009A2100000000004R3");//上层来源单据行

                        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之前，再次验证，在U8C是否已经存在
                    Boolean aBoolean = checkTobSalesInvoice(header.getId(), header.getCode());
                    if (aBoolean) {
                        logger.error("经过SQL查询判断，在U8C销售发票中已经存在OFS入库单号为：{} OFS入库主键为：{}的单据，为了避免造成单据重复，不推送到U8C！", header.getCode(), header.getId());
                    } else {
                        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);
                        //记录成功
                        updateSuccessOrFail3(details, "Y", "success", vreceiptcode, csaleid);
                    }
                } catch (Exception e) {
                    logger.error("TOB的销售发票传输失败，抛出异常", e);
                    //记录失败
                    String message = e.getMessage();
                    if (message == null) {
                        message = "未知错误";
                    }
                    updateSuccessOrFail3(details, "N", message, null, null);
                }
            }
        }
    }

    /**
     * 2024年8月28日 11:57:58
     * 推送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 = resultDataHandle(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "TOB业务O出库单推送U8C销售发票失败 接口返回结果：{}", result);
        }
        return soSaleResultRootDto;
    }

    /**
     * 查找来源单据,销售发票的来源单据为销售出库单，生成TOB销售订单时，明细行传O的明细行主键，查找逻辑
     * O明细行主键 -> 定位到U8C销售订单明细行 -> 销售出库单明细行
     *
     * @param header                                  O表头明细行
     * @param detailsDto                              O明细行
     * @param soSaleorderBEntityList                  U8C销售订单明细集合
     * @param icGeneralBEntityList                    U8C销售出库单明细集合
     * @param extIntegrationTaskLivingDetailsQueryVos U8C销售订单执行情况明细表
     * @author liuyang
     */
    private IcGeneralBEntity findSourceDocuments(HeaderDto header, DetailsDto detailsDto, List<SoSaleorderBEntity> soSaleorderBEntityList, List<IcGeneralBEntity> icGeneralBEntityList, List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos) {
        Assert.notNull(header, "header不能为空");
        Assert.notNull(detailsDto, "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(detailsDto.getId())) {
                targetExtIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVo;
            }
        }
        Assert.notNull(targetExtIntegrationTaskLivingDetailsQueryVo, "无法匹配到销售订单执行情况明细行，O明细行主键", detailsDto.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 detailsDto             O明细行
     * @param soSaleorderBEntityList U8C销售订单明细集合
     * @author liuyang
     */
    private SoSaleorderBEntity findSourceDocumentsV2(HeaderDto header, DetailsDto detailsDto, List<SoSaleorderBEntity> soSaleorderBEntityList, List<ExtIntegrationTaskLivingDetailsQueryVo> extIntegrationTaskLivingDetailsQueryVos) {
        Assert.notNull(header, "header不能为空");
        Assert.notNull(detailsDto, "detailsDto不能为空");
        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(detailsDto.getId())) {
                targetExtIntegrationTaskLivingDetailsQueryVo = extIntegrationTaskLivingDetailsQueryVo;
            }
        }
        Assert.notNull(targetExtIntegrationTaskLivingDetailsQueryVo, "无法匹配到销售订单执行情况明细行，O明细行主键", detailsDto.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("N");//仅查询销售订单
            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)) {
                            startImplementByTranTime(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)) {
                    startImplementByTranTime(split[0], split[1]);
                }
            }
        } catch (Exception e) {
            logger.error("记录splitDateAndPush方法抛出的异常", e);
        }
    }

    /**
     * 处理调用U8C接口，抛出的异常，或者调用成功的记录
     *
     * @author liuyang
     */
//    private void updateSuccessOrFail1(List<DetailsDto> orderOutTobHeaderDtoList, 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 (orderOutTobHeaderDtoList != null && orderOutTobHeaderDtoList.size() > 0) {
//                        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = new ArrayList<>();
//                        for (int i = 0; i < orderOutTobHeaderDtoList.size(); i++) {
//                            DetailsDto detailsDto = orderOutTobHeaderDtoList.get(i);
//
//                            TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
//                            tocofsSaleoutDetailedEntity.setId(detailsDto.getId());
//                            tocofsSaleoutDetailedEntity.setNewpushdate(getNewDateStr());
//                            tocofsSaleoutDetailedEntity.setNewtransmitinfo(finalNewTransmitInfo);
//                            tocofsSaleoutDetailedEntity.setNewstate4(newstate);
//                            if (successY.equals(newstate)) {
//                                //只有成功才填充下游系统主键和编码
//                                tocofsSaleoutDetailedEntity.setNewsystemnumber(newsystemnumber);
//                                tocofsSaleoutDetailedEntity.setNewsystemprimary(newsystemprimary);
//                            }
//                            tocofsSaleoutDetailedEntityList.add(tocofsSaleoutDetailedEntity);
//                        }
//
//                        //以50行为一个批次，推送到Mysql
//                        if (tocofsSaleoutDetailedEntityList.size() > 0) {
//                            List<List<TocofsSaleoutDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsSaleoutDetailedEntityList, 50);
//                            for (int i = 0; i < splitListByCount.size(); i++) {
//                                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList1 = splitListByCount.get(i);
//                                iTocofsSaleoutDetailedDao.entityInsertOrUpdateBatchStock5(tocofsSaleoutDetailedEntityList1);
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    logger.error("处理调用U8C接口，抛出的异常，或者调用成功的记录对应的方法抛出异常", e);
//                }
//            }
//        });
//        thread.start();
//        try {
//            thread.join();
//        } catch (Exception e) {
//            logger.error("updateSuccessOrFail1方法现场抛出异常", e);
//        }
//    }

    /**
     * 处理调用U8C接口，抛出的异常，或者调用成功的记录
     *
     * @author liuyang
     */
    private void updateSuccessOrFail2(List<DetailsDto> orderOutTobHeaderDtoList, 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 (orderOutTobHeaderDtoList != null && orderOutTobHeaderDtoList.size() > 0) {
                        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < orderOutTobHeaderDtoList.size(); i++) {
                            DetailsDto detailsDto = orderOutTobHeaderDtoList.get(i);

                            TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
                            tocofsSaleoutDetailedEntity.setId(detailsDto.getId());
                            tocofsSaleoutDetailedEntity.setNewpushdate(getNewDateStr());
                            tocofsSaleoutDetailedEntity.setNewtransmitinfo(finalNewTransmitInfo);
                            tocofsSaleoutDetailedEntity.setNewstate(newstate);
                            if (successY.equals(newstate)) {
                                //只有成功才填充下游系统主键和编码
                                tocofsSaleoutDetailedEntity.setNewsystemnumber(newsystemnumber);
                                tocofsSaleoutDetailedEntity.setNewsystemprimary(newsystemprimary);
                            }
                            tocofsSaleoutDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                        }

                        //以50行为一个批次，推送到Mysql
                        if (tocofsSaleoutDetailedEntityList.size() > 0) {
                            List<List<TocofsSaleoutDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsSaleoutDetailedEntityList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList1 = splitListByCount.get(i);
                                iTocofsSaleoutDetailedDao.entityInsertOrUpdateBatchStock6(tocofsSaleoutDetailedEntityList1);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("处理调用U8C接口，抛出的异常，或者调用成功的记录对应的方法抛出异常", e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("updateSuccessOrFail1方法现场抛出异常", e);
        }
    }

    /**
     * 处理调用U8C接口，抛出的异常，或者调用成功的记录
     *
     * @author liuyang
     */
    private void updateSuccessOrFail3(List<DetailsDto> orderOutTobHeaderDtoList, 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 (orderOutTobHeaderDtoList != null && orderOutTobHeaderDtoList.size() > 0) {
                        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < orderOutTobHeaderDtoList.size(); i++) {
                            DetailsDto detailsDto = orderOutTobHeaderDtoList.get(i);

                            TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
                            tocofsSaleoutDetailedEntity.setId(detailsDto.getId());
                            tocofsSaleoutDetailedEntity.setDef5(getNewDateStr());
                            tocofsSaleoutDetailedEntity.setDef6(finalNewTransmitInfo);
                            tocofsSaleoutDetailedEntity.setNewstate4(newstate);
                            if (successY.equals(newstate)) {
                                //只有成功才填充下游系统主键和编码
                                tocofsSaleoutDetailedEntity.setNewsystemnumber4(newsystemnumber);
                                tocofsSaleoutDetailedEntity.setNewsystemprimary4(newsystemprimary);
                            }
                            tocofsSaleoutDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                        }

                        //以50行为一个批次，推送到Mysql
                        if (tocofsSaleoutDetailedEntityList.size() > 0) {
                            List<List<TocofsSaleoutDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsSaleoutDetailedEntityList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList1 = splitListByCount.get(i);
                                iTocofsSaleoutDetailedDao.entityInsertOrUpdateBatchStock8(tocofsSaleoutDetailedEntityList1);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("处理调用U8C接口，抛出的异常，或者调用成功的记录对应的方法抛出异常", 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);
    }

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

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (errorHeaderDetailsDtoDtoList != null && errorHeaderDetailsDtoDtoList.size() > 0) {
                        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < errorHeaderDetailsDtoDtoList.size(); i++) {
                            ErrorHeaderDetailsDtoDto errorHeaderDetailsDtoDto = errorHeaderDetailsDtoDtoList.get(i);
                            HeaderDto header = errorHeaderDetailsDtoDto.getHeader();
                            List<DetailsDto> details = errorHeaderDetailsDtoDto.getDetails();
                            String newstate = errorHeaderDetailsDtoDto.getNewstate();
                            String newPushDate = errorHeaderDetailsDtoDto.getNewPushDate();
                            String newTransmitInfo = errorHeaderDetailsDtoDto.getNewTransmitInfo();

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

                            for (int j = 0; j < details.size(); j++) {
                                DetailsDto detailsDto = details.get(j);

                                TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
                                tocofsSaleoutDetailedEntity.setId(detailsDto.getId());
                                tocofsSaleoutDetailedEntity.setNewpushdate(newPushDate);
                                tocofsSaleoutDetailedEntity.setNewtransmitinfo(newTransmitInfo);
                                tocofsSaleoutDetailedEntity.setNewstate(newstate);
                                tocofsSaleoutDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                            }
                        }

                        //以50行为一个批次更新状态
                        if (tocofsSaleoutDetailedEntityList.size() > 0) {
                            List<List<TocofsSaleoutDetailedEntity>> splitListByCount = SplitListByCountUtil.splitListByCount(tocofsSaleoutDetailedEntityList, 50);
                            for (int i = 0; i < splitListByCount.size(); i++) {
                                List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList1 = splitListByCount.get(i);
                                iTocofsSaleoutDetailedDao.entityInsertOrUpdateBatchStock1(tocofsSaleoutDetailedEntityList1);
                            }
                        }
                    }
                } 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<ErrorHeaderDetailsDtoDto> errorHeaderDetailsDtoDtoList) {
        Assert.notNull(errorHeaderDetailsDtoDtoList, "errorHeaderDetailsDtoDtoList不能为空！");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (errorHeaderDetailsDtoDtoList != null && errorHeaderDetailsDtoDtoList.size() > 0) {
                        List<TocofsSaleoutDetailedEntity> tocofsSaleoutDetailedEntityList = new ArrayList<>();
                        for (int i = 0; i < errorHeaderDetailsDtoDtoList.size(); i++) {
                            ErrorHeaderDetailsDtoDto errorHeaderDetailsDtoDto = errorHeaderDetailsDtoDtoList.get(i);
                            HeaderDto header = errorHeaderDetailsDtoDto.getHeader();
                            List<DetailsDto> details = errorHeaderDetailsDtoDto.getDetails();

                            String newstate = errorHeaderDetailsDtoDto.getNewstate4();
                            String newPushDate = errorHeaderDetailsDtoDto.getDef5();
                            String newTransmitInfo = errorHeaderDetailsDtoDto.getDef6();

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

                            for (int j = 0; j < details.size(); j++) {
                                DetailsDto detailsDto = details.get(j);

                                TocofsSaleoutDetailedEntity tocofsSaleoutDetailedEntity = new TocofsSaleoutDetailedEntity();
                                tocofsSaleoutDetailedEntity.setId(detailsDto.getId());
                                tocofsSaleoutDetailedEntity.setDef5(newPushDate);
                                tocofsSaleoutDetailedEntity.setDef6(newTransmitInfo);
                                tocofsSaleoutDetailedEntity.setNewstate4(newstate);
                                tocofsSaleoutDetailedEntityList.add(tocofsSaleoutDetailedEntity);
                            }
                        }

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

    /**
     * 通过OFS销售出库单，联查OFS销售订单
     *
     * @param headerDetailsDtoList OFS销售出库单
     */
//    private List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto> queryOfsOrder(List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> headerDetailsDtoList) throws Exception {
//        List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto> allHeaderDetailsDtoArrayList = new ArrayList<>();
//        try {
//            if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
//                List<List<HeaderDetailsDto>> splitListByCount = SplitListByCountUtil.splitListByCount(headerDetailsDtoList, 100);
//                for (int i = 0; i < splitListByCount.size(); i++) {
//                    List<HeaderDetailsDto> headerDetailsDtos = splitListByCount.get(i);
//
//                    StringBuffer stringBuffer = new StringBuffer();
//                    if (headerDetailsDtos != null && headerDetailsDtos.size() > 0) {
//                        for (int j = 0; j < headerDetailsDtos.size(); j++) {
//                            HeaderDetailsDto headerDetailsDto = headerDetailsDtos.get(j);
//                            HeaderDto header = headerDetailsDto.getHeader();
////                List<DetailsDto> details = headerDetailsDto.getDetails();
////                stringBuffer.append("'");
//                            stringBuffer.append(header.getRefOrderCode());
////                stringBuffer.append("'");
//                            stringBuffer.append(",");
//                        }
//                    }
//                    String substring = stringBuffer.substring(0, stringBuffer.length());
//
//                    List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto> headerDetailsDtoArrayList = new ArrayList<>();
//                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
//                    queryOfsSoSaleOutVo.setCode(substring);
//                    ofsStandardUtil.getOfsSaleOrder(queryOfsSoSaleOutVo, headerDetailsDtoArrayList, 1L);
//                    allHeaderDetailsDtoArrayList.addAll(headerDetailsDtoArrayList);
//                }
//            }
//        } catch (Exception e) {
//            logger.error("queryOfsOrder方法抛出异常", e);
//        }
//        return allHeaderDetailsDtoArrayList;
//    }

    /**
     * 代码匹配销售订单
     *
     * @param ofsSaleOrder    ofs销售订单集合
     * @param ofsSaleOutOrder ofs销售出库单集合
     * @author liuyang
     */
//    private void findMatchingOfsOrder(List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto> ofsSaleOrder, List<com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto> ofsSaleOutOrder) throws Exception {
//        if (ofsSaleOrder != null && ofsSaleOutOrder != null && ofsSaleOrder.size() > 0 && ofsSaleOutOrder.size() > 0) {
//            try {
//                for (int i = 0; i < ofsSaleOutOrder.size(); i++) {
//                    HeaderDetailsDto headerDetailsDto = ofsSaleOutOrder.get(i);
//                    HeaderDto header = headerDetailsDto.getHeader();
//                    List<DetailsDto> details = headerDetailsDto.getDetails();
//
//                    String targetRefOrderCode = header.getRefOrderCode();
//                    for (int j = 0; j < ofsSaleOrder.size(); j++) {
//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDetailsDto headerDetailsDto1 = ofsSaleOrder.get(j);
//                        com.hzya.frame.ttxofs.dto.ofssalesordersearch.HeaderDto header1 = headerDetailsDto1.getHeader();
//                        List<com.hzya.frame.ttxofs.dto.ofssalesordersearch.DetailsDto> details1 = headerDetailsDto1.getDetails();
//                        if (header1.getCode().equals(targetRefOrderCode)) {
//                            header.setHeaderDetailsDto(headerDetailsDto1);
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                logger.error("findMatchingOfsOrder方法抛出异常", e);
//            }
//        }
//    }
}