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

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.QueryIntegrationTaskLivingDetails;
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.dao.IIntegrationTaskLivingDetailsDao;
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.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.*;

/**
 * O采购入库 -> U8C委外加工入库
 *
 * @Author：liuyang
 * @Package：com.hzya.frame.plugin.lets.plugin.outsourc
 * @Project：kangarooDataCenterV3
 * @name：ConsignmachiningIn
 * @Date：2024年8月26日 10:23:20
 * @Filename：ConsignmachiningIn
 */
public class ConsignmachiningIn extends PluginBaseEntity {

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

    @Autowired
    private QueryBdBusitypeUtil queryBdBusitypeUtil;

    @Autowired
    private IBdCorpDao iBdCorpDao;

    @Autowired
    private IBdInvmandocDao iBdInvmandocDao;

    @Autowired
    private IBdCalbodyDao iBdCalbodyDao;

    @Autowired
    private IBdStordocDao iBdStordocDao;

    @Autowired
    private RdclUtil rdclUtil;

    @Autowired
    private OfsStandardUtil ofsStandardUtil;

    @Autowired
    private IScOrderDao iScOrderDao;

    @Autowired
    private IScOrderBDao iScOrderBDao;

    @Autowired
    private IBdPurorgDao iBdPurorgDao;

    @Autowired
    private IBdCubasdocDao iBdCubasdocDao;

    @Autowired
    private IBdCumandocDao iBdCumandocDao;

    @Autowired
    private IBdInvbasdocDao iBdInvbasdocDao;

    @Autowired
    private OnlyImplementProxyOrderUtil onlyImplementProxyOrder;

    @Autowired
    private IBdBomDao iBdBomDao;

    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;

    @Autowired
    private IntegrationTaskLivingDetailsUtil integrationTaskLivingDetailsUtil;

