package com.hzya.frame.plugin.lets.plugin.purchase.bak;

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.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.ofsvo.QueryOfsSoSaleOutVo;
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.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderData;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderDetails;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderHeader;
import com.hzya.frame.ttxofs.dto.stock.StockinOrderSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.BaseResult;
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.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 代理品牌采购业务：（代理品牌采购）OFS采购入库单生成U8C采购入库单(关联原采购订单)
 * <p>
 * 2025 年 3 月 11 日 14:49:52
 * 调整为：
 * OFS采购入库确认单(成品、代理)生成U8C采购入库单(关联原采购订单)
 *
 * @Author：liuyang
 * @Package：com.hzya.frame.plugin.lets.plugin.purchase
 * @Project：kangarooDataCenterV3
 * @name：ProxyPurchase
 * @Date：2024/8/19 18:01
 * @Filename：ProxyPurchase
 */
public class ProxyPurchaseWarehousWarehouse extends PluginBaseEntity {

    private static final ReentrantLock LOCK1 = new ReentrantLock(true);

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

    @Autowired
    private OfsUnifiedService ofsUnifiedService;

    @Autowired
    private QueryBdBusitypeUtil queryBdBusitypeUtil;

    @Autowired
    private IBdCorpDao iBdCorpDao;

    @Autowired
    private IBdDeptdocDao iBdDeptdocDao;

    @Autowired
    private IBdPurorgDao iBdPurorgDao;

    @Autowired
    private IBdCubasdocDao iBdCubasdocDao;

    @Autowired
    private IBdCumandocDao iBdCumandocDao;

    @Autowired
    private IBdInvmandocDao iBdInvmandocDao;

    @Autowired
    private QueryU8CEntityUtil queryU8CEntityUtil;

    @Autowired
    private IBdCalbodyDao iBdCalbodyDao;

    @Autowired
    private IBdStordocDao iBdStordocDao;

    @Autowired
    private RdclUtil rdclUtil;

    @Autowired
    private OfsStandardUtil ofsStandardUtil;

    @Autowired
    private OnlyImplementProxyOrderUtil onlyImplementProxyOrder;

    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private IntegrationTaskLivingDetailsUtil integrationTaskLivingDetailsUtil;

    @Autowired
    private OffsetTimeTime offsetTimeTime;

    @Autowired
    private IPoOrderDao iPoOrderDao;

    @Autowired
    private IPoOrderBDao iPoOrderBDao;

    private static final String PROD_FILED = "prod";

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

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

    @Override
    public String getPluginId() {
        return "purchase.ProxyPurchaseWarehous";
    }

    @Override
    public String getPluginName() {
        return "OFS采购入库确认单(成品、代理)生成U8C采购入库单(关联原采购订单)";
    }