    @Autowired
    private OffsetTimeTime offsetTimeTime;

    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 "outsourc.ConsignmachiningIn";
    }

    @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 {
        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)) {
                    startImplement(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.LETS_PROFILES_ACTIVE.equals(PROD_FILED)) {
                    //默认被定时器执行，实时执行，计算时间偏移量
                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    startImplement(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;
    }

    /**
     * 根据单号查询
     *
     * @author liuyang
     */
    public void startImplement(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("数据返回行数：{}", returnGoodHeaderDetailsDataDtoArrayList.size());
                    if (returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
                        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 endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("结束（委外采购）OFS采购入库单生成U8C委外加工入库 开始时间：{} 结束时间：{} 耗时：{}", startTime, endTime, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 根据单号查询
     *
     * @author liuyang
     */
    public void startImplement(String code) {
        long startMillis = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("开始（委外采购）OFS采购入库单生成U8C委外加工入库 OFS采购入库单号：{}", 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) {
                        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 endMillis = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("结束（委外采购）OFS采购入库单生成U8C委外加工入库 OFS采购入库单号：{}", code, (endMillis - startMillis));
        logger.info(threadNameStrEnd);
    }

    /**
     * 环境预配置
     *
     * @param returnGoodHeaderDetailsDataDtoArrayList 采购入库单
     * @author liuyang
     */
    private void getSet(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //过滤成功的数据
        List<StockinOrderSearchResponse.StockinOrder> stockinOrderList = filterData(returnGoodHeaderDetailsDataDtoArrayList);
        //执行推送主逻辑
        implement(stockinOrderList);
    }

    /**
     * 过滤掉成功的数据
     *
     * @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> headerDetailsDtoList1) {
        if (headerDetailsDtoList1 != null && headerDetailsDtoList1.size() > 0) {
            StringBuilder result = new StringBuilder();
            for (StockinOrderSearchResponse.StockinOrder obj : headerDetailsDtoList1) {
                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<ConsignmachiningInSonDto> consignmachiningInSonDtos = queryBasicArchives(returnGoodHeaderDetailsDataDtoList);
                // 查询采购收发类别
                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("105");
                //代理委外入库业务流程
                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();

                if (consignmachiningInSonDtos != null && consignmachiningInSonDtos.size() > 0) {
                    for (int i = 0; i < consignmachiningInSonDtos.size(); i++) {
                        ConsignmachiningInSonDto consignmachiningInSonDto = consignmachiningInSonDtos.get(i);

                        String generateBusinessDate = null;
                        try {
                            //                        StockinOrderSearchResponse.StockinOrder.StockinH header = consignmachiningInSonDto.getHeader();
                            List<StockinOrderSearchResponse.StockinOrder.StockinB> details = consignmachiningInSonDto.getDetails();

                            generateBusinessDate = createGenerateBusinessDate(consignmachiningInSonDto); //生成业务日期
                            OfsPoOrderData ofsPoOrderData = consignmachiningInSonDto.getOfsPoOrderData();//OFS采购订单
                            OfsPoOrderHeader ofsPoOrderDataHeader = ofsPoOrderData.getHeader();
                            List<OfsPoOrderDetails> ofsPoOrderDataDetails = ofsPoOrderData.getDetails();

//                        ScOrderEntity scOrderEntity = consignmachiningInSonDto.getScOrderEntity();//U8C委外订单
                            BdCorpEntity bdCorpEntity = consignmachiningInSonDto.getBdCorpEntity();//公司
                            BdCalbodyEntity bdCalbodyEntity = consignmachiningInSonDto.getBdCalbodyEntity();//库存组织
                            BdPurorgEntity bdPurorgEntity = consignmachiningInSonDto.getBdPurorgEntity();//采购组织
//                        BdStordocEntity bdStordocEntity = consignmachiningInSonDto.getBdStordocEntity();//仓库
//                        StockinOrderSearchResponse.StockinOrder.StockinH header1 = consignmachiningInSonDto.getHeader();
                            List<StockinOrderSearchResponse.StockinOrder.StockinB> details1 = consignmachiningInSonDto.getDetails();//OFS采购入库单明细行
//                        List<ScOrderBEntity> scOrderBEntityList = consignmachiningInSonDto.getScOrderBEntityList();//U8C委外订单明细行主键
                            BdCubasdocEntity bdCubasdocEntity = consignmachiningInSonDto.getBdCubasdocEntity();//客商基本档案
                            BdCumandocEntity bdCumandocEntity = consignmachiningInSonDto.getBdCumandocEntity();//客商管理档案
                            BdStordocEntity bdStordocEntity = consignmachiningInSonDto.getBdStordocEntity();//表体仓库

                            //委外订单表头
                            ScorderHeadDto poOrderParentDto = new ScorderHeadDto();
                            poOrderParentDto.setPk_corp(bdCorpEntity.getPkCorp());
                            poOrderParentDto.setCbiztype(bdBusitypeEntity.getPkBusitype());
                            poOrderParentDto.setCoperator(OverallConstant.getOverAllValue("u8cApiZdrPK"));
                            poOrderParentDto.setCpurorganization(bdPurorgEntity.getPkPurorg());
                            poOrderParentDto.setCgiveinvoicevendor(bdCumandocEntity.getPkCumandoc());
                            poOrderParentDto.setCvendormangid(bdCumandocEntity.getPkCumandoc());
                            poOrderParentDto.setDorderdate(generateBusinessDate);
                            poOrderParentDto.setCwareid(bdCalbodyEntity.getPkCalbody());//库存组织

                            poOrderParentDto.setPk_defdoc3(bdRdclEntity.getPkRdcl());//收发类别
                            poOrderParentDto.setVdef3(bdRdclEntity.getRdname());
                            poOrderParentDto.setVdef17(ProfilesActiveConstant.sourceSystem1);//来源系统
                            poOrderParentDto.setVdef19(consignmachiningInSonDto.getCode());//原单单号
                            poOrderParentDto.setVdef20(consignmachiningInSonDto.getId());//原单主键

                            //委外入库表头明细行
                            List<ScorderBodyDto> scorderBodyDtoArrayList = new ArrayList<>();
                            for (int j = 0; j < details.size(); j++) {
                                StockinOrderSearchResponse.StockinOrder.StockinB stockinB = details.get(j);
                                //匹配U8C采购订单明细行
//                            ScOrderBEntity u8cPoOrderDetail = findOfsPoOrderDetailAndU8cPoOrderDetail(stockinB, ofsPoOrderData, scOrderBEntityList);
                                //通过O采购订单入库单明细行，联查OFS采购订单明细行
                                OfsPoOrderDetails ofsPoOrderDetailRowTraget = findOfsPoOrderDetailRowTraget(stockinB, ofsPoOrderData);
                                //查询存货管理档案
                                BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(stockinB, bdCorpEntity.getPkCorp());
                                //存货基础档案
                                BdInvbasdocEntity bdInvbasdocEntity = queryStockBasicArchives(bdInvmandocEntity.getPkInvmandoc(), bdCorpEntity.getPkCorp());
                                //存货对应的BOM
                                List<BdBomEntity> bomVersion = getBomVersion(bdCalbodyEntity.getPkCalbody(), bdInvbasdocEntity.getPkInvbasdoc());

                                //计算含税单价
                                BigDecimal noriginalcurprice = null;
                                String receivedQty = stockinB.getReceivedQty();//实收数量
                                String fulfillAmount = ofsPoOrderDetailRowTraget.getFulfillAmount();//实收累计总金额
                                try {
                                    noriginalcurprice = new BigDecimal(fulfillAmount).divide(new BigDecimal(receivedQty), 20, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP);
                                } catch (Exception e) {
                                    logger.error("计算委外订单原币含税单价失败", e);
                                    Assert.state(false, "计算采购入库单原币含税单价失败 原因：{}", e.getMessage());
                                }

                                ScorderBodyDto scorderBodyDto = new ScorderBodyDto();
                                scorderBodyDto.setCmangid(bdInvmandocEntity.getPkInvmandoc());//存货
                                scorderBodyDto.setNordernum(stockinB.getReceivedQty());//数量
                                scorderBodyDto.setNoriginalnetprice(noriginalcurprice.stripTrailingZeros().toPlainString());//净单价
                                scorderBodyDto.setCwarehouseid(bdStordocEntity.getPkStordoc());//仓库
                                scorderBodyDto.setBomversion(bomVersion.get(0).getVersion());//BOM版本
                                scorderBodyDto.setDplanarrvdate(generateBusinessDate);//计划到货日期
                                scorderBodyDtoArrayList.add(scorderBodyDto);
                            }

                            List<ScorderDto> scorderDtoArrayList = new ArrayList<>();
                            ScorderDto scorderDto = new ScorderDto();
                            scorderDto.setParentvo(poOrderParentDto);
                            scorderDto.setChildrenvo(scorderBodyDtoArrayList);
                            scorderDtoArrayList.add(scorderDto);

                            Map<String, List<ScorderDto>> stringStringMap = new HashMap<>();
                            stringStringMap.put("OrderVO", scorderDtoArrayList);
                            ScOrderResultDto scOrderResultDto = sendU8cScorder(JSON.toJSONString(stringStringMap));

                            String cgeneralhid = null;
                            String vbillcode = null;
                            ScOrderResultHeadDto parentvo = scOrderResultDto.getParentvo();
                            List<ScOrderResultDetailDto> childrenvo = scOrderResultDto.getChildrenvo();
                            if (parentvo != null) {
                                cgeneralhid = parentvo.getCorderid();
                            }
                            if (parentvo != null) {
                                vbillcode = parentvo.getVordercode();
                            }
                            logger.info("推送U8C委外订单成功！委外订单主键：{} 委外订单编码：{}", cgeneralhid, vbillcode);

                            // 成功记录日志
                            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                            integrationTaskLivingDetailsEntity.setRootAppNewData(JSON.toJSONString(consignmachiningInSonDto));//原始数据json
                            integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(parentvo));//返回结果
                            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                            integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                            integrationTaskLivingDetailsEntity.setRootAppPk(consignmachiningInSonDto.getId());
                            integrationTaskLivingDetailsEntity.setRootAppBill(consignmachiningInSonDto.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(consignmachiningInSonDto));//原始数据json
                            integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(message));//返回结果
                            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                            integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                            integrationTaskLivingDetailsEntity.setRootAppPk(consignmachiningInSonDto.getId());
                            integrationTaskLivingDetailsEntity.setRootAppBill(consignmachiningInSonDto.getCode());
                            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                            saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
                        }
                    }
                } else {
                    logger.info("poOrderSonDto.size为0！");
                }
            } catch (Exception e) {
                logger.error("implement方法抛出异常", e);
            }
        }
    }

    /**
     * 档案转换(OFS->U8C)
     * 2024年8月23日 12:02:47 和妮姐沟通，单据流程U8C成品委外订单 -> 备料计划 -> U8C委外发料(核销)
     *
     * @author liuyang
     */
    private List<ConsignmachiningInSonDto> queryBasicArchives(List<StockinOrderSearchResponse.StockinOrder> returnGoodHeaderDetailsDataDtoList) {
        List<ConsignmachiningInSonDto> consignmachiningInSonDtoArrayList = new ArrayList<>();

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

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

                    //2024年8月25日 09:54:31 查询OFS采购订单
                    OfsPoOrderData ofsPoOrderData = ofsStandardUtil.queryOfsPoOrder(header.getRefOrderCode());
                    Assert.notNull(ofsPoOrderData, "无法查询到委外订单(OFS采购入库单->OSF采购订单->OFS采购订单主键->U8C委外订单自定义项20)");
                    OfsPoOrderHeader ofsPoOrderDataHeader = ofsPoOrderData.getHeader();
                    List<OfsPoOrderDetails> ofsPoOrderDataDetails = ofsPoOrderData.getDetails();

                    //如果该O采购订单对应的类型为：委外加工，则继续代码逻辑，否则就跳过代码逻辑
                    boolean checkResult = onlyImplementProxyOrder.onlyImplementProxyOrder(ofsPoOrderData, "WWJG");
                    if (!checkResult) {
                        continue;
                    }

                    //2024年8月25日 09:42:58 查询委外订单，如果这一步报错，后续的逻辑就没有必要执行了
//                    String ofsId = ofsPoOrderDataHeader.getId();
//                    Assert.notNull(ofsId, "通过接口查询到OFS采购订单，但是没有采购订单主键，业务逻辑无法完成");
//                    ScOrderEntity scOrderEntity = queryScOrder(ofsId);

                    //2024年8月25日 14:15:45 根据委外订单id，查询委外订单表体明细行
//                    List<ScOrderBEntity> scOrderBEntityList = queryScOrderDetail(scOrderEntity.getCorderid());

                    //委外订单表头公司
                    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());
                    }

                    //采购组织
                    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();
                    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);
                    }

                    //客商管理档案
                    BdCumandocEntity bdCumandocEntity1 = new BdCumandocEntity();
                    bdCumandocEntity1.setDataSourceCode("lets_u8c");
                    bdCumandocEntity1.setDr(0L);
                    bdCumandocEntity1.setPkCorp(bdCorpEntityList.get(0).getPkCorp());
                    bdCumandocEntity1.setCustflags(ProfilesActiveConstant.SUPPLIER);
                    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());
                    }

                    //2024年8月25日 10:09:20 委外入库公司，取委外订单上的公司，已经和妮姐确认，没有必要通过O的公司转换，因为不存在跨组织的问题
//                    Assert.notNull(scOrderEntity.getPkCorp(), "O表头公司不能为空");
//                    BdCorpEntity bdCorpEntity = new BdCorpEntity();
//                    bdCorpEntity.setDr(0);
//                    bdCorpEntity.setDataSourceCode("lets_u8c");
//                    bdCorpEntity.setPkCorp(scOrderEntity.getPkCorp());
//                    List<BdCorpEntity> bdCorpEntityList = iBdCorpDao.query(bdCorpEntity);
//                    if (bdCorpEntityList.size() == 0) {
//                        Assert.state(false, "根据委外订单公司主键:{}，无法匹配到委外入库单", scOrderEntity.getPkCorp());
//                    } else if (bdCorpEntityList.size() >= 2) {
//                        Assert.state(false, "根据委外订单公司主键:{}，匹配到{}个委外入库单", scOrderEntity.getPkCorp(), bdCorpEntityList.size());
//                    }

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

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

                    ConsignmachiningInSonDto consignmachiningInSonDto = new ConsignmachiningInSonDto();
                    consignmachiningInSonDto.setOfsPoOrderData(ofsPoOrderData);
//                    consignmachiningInSonDto.setScOrderEntity(scOrderEntity);
                    consignmachiningInSonDto.setBdCorpEntity(bdCorpEntityList.get(0));
                    consignmachiningInSonDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
//                    consignmachiningInSonDto.setBdStordocEntity(bdStordocEntityList.get(0));
                    consignmachiningInSonDto.setBdPurorgEntity(bdPurorgEntityList.get(0));
                    consignmachiningInSonDto.setBdCubasdocEntity(bdCubasdocEntityList.get(0));
                    consignmachiningInSonDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
//                    consignmachiningInSonDto.setHeader(header);
//                    consignmachiningInSonDto.setScOrderBEntityList(scOrderBEntityList);
                    consignmachiningInSonDto.setDetails(details);
                    consignmachiningInSonDto.setBdStordocEntity(bdStordocEntityList.get(0));

                    BeanUtil.copyPropertiesV2(header, consignmachiningInSonDto);
                    consignmachiningInSonDtoArrayList.add(consignmachiningInSonDto);
                    //成功，交给下一个业务流程处理环节
                } catch (Exception e) {
                    logger.error("采购入库单OFS档案转换错误", 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);
                }
            }
        } else {
            logger.info("queryBasicArchives对应returnGoodHeaderDetailsDataDtoList.size为0");
        }
        return consignmachiningInSonDtoArrayList;
    }

    /**
     * 查询委外订单表头对象
     *
     * @author liuyang
     */
//    private ScOrderEntity queryScOrder(String ofsPoOrderId) {
//        Assert.notNull(ofsPoOrderId, "ofsPoOrderId不能为空!");
//        Assert.state(!"".equals(ofsPoOrderId.trim()), "ofsPoOrderId不能为空");
//
//        ScOrderEntity scOrderEntity = new ScOrderEntity();
//        scOrderEntity.setVdef20(ofsPoOrderId);
//        scOrderEntity.setDr("0");
//        scOrderEntity.setDataSourceCode("lets_u8c");
//        List<ScOrderEntity> scOrderEntityList = iScOrderDao.query(scOrderEntity);
//        if (scOrderEntityList == null || scOrderEntityList.size() == 0) {
//            Assert.state(false, "根据O采购订单主键:{}(u委外订单自定义项20存储O采购订单主键)，无法匹配到U8C委外订单", ofsPoOrderId);
//        } else if (scOrderEntityList.size() >= 2) {
//            Assert.state(false, "根据O采购订单主键:{}(u委外订单自定义项20存储O采购订单主键)，匹配到{}个U8C委外订单", ofsPoOrderId, scOrderEntityList.size());
//        }
//        return scOrderEntityList.get(0);
//    }

    /**
     * 2024年8月25日 14:11:31 查询U8C委外订单明细
     *
     * @param corderid 委外订单表头主键
     * @author liuyang
     */