    @Override
    public String getPluginLabel() {
        return "OFS采购入库确认单(成品、代理)生成U8C采购入库单(关联原采购订单)";
    }

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

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) throws Exception {
        logger.info("触发调用：{}" + getPluginName());
        try {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    long startMillis = System.currentTimeMillis();
                    logger.info("executeBusiness方法调用开始：" + getPluginName() + "-插件");

                    try {
                        String param = String.valueOf(requestJson.get("param"));
                        if (ProfilesActiveConstant.TYPE_VBILLCODE.equals(requestJson.get("type"))) {
                            //按单号推送
                            if (param != null && !"".equals(param)) {
                                startImplementByCode(param);
                            }
                        } else if (ProfilesActiveConstant.TYPE_TIME_FRAME.equals(requestJson.get("type"))) {
                            //前台页面功能日期推送，或者接口调用也行
                            String craeteDateStr = offsetTimeTime.computingTime(param);
                            if (craeteDateStr != null && !"".equals(craeteDateStr)) {
                                splitDateAndPush(craeteDateStr);
                            }
                        } else if (ProfilesActiveConstant.TYPE_DETAIL_ERROR.equals(requestJson.get("type"))) {
                            String integration_task_living_details_id = String.valueOf(requestJson.get("integration_task_living_details_id"));
                            Assert.notNull(integration_task_living_details_id, "明细行主键不能为空！");
                            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = saveOrUpdateBusinessLogUtil.queryIntegrationTaskLivingDetailsEntity(integration_task_living_details_id);
                            if (integrationTaskLivingDetailsEntity != null && integrationTaskLivingDetailsEntity.getRootAppBill() != null) {
                                startImplementByCode(integrationTaskLivingDetailsEntity.getRootAppBill());
                            }
                        } else {
                            if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(PROD_FILED)) {
                                //默认被定时器执行，实时执行，计算时间偏移量
                                StartAndEndVo startAndEndVo = offsetTimeTime.getCurrentDateRange();
                                startImplementByTime(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;
                }
            }, "执行插件：" + getPluginName());
            thread.start();

            if (requestJson != null && requestJson.get("type") != null && ProfilesActiveConstant.TYPE_DETAIL_ERROR.equals(requestJson.get("type"))) {
                try {
                    thread.join();
                } catch (Exception e) {
                    logger.error("thread.join();抛出异常", e);
                }
            }
        } catch (Exception e) {
            logger.error("executeBusiness方法抛出异常", e);
        }
        return BaseResult.getSuccessMessageEntity("插件执行成功");
    }

    /**
     * 根据时间范围查询
     *
     * @author liuyang
     */
    public void startImplementByTime(String startTime, String endTime) {
        long startMillis = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("开始（代理品牌采购）OFS采购入库单生成U8C采购订单 开始时间：{} 结束时间：{}", startTime, endTime);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClosedAt_start(startTime);
                    queryOfsSoSaleOutVo.setClosedAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setInternalInstructionType("PURCHASE");
                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsReturnGoods(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.receipt.search");
                    logger.info("插件：{} O接口返回行数：{} 时间段：{} {}", getPluginName(), returnGoodHeaderDetailsDataDtoArrayList.size(), startTime, endTime);
                    printOfsDocCode(returnGoodHeaderDetailsDataDtoArrayList, startTime, endTime);

                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        returnGoodHeaderDetailsDataDtoArrayList.removeIf(new Predicate<StockinOrderSearchResponse.StockinOrder>() {
                            @Override
                            public boolean test(StockinOrderSearchResponse.StockinOrder headerDetailsDto) {
                                StockinOrderSearchResponse.StockinOrder.StockinH header = headerDetailsDto.getHeader();
                                if (header != null && header.getCompanyCode() != null) {
                                    if (ProfilesActiveConstant.FILTER_COMPANY.contains(header.getCompanyCode().trim())) {
                                        return true;
                                    }
                                }
                                return false;
                            }
                        });
                        getSet(returnGoodHeaderDetailsDataDtoArrayList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplementByTime-方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("结束（代理品牌采购）OFS采购入库单生成U8C采购订单 开始时间：{} 结束时间：{} 耗时：{}", startTime, endTime, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 根据单号查询
     *
     * @author liuyang
     */
    public void startImplementByCode(String code) {
        long startTime = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("（代理品牌采购）OFS采购入库单生成U8C采购订单开始 采购入库单号：{}", code);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setCode(code);
                    queryOfsSoSaleOutVo.setInternalInstructionType("PURCHASE");
                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsReturnGoods(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.receipt.search");
                    logger.info("数据返回行数：{}", returnGoodHeaderDetailsDataDtoArrayList.size());
                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        returnGoodHeaderDetailsDataDtoArrayList.removeIf(new Predicate<StockinOrderSearchResponse.StockinOrder>() {
                            @Override
                            public boolean test(StockinOrderSearchResponse.StockinOrder headerDetailsDto) {
                                StockinOrderSearchResponse.StockinOrder.StockinH header = headerDetailsDto.getHeader();
                                if (header != null && header.getCompanyCode() != null) {
                                    if (ProfilesActiveConstant.FILTER_COMPANY.contains(header.getCompanyCode().trim())) {
                                        return true;
                                    }
                                }
                                return false;
                            }
                        });
                        getSet(returnGoodHeaderDetailsDataDtoArrayList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplement-方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endTime = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("（代理品牌采购）OFS采购入库单生成U8C采购订单结束 采购入库单号：{} 耗时：{}", code, (endTime - startTime));
        logger.info(threadNameStrEnd);
    }

    /**
     * 查询OFS售后退货入库单
     *
     * @param queryOfsSoSaleOutVo  查询参数
     * @param headerDetailsDtoList 查询结果集
     * @param pageNo               从第pageNo页开始查询
     */
//    private void queryOfsReturnGoods(QueryOfsSoSaleOutVo queryOfsSoSaleOutVo, List<StockinOrderSearchResponse.StockinOrder> headerDetailsDtoList, Long pageNo) throws Exception {
//        Long pageSize = 200L;
//        queryOfsSoSaleOutVo.setPageNo(pageNo);
//        queryOfsSoSaleOutVo.setPageSize(pageSize);
//
//        InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
//        interfaceParamDto.setApi("ofs.receipt.search");
//        interfaceParamDto.setData(JSON.toJSONString(queryOfsSoSaleOutVo));
//        StockinOrderSearchResponse rertunGoodsRootBean = (StockinOrderSearchResponse) ofsUnifiedService.unified(interfaceParamDto);
//        if (rertunGoodsRootBean != null) {
//            if ("false".equals(rertunGoodsRootBean.getError()) && "0".equals(rertunGoodsRootBean.getCode()) && "Success".equals(rertunGoodsRootBean.getMsg())) {
//                List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = rertunGoodsRootBean.getData();
//                if (stockinOrderList != null && stockinOrderList.size() > 0) {
//                    headerDetailsDtoList.addAll(stockinOrderList);
//
//                    //TODO OFS没有提供分页字段，等待开发
//                }
//            } else {
//                logger.error("查询失败，失败原因:{}", JSON.toJSON(interfaceParamDto));
//            }
//        } else {
//            logger.error("rertunGoodsRootBean为空！interfaceParamDto对象的结果集json：{}", JSON.toJSON(interfaceParamDto));
//        }
//    }

    /**
     * 环境预配置
     *
     * @param returnGoodHeaderDetailsDataDtoArrayList 采购入库单
     * @author liuyang
     */
    private void getSet(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        LOCK1.lock();
        try {
            //过滤成功的数据
            List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = filterData(returnGoodHeaderDetailsDataDtoArrayList);
            //执行推送主逻辑
            implement(stockinOrderList);
        } catch (Exception e) {
            logger.error("getSet抛出异常", e);
        } finally {
            LOCK1.unlock();
        }
    }

    /**
     * 过滤掉成功的数据
     *
     * @author liuyang
     */
    private List<StockinOrderSearchResponse.StockinOrder> filterData(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) {
        List<StockinOrderSearchResponse.StockinOrder> headerDetailsDtoList1 = new ArrayList<>();
        //查询得到已经成功的日志，成功或者已处理
        List<IntegrationTaskLivingDetailsEntity> successIntegrationTaskLivingDetails = new ArrayList<>();
        try {
            if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                //每100个开始拆分
                List<List<StockinOrderSearchResponse.StockinOrder>> splitListByCount = SplitListByCountUtil.splitListByCount(returnGoodHeaderDetailsDataDtoArrayList, 100);
                for (int i = 0; i < splitListByCount.size(); i++) {
                    List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = splitListByCount.get(i);
                    String primaryKey = fieldConcaten(stockinOrderList);

                    List<IntegrationTaskLivingDetailsEntity> integrationTaskLivingDetailsEntities = integrationTaskLivingDetailsUtil.queryIntegrationTaskLivingDetails(primaryKey, getPluginId());
                    successIntegrationTaskLivingDetails.addAll(integrationTaskLivingDetailsEntities);
                }

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

                    boolean isExi = false;
                    for (int j = 0; j < successIntegrationTaskLivingDetails.size(); j++) {
                        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = successIntegrationTaskLivingDetails.get(j);
                        if (integrationTaskLivingDetailsEntity.getRootAppPk().equals(header.getId())) {
                            isExi = true;
                        }
                    }
                    if (!isExi) {
                        headerDetailsDtoList1.add(stockinOrder);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("过滤成功的数据抛出异常", e);
        }
        return headerDetailsDtoList1;
    }

    /**
     * 字段拼接
     */
    private String fieldConcaten(List<StockinOrderSearchResponse.StockinOrder> stockinOrderList) {
        if (stockinOrderList != null && stockinOrderList.size() > 0) {
            StringBuilder result = new StringBuilder();
            for (StockinOrderSearchResponse.StockinOrder obj : stockinOrderList) {
                StockinOrderSearchResponse.StockinOrder.StockinH header = obj.getHeader();
//                if (result.length() > 0) {
//                    result.append(",");
//                }
                result.append("'").append(header.getId()).append("'").append(",");
            }
            return result.substring(0, result.length() - 1);
        }
        return null;
    }

    /**
     * 执行主逻辑
     *
     * @author liuyang
     */
    private void implement(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            try {
                // 查询基本档案
                List<PoOrderSonDto> poOrderSonDtos = queryBasicArchives(returnGoodHeaderDetailsDataDtoList);
                // 代理品牌采购业务流程
//                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
                // 查询采购收发类别
//                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("102");

                if (poOrderSonDtos != null && poOrderSonDtos.size() > 0) {
                    for (int i = 0; i < poOrderSonDtos.size(); i++) {
                        PoOrderSonDto poOrderSonDto = poOrderSonDtos.get(i);
                        List<StockinOrderSearchResponse.StockinOrder.StockinB> details = poOrderSonDto.getDetails();

                        String generateBusinessDate = null;
                        try {
                            //生成业务日期
                            generateBusinessDate = createGenerateBusinessDate(poOrderSonDto);

                            BdCorpEntity bdCorpEntity = poOrderSonDto.getBdCorpEntity();//采购公司、收货公司
                            BdDeptdocEntity bdDeptdocEntity = poOrderSonDto.getBdDeptdocEntity();//采购部门
                            BdPurorgEntity bdPurorgEntity = poOrderSonDto.getBdPurorgEntity();//采购组织
                            BdCubasdocEntity bdCubasdocEntity = poOrderSonDto.getBdCubasdocEntity();//客商基本档案-供应商
                            BdCumandocEntity bdCumandocEntity = poOrderSonDto.getBdCumandocEntity();//客商管理档案-供应商
                            BdCalbodyEntity bdCalbodyEntity = poOrderSonDto.getBdCalbodyEntity();//收货库存组织
                            BdStordocEntity bdStordocEntity = poOrderSonDto.getBdStordocEntity();//收货仓库

                            OfsPoOrderData ofsPoOrderData = poOrderSonDto.getOfsPoOrderData();//OFS采购订单
                            OfsPoOrderHeader ofsPoOrderDataHeader = ofsPoOrderData.getHeader();
                            List<OfsPoOrderDetails> ofsPoOrderDataDetails = ofsPoOrderData.getDetails();

                            PoOrderEntity poOrderEntity = poOrderSonDto.getPoOrderEntity();//U8C采购订单
                            List<PoOrderBEntity> poOrderBEntityList = poOrderSonDto.getPoOrderBEntityList();//U8C采购订单明细

                            //查询对应的U8C业务流程
                            BdBusitypeEntity bdBusitypeEntity = queryU8CEntityUtil.queryU8cPoOrderOperationFlow(ofsPoOrderDataHeader.getPurchaseOrderType());
                            //查询对应的U8C收发类别
                            BdRdclEntity bdRdclEntity = queryU8CEntityUtil.queryU8cPoOrderRertunSendingReceivCategory(ofsPoOrderDataHeader.getPurchaseOrderType());

                            //采购订单表头
                            PurchaseReceiptHeadDto poOrderParentDto = new PurchaseReceiptHeadDto();
                            poOrderParentDto.setCbiztype(bdBusitypeEntity.getPkBusitype());//业务流程
                            poOrderParentDto.setCdptid(bdDeptdocEntity.getPkDeptdoc());//采购部门
                            poOrderParentDto.setCbizid(OverallConstant.getOverAllValue("u8cApiZdrPK"));//制单人
                            poOrderParentDto.setCoperatorid(OverallConstant.getOverAllValue("u8cApiZdrPK"));//操作员
                            poOrderParentDto.setPk_corp(bdCorpEntity.getPkCorp());//采购公司
                            poOrderParentDto.setCproviderid(bdCumandocEntity.getPkCumandoc());//供应商管理档案
                            poOrderParentDto.setDaccountdate(generateBusinessDate);//审批日期
                            poOrderParentDto.setDbilldate(generateBusinessDate);//订单日期
                            poOrderParentDto.setCwarehouseid(bdStordocEntity.getPkStordoc());//入库仓库
                            poOrderParentDto.setFreplenishflag(false);//退货标志(Y/N)
                            poOrderParentDto.setPk_calbody(bdCalbodyEntity.getPkCalbody());//库存组织
                            poOrderParentDto.setCdispatcherid(bdRdclEntity.getPkRdcl());//收发类别

                            poOrderParentDto.setPk_defdoc3(bdRdclEntity.getPkRdcl());//收发类别名称主键
                            poOrderParentDto.setVuserdef3(bdRdclEntity.getRdname());//收发类别名称

                            poOrderParentDto.setVuserdef17(ProfilesActiveConstant.sourceSystem1);//来源系统
                            poOrderParentDto.setVuserdef19(poOrderSonDto.getCode());//原单单号
                            poOrderParentDto.setVuserdef20(poOrderSonDto.getId());//原单主键

                            //采购入库单明细行
                            List<PurchaseReceiptBodyDto> purchaseReceiptBodyDtos = new ArrayList<>();

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

                                //OFS采购订单明细行
                                OfsPoOrderDetails ofsPoOrderDetail = findOfsPoOrderDetail(ofsPoOrderDataDetails, stockinB);
                                //U8C采购订单明细行
                                PoOrderBEntity poOrderBEntity = findPoOrderBEntity(stockinB, poOrderBEntityList);

                                //2024年8月20日 16:02:21 已经和妮姐、万万确认，采购公司和收货公司目前是一致的，暂时不用区分取数逻辑
                                BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(stockinB, bdCorpEntity.getPkCorp());
                                String receivedQty = stockinB.getReceivedQty();//实收数量
                                String discountPrice = ofsPoOrderDetail.getDiscountPrice();//实际进价

                                //含税单价
                                BigDecimal noriginalcurprice = null;
                                //含税金额=含税单价*数量
                                BigDecimal ntaxmny = null;
                                try {
                                    noriginalcurprice = new BigDecimal(discountPrice);
                                    ntaxmny = noriginalcurprice.multiply(new BigDecimal(receivedQty)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                } catch (Exception e) {
                                    logger.error("计算采购入库单原币含税单价失败", e);
                                    Assert.state(false, "计算采购入库单原币含税单价失败 原因：{}", e.getMessage());
                                }

                                String bsourcelargess = "N";
                                if ("0".equals(noriginalcurprice.stripTrailingZeros().toPlainString())) {
                                    bsourcelargess = "Y";
                                }

                                PurchaseReceiptBodyDto purchaseReceiptBodyDto = new PurchaseReceiptBodyDto();
                                purchaseReceiptBodyDto.setBonroadflag("N");//是否在途
                                purchaseReceiptBodyDto.setBsourcelargess(bsourcelargess);//来源是否赠品
                                purchaseReceiptBodyDto.setFlargess(bsourcelargess);//是否赠品
                                purchaseReceiptBodyDto.setCfirstbillbid(poOrderBEntity.getCorderBid());//源头单据表体ID
                                purchaseReceiptBodyDto.setCfirstbillhid(poOrderEntity.getCorderid());//源头单据表头ID
                                purchaseReceiptBodyDto.setCsourcebillbid(poOrderBEntity.getCorderBid());//来源单据表体pk
                                purchaseReceiptBodyDto.setCsourcebillhid(poOrderEntity.getCorderid());//来源单据表头pk
                                purchaseReceiptBodyDto.setCfirsttype("21");//源头单据类型
                                purchaseReceiptBodyDto.setCsourcetype("21");//来源单据类型
                                purchaseReceiptBodyDto.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());//存货id
                                purchaseReceiptBodyDto.setCvendorid(bdCumandocEntity.getPkCumandoc());//供应商id
                                purchaseReceiptBodyDto.setDbizdate(generateBusinessDate);//入库日期
                                purchaseReceiptBodyDto.setNinnum(new BigDecimal(receivedQty).stripTrailingZeros().toPlainString());//实收数量
                                purchaseReceiptBodyDto.setVfirstbillcode(poOrderEntity.getVordercode());//源头单据号
//                                purchaseReceiptBodyDto.setNmny(nmny.stripTrailingZeros().toPlainString());// ？？？ 这个金额是如何计算的，和前台的计算逻辑不一样，接口按单价（无税单价）*数量、
//                                purchaseReceiptBodyDto.setNprice(nprice.stripTrailingZeros().toPlainString());//单价=无税单价=含税单价/(1+税率)
                                purchaseReceiptBodyDto.setNshouldinnum(new BigDecimal(poOrderBEntity.getNordernum()).stripTrailingZeros().toPlainString());//应入数量=采购订单上的采购数量
                                purchaseReceiptBodyDto.setNtaxmny(ntaxmny.stripTrailingZeros().toPlainString());//含税金额=含税单价*数量
                                purchaseReceiptBodyDto.setNtaxprice(noriginalcurprice.stripTrailingZeros().toPlainString());//含税单价=旺店通税后价格
                                purchaseReceiptBodyDto.setPk_reqcorp(poOrderBEntity.getPkReqcorp());//需求公司:取采购单明细的收货公司
                                purchaseReceiptBodyDto.setVsourcebillcode(poOrderEntity.getVordercode());//来源单据号
                                purchaseReceiptBodyDto.setVsourcerowno(poOrderBEntity.getCrowno());//来源单据行号
                                purchaseReceiptBodyDto.setBbarcodeclose("N");
                                purchaseReceiptBodyDto.setBtoouttoiaflag("N");
                                purchaseReceiptBodyDto.setCcurrencytypeid("00010000000000000001");//币种
                                purchaseReceiptBodyDto.setPk_invoicecorp(poOrderEntity.getPkCorp());//开票公司：取采购单表头的采购公司
                                purchaseReceiptBodyDto.setPk_reqstoorg(poOrderBEntityList.get(0).getPkArrvstoorg());//需求库存组织
                                purchaseReceiptBodyDto.setPk_corp(poOrderEntity.getPkCorp());//公司=收货公司
                                purchaseReceiptBodyDtos.add(purchaseReceiptBodyDto);
                            }

                            List<PurchaseReceiptDto> purchaseReceiptDtoArrayList = new ArrayList<>();

                            PurchaseReceiptDto purchaseReceiptDto = new PurchaseReceiptDto();
                            purchaseReceiptDto.setParentvo(poOrderParentDto);
                            purchaseReceiptDto.setChildrenvo(purchaseReceiptBodyDtos);
                            purchaseReceiptDtoArrayList.add(purchaseReceiptDto);

                            Map<String, List<PurchaseReceiptDto>> stringStringMap = new HashMap<>();
                            stringStringMap.put("GeneralBillVO", purchaseReceiptDtoArrayList);
                            PoOrderResultDto poOrderResultDto = sendU8CPoOrder(JSON.toJSONString(stringStringMap));

                            String cgeneralhid = null;
                            String vbillcode = null;
                            PoOrderHead parentvo = poOrderResultDto.getParentvo();
                            if (parentvo != null) {
                                cgeneralhid = parentvo.getCgeneralhid();
                                vbillcode = parentvo.getVbillcode();
                            }
                            logger.info("推送U8C代理品牌采购入库单成功！U8C采购订单主键：{} U8C采购订单编码：{}", cgeneralhid, vbillcode);

                            // 成功记录日志
                            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                            integrationTaskLivingDetailsEntity.setRootAppNewData(JSON.toJSONString(poOrderSonDto));//原始数据json
                            integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(poOrderResultDto));//返回结果
                            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                            integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                            integrationTaskLivingDetailsEntity.setRootAppPk(poOrderSonDto.getId());
                            integrationTaskLivingDetailsEntity.setRootAppBill(poOrderSonDto.getCode());
                            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                            integrationTaskLivingDetailsEntity.setNewSystemNumber(vbillcode);//下游单据编码
                            integrationTaskLivingDetailsEntity.setNewSystemPrimary(cgeneralhid);//下游单据主键
                            saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
                        } catch (Exception e) {
                            logger.error("推送U8C代理品牌采购入库单失败", e);

                            // 失败记录日志
                            String message = e.getMessage();
                            if (message == null) {
                                message = "未知错误";
                            }
                            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                            integrationTaskLivingDetailsEntity.setRootAppNewData(JSON.toJSONString(poOrderSonDto));//原始数据json
                            integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(message));//返回结果
                            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                            integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                            integrationTaskLivingDetailsEntity.setRootAppPk(poOrderSonDto.getId());
                            integrationTaskLivingDetailsEntity.setRootAppBill(poOrderSonDto.getCode());
                            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                            saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
                        }
                    }
                } else {
                    logger.info("poOrderSonDto.size为0！");
                }
            } catch (Exception e) {
                logger.error("implement方法抛出异常", e);
            }
        }
    }

    /**
     * 档案转换
     *
     * @author liuyang
     */
    private List<PoOrderSonDto> queryBasicArchives(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) {
        List<PoOrderSonDto> poOrderSonDtoArrayList = new ArrayList<>();

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

                    String generateBusinessDate = null;
                    try {
                        generateBusinessDate = createGenerateBusinessDate(stockinOrder);

                        //查询OFS采购订单
                        OfsPoOrderData ofsPoOrderData = ofsStandardUtil.queryOfsPoOrder(header.getRefOrderCode());
                        Assert.notNull(ofsPoOrderData, "根据O表头编码{}，无法匹配到OFS采购订单", header.getRefOrderCode());
                        boolean checkResult = onlyImplementProxyOrder.onlyImplementProxyOrder(ofsPoOrderData, "DLCG,CPCG");
                        if (!checkResult) {
                            continue;
                        }

                        //采购公司
                        String companyCode = header.getCompanyCode();
                        Assert.notNull(companyCode, "O表头公司不能为空");
                        String replaceCompanyCode = queryU8CEntityUtil.queryBdDefDocByPkDefDocList(companyCode.trim());
                        Assert.notNull(replaceCompanyCode, "replaceCompanyCode不能为空！");

                        BdCorpEntity bdCorpEntity = new BdCorpEntity();
                        bdCorpEntity.setDr(0);
                        bdCorpEntity.setDataSourceCode("lets_u8c");
                        bdCorpEntity.setUnitcode(replaceCompanyCode);
                        List<BdCorpEntity> bdCorpEntityList = iBdCorpDao.query(bdCorpEntity);
                        if (bdCorpEntityList.size() == 0) {
                            Assert.state(false, "根据O货主编码{}，无法匹配到U8C销售公司", replaceCompanyCode);
                        } else if (bdCorpEntityList.size() >= 2) {
                            Assert.state(false, "根据O货主编码{}，匹配到U8C销售公司{}个", replaceCompanyCode, bdCorpEntityList.size());
                        }

                        //采购部门：业务部门
                        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());
                        }

                        //采购组织
                        BdPurorgEntity bdPurorgEntity = new BdPurorgEntity();
                        bdPurorgEntity.setDr("0");
                        bdPurorgEntity.setDataSourceCode("lets_u8c");
                        bdPurorgEntity.setOwnercorp(bdCorpEntityList.get(0).getPkCorp());
                        List<BdPurorgEntity> bdPurorgEntityList = iBdPurorgDao.query(bdPurorgEntity);
                        if (bdPurorgEntityList.size() == 0) {
                            Assert.state(false, "根据采购公司主键：{} 无法匹配到采购组织", bdCorpEntityList.get(0).getPkCorp());
                        } else if (bdPurorgEntityList.size() >= 2) {
                            Assert.state(false, "根据采购公司主键：{} 匹配到多个采购组织", bdCorpEntityList.get(0).getPkCorp());
                        }

                        //客商基本档案(供应商类型)
                        //2024年8月20日 14:47:55 丽知商城、OFS 供应商客商档案、传递到U8C的客商，
                        //其中自定义项1作为原系统编码，因此统一传到自定义项一，已经和大家确认好了，没有关系的，放心大胆传吧，宝贝
                        String shipFromCode = header.getShipFromCode();
                        //测试
//                        shipFromCode = "dy-off";
                        Assert.notNull(shipFromCode, "O供应商编码不能为空，没有办法完成业务逻辑，请配置供应商编码(采购)");
                        Assert.state(!"".equals(shipFromCode.trim()), "O供应商编码不能为空，没有办法完成业务逻辑，请配置供应商编码(采购)！");
//                        BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
//                        bdCubasdocEntity.setDataSourceCode("lets_u8c");
//                        bdCubasdocEntity.setDr(0L);
//                        bdCubasdocEntity.setDef1(shipFromCode);
//                        List<BdCubasdocEntity> bdCubasdocEntityList = iBdCubasdocDao.query(bdCubasdocEntity);
//                        if (bdCubasdocEntityList == null || bdCubasdocEntityList.size() == 0) {
//                            Assert.state(false, "根据OFS供应商业务编码{}，无法查询到U8C客商档案信息(供应商)", shipFromCode);
//                        } else if (bdCubasdocEntityList.size() >= 2) {
//                            Assert.state(false, "根据OFS供应商业务编码{}，查询到多个U8C客商档案信息(供应商)", shipFromCode);
//                        }
                        BdCubasdocEntity fuzzyQueryCustomers = queryU8CEntityUtil.getFuzzyQueryCustomers(shipFromCode.trim());
                        Assert.notNull(fuzzyQueryCustomers, "根据O供应商编码：{}，无法查询到U8C客商基本档案 def1", shipFromCode.trim());

                        //客商管理档案
                        BdCumandocEntity bdCumandocEntity1 = new BdCumandocEntity();
                        bdCumandocEntity1.setDataSourceCode("lets_u8c");
                        bdCumandocEntity1.setDr(0L);
                        bdCumandocEntity1.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                        bdCumandocEntity1.setCustflags(ProfilesActiveConstant.SUPPLIER);
                        bdCumandocEntity1.setPkCubasdoc(fuzzyQueryCustomers.getPkCubasdoc());
                        List<BdCumandocEntity> bdCumandocEntityList = iBdCumandocDao.query(bdCumandocEntity1);
                        if (bdCumandocEntityList == null || bdCumandocEntityList.size() == 0) {
                            Assert.state(false, "客商：{} 没有分配给：{}，或者客商属性为客户，不满足客商或者供应商的要求！", fuzzyQueryCustomers.getCustshortname(), bdCorpEntityList.get(0).getUnitname());
                        } else if (bdCumandocEntityList.size() >= 2) {
                            Assert.state(false, "客商：{} 公司：{} 存在多个对应关系！", fuzzyQueryCustomers.getCustshortname(), bdCorpEntityList.get(0).getUnitname());
                        }

                        // 2024年8月20日 23:51:56 收货库存组织，应该是通过收货公司查询得出收货库存组织，目前收货公司和采购公司保持一致，那么就以采购公司带出！这个逻辑已经和佳妮确认
                        BdCalbodyEntity bdCalbodyEntity = new BdCalbodyEntity();
                        bdCalbodyEntity.setDr(0);
                        bdCalbodyEntity.setDataSourceCode("lets_u8c");
                        bdCalbodyEntity.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                        List<BdCalbodyEntity> bdCalbodyEntities = iBdCalbodyDao.query(bdCalbodyEntity);
                        if (bdCalbodyEntities.size() == 0) {
                            Assert.state(false, "根据U8C采购公司{}，无法匹配到U8C发货库存组织", bdCorpEntityList.get(0).getPkCorp());
                        } else if (bdCalbodyEntities.size() >= 2) {
                            Assert.state(false, "根据U8C采购公司{}，匹配到U8C发货库存组织{}个", bdCorpEntityList.get(0).getPkCorp(), bdCalbodyEntities.size());
                        }

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

                        //查询对应的U8C采购订单
                        PoOrderEntity poOrderEntity = new PoOrderEntity();
                        poOrderEntity.setDr(0L);
                        poOrderEntity.setVdef19(header.getRefOrderCode());
                        poOrderEntity.setVdef20(header.getRefOrderId());
                        poOrderEntity.setDataSourceCode("lets_u8c");
                        List<PoOrderEntity> poOrderEntityList = iPoOrderDao.query(poOrderEntity);
                        if (poOrderEntityList == null || poOrderEntityList.size() == 0) {
                            Assert.state(false, "无法匹配到U8C采购订单 原单单号：{} 原单主键：{}", header.getRefOrderCode(), header.getRefOrderId());
                        } else if (poOrderEntityList.size() >= 2) {
                            Assert.state(false, "匹配到{}个U8C采购订单，存在歧义！ 原单单号：{} 原单主键：{}", poOrderEntityList.size(), header.getRefOrderCode(), header.getRefOrderId());
                        }

                        //查询对应的U8C采购订单明细行
                        PoOrderBEntity poOrderBEntity = new PoOrderBEntity();
                        poOrderBEntity.setDr(0L);
                        poOrderBEntity.setCorderid(poOrderEntityList.get(0).getCorderid());
                        poOrderBEntity.setDataSourceCode("lets_u8c");
                        List<PoOrderBEntity> poOrderBEntityList = iPoOrderBDao.query(poOrderBEntity);
                        if (poOrderBEntityList == null || poOrderBEntityList.size() == 0) {
                            Assert.state(false, "根据采购订单主键：{} 无法查询到U8C采购订单明细行", poOrderEntityList.get(0).getCorderid());
                        }

                        PoOrderSonDto poOrderSonDto = new PoOrderSonDto();
                        poOrderSonDto.setBdCorpEntity(bdCorpEntityList.get(0));
                        poOrderSonDto.setBdDeptdocEntity(bdDeptdocEntityList.get(0));
                        poOrderSonDto.setBdPurorgEntity(bdPurorgEntityList.get(0));
                        poOrderSonDto.setBdCubasdocEntity(fuzzyQueryCustomers);
                        poOrderSonDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
                        poOrderSonDto.setOfsPoOrderData(ofsPoOrderData);
                        poOrderSonDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
                        poOrderSonDto.setBdStordocEntity(bdStordocEntityList.get(0));
                        poOrderSonDto.setPoOrderEntity(poOrderEntityList.get(0));
                        poOrderSonDto.setPoOrderBEntityList(poOrderBEntityList);
                        poOrderSonDto.setDetails(details);

                        BeanUtil.copyPropertiesV2(header, poOrderSonDto);
                        poOrderSonDtoArrayList.add(poOrderSonDto);
                    } catch (Exception e) {
                        logger.error("档案转换失败", e);

                        String message = e.getMessage();
                        if (message == null) {
                            message = "未知错误";
                        }
                        //失败
                        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                        integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                        integrationTaskLivingDetailsEntity.setRootAppNewData(JSON.toJSONString(stockinOrder));//原始数据json
                        integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(message));//返回结果
                        integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                        integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                        integrationTaskLivingDetailsEntity.setRootAppPk(header.getId());
                        integrationTaskLivingDetailsEntity.setRootAppBill(header.getCode());
                        integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                        saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
                    }
                }
                //成功
            } catch (Exception e) {
                logger.error("代理品牌采购入库单档案转换失败", e);
                //失败
            }
        } else {
            logger.info("queryBasicArchives对应returnGoodHeaderDetailsDataDtoList.size为0");
        }
        return poOrderSonDtoArrayList;
    }

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

    /**
     * 2024年8月20日 15:46:10
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDate(PoOrderSonDto poOrderSonDto) {
        if (poOrderSonDto != null && poOrderSonDto.getClosedAt() != null) {
            String closedAt = poOrderSonDto.getClosedAt();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(closedAt);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("业务日期生成失败", e);
            }
            return businessFormat;
        } else {
            logger.error("closedAt为空! json：{}", JSON.toJSON(poOrderSonDto));
            Assert.state(false, "closedAt为空! json：{}", JSON.toJSON(poOrderSonDto));
            return null;
        }
    }

    /**
     * 2024年8月20日 15:46:10
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDate(StockinOrderSearchResponse.StockinOrder stockinOrder) {
        if (stockinOrder != null) {
            StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.getHeader();
            String closedAt = header.getClosedAt();
            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(closedAt);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("业务日期生成失败", e);
            }
            return businessFormat;
        } else {
            logger.error("生成采购订单入库日期失败，或者shipAt为空! json：{}", JSON.toJSON(stockinOrder));
            Assert.state(false, "生成采购订单入库日期失败，或者shipAt为空! json：{}", JSON.toJSON(stockinOrder));
            return null;
        }
    }

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

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

    /**
     * 2024年8月20日 16:42:14
     * 查找对应的采购订单明细行
     * 2024年8月20日 17:42:15
     * 应该通过明细行主键匹配，但是只能根据sku匹配目前的实现逻辑
     * 查找OFS采购订单明细行，主要是为了带出实付金额，通过实付金额/实收数量=含税单价
     *
     * @param ofsPoOrderDataDetails OFS采购订单明细行所有对象
     * @param stockinB              OFS采购入库单明细行对象
     * @author liuyang
     */
    private OfsPoOrderDetails findOfsPoOrderDetail(List<OfsPoOrderDetails> ofsPoOrderDataDetails, StockinOrderSearchResponse.StockinOrder.StockinB stockinB) {
        if (ofsPoOrderDataDetails != null && ofsPoOrderDataDetails.size() > 0 && stockinB != null) {
            // 2024年8月20日 23:33:11 先使用sku验证，然后O接口更新明细id，使用明细id匹配！
            // 2024年8月20日 23:36:04 使用sku匹配，在某种角度来说是错误的
            // 2024年8月21日 14:23:02 O接口已经返回明细行主键，根据这个匹配
            for (int i = 0; i < ofsPoOrderDataDetails.size(); i++) {
                Assert.notNull(ofsPoOrderDataDetails.get(i).getId(), "采购订单明细行主键不能为空!");
                Assert.notNull(stockinB.getRefOrderDetailId(), "采购入库单明细行对应的关联采购订单的明细行主键不能为空！");

                if (ofsPoOrderDataDetails.get(i).getId().equals(stockinB.getRefOrderDetailId())) {
                    return ofsPoOrderDataDetails.get(i);
                }
            }
        } else {
            logger.error("findOfsPoOrderDetail方法对应的ofsPoOrderDataDetails不能为空！否则业务目标无法完成！");
        }
        Assert.state(false, "无法匹配到采购订单明细行，业务逻辑无法完成，根据sku编码：{}查找，但是在采购订单中无法匹配！", stockinB.getSkuCode());
        return null;
    }

    /**
     * 2024年8月20日 23:58:13
     * 推送U8C采购订单
     *
     * @author liuyang
     */
    public PoOrderResultDto sendU8CPoOrder(String param) throws Exception {
        long startLong = System.currentTimeMillis();
        logger.info("代理品牌采购入库推送开始，推送参数：" + param + ",U8C_URL:" + OverallConstant.getOverAllValue("u8c_url"));
        String apiCode = "8000370035";
        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("代理品牌采购入库推送结束，返回参数：" + result);
        long endLong = System.currentTimeMillis();
        logger.info("U8C采购入库接口请求耗时：" + (endLong - startLong));

        //2024年8月21日 13:17:57 如果结果返回为null，则赋予""，后面的处理逻辑能满足需求
        if (result == null) {
            result = "";
        }

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

        boolean isSuccess = false;
        PoOrderResultDto poOrderResultDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                poOrderResultDto = resultDataHandle(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "代理品牌采购业务推送U8C采购订单失败 接口返回结果：{}", result);
        }
        return poOrderResultDto;
    }

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

    /**
     * 分割日期之后，再进行推送
     *
     * @author liuyang
     */
    private void splitDateAndPush(String param) throws Exception {
        try {
            Assert.notNull(param, "param不能为空!");
            Assert.state(!"".equals(param), "param不能为空！");

            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(",");
                        startImplementByTime(split[0], split[1]);
                    }
                }
            } else {
                String[] split = param.split(",");
                startImplementByTime(split[0], split[1]);
            }
        } catch (Exception e) {
            logger.info("记录splitDateAndPush方法抛出的异常", e);
        }
    }

    /**
     * 查找U8C表体明细行
     *
     * @author liuyang
     */
    private PoOrderBEntity findPoOrderBEntity(StockinOrderSearchResponse.StockinOrder.StockinB stockinB, List<PoOrderBEntity> poOrderBEntityList) throws Exception {
        Assert.notNull(stockinB, "stockinB不能为空");
        Assert.notNull(poOrderBEntityList, "poOrderBEntityList不能为空");

        for (int i = 0; i < poOrderBEntityList.size(); i++) {
            PoOrderBEntity poOrderBEntity = poOrderBEntityList.get(i);
            if (poOrderBEntity.getVdef20() != null) {
                if (poOrderBEntity.getVdef20().equals(stockinB.getRefOrderDetailId())) {
                    return poOrderBEntity;
                }
            }
        }
        Assert.state(false, "无法匹配到U8C采购订单明细行！refOrderDetailId：{}", stockinB.getRefOrderDetailId());
        return null;
    }

    /**
     * 打印OFS单号
     *
     * @author liuyang
     */
    private void printOfsDocCode(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList, String startTime, String endTime) {
        Assert.notNull(returnGoodHeaderDetailsDataDtoArrayList, "returnGoodHeaderDetailsDataDtoArrayList不能为空");
        Assert.notNull(startTime, "startTime不能为空");
        Assert.notNull(endTime, "endTime不能为空");

        try {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("插件：");
            stringBuffer.append(getPluginName());
            stringBuffer.append(" ");

            stringBuffer.append("开始时间：");
            stringBuffer.append(startTime);
            stringBuffer.append("结束时间：");
            stringBuffer.append(endTime);
            stringBuffer.append(" ");

            stringBuffer.append("获取到的单号：");
            String codes = returnGoodHeaderDetailsDataDtoArrayList.stream().map(returnGoodHeaderDetailsDataDto -> returnGoodHeaderDetailsDataDto.getHeader().getCode()).collect(Collectors.joining(","));
            stringBuffer.append(codes);
            logger.info(stringBuffer.toString());
        } catch (Exception e) {
            logger.error("插件:{}，打印拉取到的单据号出错", getPluginName(), e);
        }
    }
}