//    private List<ScOrderBEntity> queryScOrderDetail(String corderid) throws Exception {
//        Assert.notNull(corderid, "委外订单表头主键不能为空！");
//        Assert.state(!"".equals(corderid), "委外订单表头主键不能为空！");
//
//        ScOrderBEntity scOrderBEntity = new ScOrderBEntity();
//        scOrderBEntity.setCorderid(corderid);
//        scOrderBEntity.setDr("0");
//        scOrderBEntity.setDataSourceCode("lets_u8c");
//        List<ScOrderBEntity> scOrderBEntityList = iScOrderBDao.query(scOrderBEntity);
//        if (scOrderBEntityList == null || scOrderBEntityList.size() == 0) {
//            //2024年8月25日 14:16:31 这个验证非常要必要，单据如果没有表体没有行，是很可疑的
//            Assert.state(false, "根据U8C委外订单主键({})无法查询到委外订单表体明细行！", corderid);
//        }
//        return scOrderBEntityList;
//    }

    /**
     * 2024年8月6日 10:59:03 查询U8C业务流程
     *
     * @author liuyang
     */
    private BdBusitypeEntity u8cOperationFlow() throws Exception {
//        Assert.notNull(pkCorp, "公司主键不能为空！");
//        Assert.state(!"".equals(pkCorp.trim()), "公司主键不能为空！");
        //查询业务流程
        //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(ConsignmachiningInSonDto consignmachiningInSonDto) {
        if (consignmachiningInSonDto != null && consignmachiningInSonDto.getCheckInFrom() != null) {
            String checkInFrom = consignmachiningInSonDto.getCheckInFrom();

            String businessFormat = null;
            try {
                Date dbill = DateUtil.parse(checkInFrom);
                businessFormat = DateUtil.format(dbill, "yyyy-MM-dd");
            } catch (Exception e) {
                logger.error("业务日期生成失败", e);
            }
            return businessFormat;
        } else {
            logger.error("生成采购订单入库日期失败，或者checkInFrom为空! json：{}", JSON.toJSON(consignmachiningInSonDto));
            Assert.state(false, "生成采购订单入库日期失败，或者checkInFrom为空! json：{}", JSON.toJSON(consignmachiningInSonDto));
            return null;
        }
    }

    /**
     * 2024年8月20日 15:46:10
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDateV2(StockinOrderSearchResponse.StockinOrder.StockinH header) {
        if (header != null) {
            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);
            }
            return businessFormat;
        } else {
            logger.error("生成业务日期失败，或者shipAt为空! json：{}", JSON.toJSON(header));
            Assert.state(false, "生成业务日期失败，或者shipAt为空! json：{}", JSON.toJSON(header));
            return null;
        }
    }

    /**
     * 匹配U8C采购订单明细行
     * 通过O采购入库单明细行，得到采购订单明细行，最后查找到U8C采购订单明细行
     *
     * @param stockinB           OFS采购入库单明细行
     * @param ofsPoOrderData     OFS采购订单
     * @param scOrderBEntityList U8C委外订单明细行
     * @author liuyang
     */
//    private ScOrderBEntity findOfsPoOrderDetailAndU8cPoOrderDetail(StockinOrderSearchResponse.StockinOrder.StockinB stockinB, OfsPoOrderData ofsPoOrderData, List<ScOrderBEntity> scOrderBEntityList) {
//        Assert.notNull(stockinB, "stockinB不能为空");
//        Assert.notNull(ofsPoOrderData, "ofsPoOrderData不能为空");
//        Assert.notNull(scOrderBEntityList, "scOrderBEntityList删除不能为空");
//
////        OfsPoOrderHeader header = ofsPoOrderData.getHeader();
//        List<OfsPoOrderDetails> details = ofsPoOrderData.getDetails();
//
//        //查找采购订单明细行
//        OfsPoOrderDetails tarGetOfsPoOrderDetails = null;
//        for (int i = 0; i < details.size(); i++) {
//            OfsPoOrderDetails ofsPoOrderDetails = details.get(i);
//            if (ofsPoOrderDetails.getId().equals(stockinB.getRefOrderDetailId())) {
//                tarGetOfsPoOrderDetails = ofsPoOrderDetails;
//            }
//        }
//        Assert.notNull(tarGetOfsPoOrderDetails, "无法匹配到采购订单明细行！ 目标主键：{}", stockinB.getRefOrderDetailId());
//
//        //根据采购订单明细行主键，查找U8C采购订单明细行
//        for (int i = 0; i < scOrderBEntityList.size(); i++) {
//            ScOrderBEntity scOrderBEntity = scOrderBEntityList.get(i);
//            Assert.notNull(scOrderBEntity.getVdef20(), "委外订单明细行v20不能为空(明细行v20存储O采购订单明细行主键)！");
//            Assert.state(!"".equals(scOrderBEntity.getVdef20()), "委外订单明细行v20不能为空(明细行v20存储O采购订单明细行主键)！");
//            if (tarGetOfsPoOrderDetails.getId().equals(scOrderBEntity.getVdef20())) {
//                return scOrderBEntity;
//            }
//        }
//        Assert.state(false, "通过U8C采购订单明细行主键层层匹配到U8C采购明细失败！");
//        return null;
//    }

    /**
     * 匹配U8C采购订单明细行
     * 通过O采购入库单明细行，得到采购订单明细行，最后查找到U8C采购订单明细行
     *
     * @param stockinB       OFS采购入库单明细行
     * @param ofsPoOrderData OFS采购订单
     * @author liuyang
     */
    private OfsPoOrderDetails findOfsPoOrderDetailRowTraget(StockinOrderSearchResponse.StockinOrder.StockinB stockinB, OfsPoOrderData ofsPoOrderData) {
        Assert.notNull(stockinB, "stockinB不能为空");
        Assert.notNull(ofsPoOrderData, "ofsPoOrderData不能为空");

        List<OfsPoOrderDetails> details = ofsPoOrderData.getDetails();
        for (int i = 0; i < details.size(); i++) {
            OfsPoOrderDetails ofsPoOrderDetails = details.get(i);
            if (ofsPoOrderDetails.getId().equals(stockinB.getRefOrderDetailId())) {
                return ofsPoOrderDetails;
            }
        }
        Assert.state(false, "通过OFS采购入库单，无法匹配到OFS采购订单明细行！ 目标主键：{}", stockinB.getRefOrderDetailId());
        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月25日 15:12:22
     * 推送U8C委外入库单
     *
     * @param param 原数据json
     * @author liuyang
     */
    public ScOrderResultDto sendU8cScorder(String param) throws Exception {
        long startLong = System.currentTimeMillis();
        logger.info("U8C委外订单推送开始，推送参数：" + param + ",U8C_URL:" + OverallConstant.getOverAllValue("u8c_url"));
        String apiCode = "8000370037";
        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("U8C委外订单推送结束，返回参数：" + result);
        long endLong = System.currentTimeMillis();
        logger.info("U8C委外订单推送耗时：" + (endLong - startLong));

        if (result == null) {
            result = "";
        }

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

        boolean isSuccess = false;
        ScOrderResultDto scOrderResultDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                scOrderResultDto = resultDataHandle(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "O采购入库业务(委外入库)推送U8C委外订单失败 接口返回结果：{}", result);
        }
        return scOrderResultDto;
    }

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

    /**
     * 查询BOM版本，版本最新的在返回的结果集的最前面
     *
     * @param gcbm   工厂主键
     * @param wlbmid 物料编码id，经过测试，这是存货基本档案主键
     */
    private List<BdBomEntity> getBomVersion(String gcbm, String wlbmid) throws Exception {
        Assert.notNull(gcbm, "gcbm工厂主键");
        Assert.notNull(wlbmid, "wlbmid物料编码id不能为空");

        BdBomEntity bdBomEntity = new BdBomEntity();
        bdBomEntity.setDataSourceCode("lets_u8c");
        bdBomEntity.setWlbmid(wlbmid);
        bdBomEntity.setGcbm(gcbm);
        List<BdBomEntity> bdBomEntityList = iBdBomDao.query(bdBomEntity);
        //2024年9月2日 15:08:30 等待妮姐确认，如果对应的存货没有BOM，是否抛出异常
        //2024年9月2日 15:14:18 已经和妮姐确认，如果存货对应的BOM不存在，则抛出异常
        if (bdBomEntityList == null || bdBomEntityList.size() == 0) {
            Assert.state(false, "存货：{} 工厂(库存足足)：{}对应的BOM不存在(该存货需要维护BOM)!");
        }
        return bdBomEntityList;
    }

    /**
     * 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);
    }

    /**
     * 分割日期之后，再进行推送
     *
     * @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(",");
                        startImplement(split[0], split[1]);
                    }
                }
            } else {
                String[] split = param.split(",");
                startImplement(split[0], split[1]);
            }
        } catch (Exception e) {
            logger.error("记录splitDateAndPush方法抛出的异常", e);
        }
    }
}