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

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.InterfaceParamDto;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderBean;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderData;
import com.hzya.frame.ttxofs.dto.ofspurchasereturnorder.PurchaseReturnOrder;
import com.hzya.frame.ttxofs.dto.ofspurchasereturnorder.PurchaseReturnOrderDetails;
import com.hzya.frame.ttxofs.dto.ofspurchasereturnorder.PurchaseReturnOrderHeader;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.DetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDto;
import com.hzya.frame.ttxofs.dto.stock.StockinOrderSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 代理品牌采购退货业务：（代理品牌采购退货）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 ProxyPurchaseReturn extends PluginBaseEntity {

    Logger logger = LoggerFactory.getLogger(ProxyPurchaseReturn.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 IBdCalbodyDao iBdCalbodyDao;

    @Autowired
    private IBdStordocDao iBdStordocDao;

    @Autowired
    private RdclUtil rdclUtil;

    @Autowired
    private OfsStandardUtil ofsStandardUtil;

    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private OnlyImplementProxyOrderUtil onlyImplementProxyOrder;

    @Autowired
    private IntegrationTaskLivingDetailsUtil integrationTaskLivingDetailsUtil;

    private static final String PROD_FILED = "prod";

    @Autowired
    private OffsetTimeTime offsetTimeTime;

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

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

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

    @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 {
                    //OFS采退出库
                    List<HeaderDetailsDto> 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_RETURN");
                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsSaleOrder(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.shipment.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采购订单 售后入库单号：{}", code);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<HeaderDetailsDto> returnGoodHeaderDetailsDataDtoArrayList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setCode(code);
                    queryOfsSoSaleOutVo.setInternalInstructionType("PURCHASE_RETURN");
                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsSaleOrder(queryOfsSoSaleOutVo, returnGoodHeaderDetailsDataDtoArrayList, 1L, "ofs.shipment.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采购订单 售后入库单号：{} 耗时：{}", code, (endMillis - startMillis));
        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<HeaderDetailsDto> returnGoodHeaderDetailsDataDtoArrayList) throws Exception {
        //过滤成功的数据
        List<HeaderDetailsDto> headerDetailsDtos = filterData(returnGoodHeaderDetailsDataDtoArrayList);
        //执行推送主逻辑
        implement(headerDetailsDtos);
    }

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

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

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

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

    /**
     * 字段拼接
     *
     * @author liuyang
     */
    private String fieldConcaten(List<HeaderDetailsDto> headerDetailsDtoList) {
        if (headerDetailsDtoList != null && headerDetailsDtoList.size() > 0) {
            StringBuilder result = new StringBuilder();
            for (HeaderDetailsDto obj : headerDetailsDtoList) {
                HeaderDto 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<HeaderDetailsDto> headerDetailsDtos) throws Exception {
        if (headerDetailsDtos != null && headerDetailsDtos.size() > 0) {
            try {
                // 转换基本档案
                List<PoOrderRerturnSonDto> poOrderRerturnSonDtos = queryBasicArchives(headerDetailsDtos);
                // 代理品牌采购业务流程
                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
                // 查询采购收发类别
                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("102");

                if (poOrderRerturnSonDtos != null && poOrderRerturnSonDtos.size() > 0) {
                    for (int i = 0; i < poOrderRerturnSonDtos.size(); i++) {
                        PoOrderRerturnSonDto poOrderSonDto = poOrderRerturnSonDtos.get(i);
                        List<DetailsDto> 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();//收货仓库

                            PurchaseReturnOrder purchaseReturnOrder = poOrderSonDto.getPurchaseReturnOrder();//OFS采退订单
                            PurchaseReturnOrderHeader header = purchaseReturnOrder.getHeader();
                            List<PurchaseReturnOrderDetails> details1 = purchaseReturnOrder.getDetails();

                            //采购订单表头
                            PoOrderParentDto poOrderParentDto = new PoOrderParentDto();
                            poOrderParentDto.setBreturn(true);//确认退货
                            poOrderParentDto.setCbiztype(bdBusitypeEntity.getPkBusitype());//业务流程
                            poOrderParentDto.setCdeptid(bdDeptdocEntity.getPkDeptdoc());//采购部门
                            poOrderParentDto.setCoperator(OverallConstant.getOverAllValue("u8cApiZdrPK"));//制单人
                            poOrderParentDto.setCpurorganization(bdPurorgEntity.getPkPurorg());//采购组织
                            poOrderParentDto.setPk_corp(bdCorpEntity.getPkCorp());//采购公司
                            poOrderParentDto.setCvendormangid(bdCumandocEntity.getPkCumandoc());//供应商管理档案
                            poOrderParentDto.setDauditdate(generateBusinessDate);//审批日期
                            poOrderParentDto.setDorderdate(generateBusinessDate);//订单日期
                            poOrderParentDto.setDrevisiondate(generateBusinessDate);//修改日期
                            //2024年8月21日 13:34:07 对比了手工建单和接口传单，发现接口传单少了这个：是否由销售订单协同生成、补货标志、是否已协同生成销售订单 默认为N
                            poOrderParentDto.setBsocooptome(false);//是否由销售订单协同生成
                            poOrderParentDto.setBisreplenish(false);//补货标志
                            poOrderParentDto.setBcooptoso(false);//是否已协同生成销售订单
                            poOrderParentDto.setCgiveinvoicevendor(bdCumandocEntity.getPkCumandoc());//发票方id

                            poOrderParentDto.setVdef17(ProfilesActiveConstant.sourceSystem1);//来源系统
                            poOrderParentDto.setVdef19(poOrderSonDto.getCode());//原单单号
                            poOrderParentDto.setVdef20(poOrderSonDto.getId());//原单主键

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

                            //采购订单明细行
                            List<PoOrderChildrenDto> poOrderChildrenDtoList = new ArrayList<>();

                            for (int j = 0; j < details.size(); j++) {
                                DetailsDto detailsDto = details.get(j);
                                PurchaseReturnOrderDetails ofsPoOrderDetail = findOfsPoOrderDetail(details1, detailsDto);

                                //TODO 测试
                                detailsDto.setShipQty("1");
                                ofsPoOrderDetail.setFulfillAmount("10");

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

                                //原币含税单价
                                BigDecimal noriginalcurprice = null;
                                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());
                                }

                                PoOrderChildrenDto poOrderChildrenDto = new PoOrderChildrenDto();
                                poOrderChildrenDto.setCmangid(bdInvmandocEntity.getPkInvmandoc());//存货管理id
                                poOrderChildrenDto.setNordernum("-" + new BigDecimal(receivedQty).stripTrailingZeros().toPlainString());//订货数量
                                poOrderChildrenDto.setNorgtaxprice(noriginalcurprice.stripTrailingZeros().toPlainString());//原币含税单价
                                poOrderChildrenDto.setPk_arrvcorp(bdCorpEntity.getPkCorp());//收货公司
                                poOrderChildrenDto.setPk_arrvstoorg(bdCalbodyEntity.getPkCalbody());//收货库存组织
                                poOrderChildrenDto.setCwarehouseid(bdStordocEntity.getPkStordoc());//收货仓库
                                poOrderChildrenDto.setPk_reqcorp(bdCorpEntity.getPkCorp());//需求公司 *
//                            poOrderChildrenDto.setIisreplenish(false);//补货标识 *
                                poOrderChildrenDto.setCoperator(OverallConstant.getOverAllValue("u8cApiZdrPK"));//操作员id
//                            poOrderChildrenDto.setBreceiveplan(false);//存在到货计划
                                poOrderChildrenDtoList.add(poOrderChildrenDto);

                                //2024年8月20日 16:00:03 已经和佳妮总确认，计划到货日期，不用进行传递
                            }

                            List<PoOrderParentChildrenDto> poOrderParentChildrenDtoList = new ArrayList<>();
                            PoOrderParentChildrenDto poOrderParentChildrenDto = new PoOrderParentChildrenDto();
                            poOrderParentChildrenDto.setParentvo(poOrderParentDto);
                            poOrderParentChildrenDto.setChildrenvo(poOrderChildrenDtoList);
                            poOrderParentChildrenDtoList.add(poOrderParentChildrenDto);

                            Map<String, List<PoOrderParentChildrenDto>> stringStringMap = new HashMap<>();
                            stringStringMap.put("puordervo", poOrderParentChildrenDtoList);
                            PoOrderHeadBodyDto poOrderHeadBodyDto = sendU8CPoOrder(JSON.toJSONString(stringStringMap));

                            String corderid = null;
                            String vordercode = null;
                            PoOrderHeadDto parentvo = poOrderHeadBodyDto.getParentvo();
                            List<PoOrderBodyDto> childrenvo = poOrderHeadBodyDto.getChildrenvo();
                            if (parentvo != null) {
                                corderid = parentvo.getCorderid();
                            }
                            if (childrenvo != null) {
                                vordercode = parentvo.getVordercode();
                            }
                            logger.info("推送U8C代理品牌采购订单采购！U8C采购订单主键：{} U8C采购订单编码：{}", corderid, vordercode);

                            // 成功记录日志
                            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                            integrationTaskLivingDetailsEntity.setRootAppNewData(JSON.toJSONString(poOrderSonDto));//原始数据json
                            integrationTaskLivingDetailsEntity.setNewTransmitInfo(JSON.toJSONString(poOrderHeadBodyDto));//返回结果
                            integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                            integrationTaskLivingDetailsEntity.setBusinessDate(generateBusinessDate);
                            integrationTaskLivingDetailsEntity.setRootAppPk(poOrderSonDto.getId());
                            integrationTaskLivingDetailsEntity.setRootAppBill(poOrderSonDto.getCode());
                            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                            integrationTaskLivingDetailsEntity.setNewSystemNumber(vordercode);//下游单据编码
                            integrationTaskLivingDetailsEntity.setNewSystemPrimary(corderid);//下游单据主键
                            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);
            }
        }
    }

    /**
     * 档案转换(OFS->U8C)
     *
     * @param returnGoodHeaderDetailsDataDtoList 采退出库单
     * @author liuyang
     */
    private List<PoOrderRerturnSonDto> queryBasicArchives(List<HeaderDetailsDto> returnGoodHeaderDetailsDataDtoList) {
        List<PoOrderRerturnSonDto> poOrderSonDtoArrayList = new ArrayList<>();

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

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

                    //2024年8月22日 15:30:09 如果purchaseReturnOrder为null，那么在queryPurchaseReturnOrder会抛出异常，此处不需要验证purchaseReturnOrder是否为null
                    PurchaseReturnOrder purchaseReturnOrder = queryPurchaseReturnOrder(header.getRefOrderCode());
                    PurchaseReturnOrderHeader header1 = purchaseReturnOrder.getHeader();
                    List<PurchaseReturnOrderDetails> details1 = purchaseReturnOrder.getDetails();
                    boolean checkResult = onlyImplementProxyOrder.onlyImplementProxyOrder(purchaseReturnOrder, "DLCG");
                    if (!checkResult) {
                        continue;
                    }

                    //采购公司
                    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());
                    }

                    //采购部门：其他
                    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 = header1.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月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());
                    }

                    PoOrderRerturnSonDto poOrderRerturnSonDto = new PoOrderRerturnSonDto();
                    poOrderRerturnSonDto.setBdCorpEntity(bdCorpEntityList.get(0));
                    poOrderRerturnSonDto.setBdDeptdocEntity(bdDeptdocEntityList.get(0));
                    poOrderRerturnSonDto.setBdPurorgEntity(bdPurorgEntityList.get(0));
                    poOrderRerturnSonDto.setBdCubasdocEntity(bdCubasdocEntityList.get(0));
                    poOrderRerturnSonDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
                    poOrderRerturnSonDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
                    poOrderRerturnSonDto.setBdStordocEntity(bdStordocEntityList.get(0));
                    poOrderRerturnSonDto.setDetails(details);
                    poOrderRerturnSonDto.setPurchaseReturnOrder(purchaseReturnOrder);

                    BeanUtil.copyPropertiesV2(header, poOrderRerturnSonDto);
                    poOrderSonDtoArrayList.add(poOrderRerturnSonDto);
                } 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(headerDetailsDto));//原始数据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 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(PoOrderRerturnSonDto poOrderSonDto) {
        if (poOrderSonDto != null && poOrderSonDto.getShipAt() != null) {
            String shipAt = poOrderSonDto.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(poOrderSonDto));
            Assert.state(false, "生成采退出库日期失败，或者shipAt为空! json：{}", JSON.toJSON(poOrderSonDto));
            return null;
        }
    }

    /**
     * 2024年8月20日 15:46:10
     * 生成业务日期，以发货时间作为业务日期
     *
     * @author liuyang
     */
    private String createGenerateBusinessDate(HeaderDto 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;
        }
    }

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

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

    /**
     * 2024年8月20日 16:11:46
     *
     * @author liuyang
     */
    public OfsPoOrderData queryOfsPoOrder(String code) throws Exception {
        if (code != null && !"".equals(code)) {
            Long pageSize = 200L;
            Long pageNo = 1L;

            QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
            queryOfsSoSaleOutVo.setPageNo(pageNo);
            queryOfsSoSaleOutVo.setPageSize(pageSize);
            queryOfsSoSaleOutVo.setCode(code);

            InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
            interfaceParamDto.setApi("ofs.purchaseOrder.search");
            interfaceParamDto.setData(JSON.toJSONString(queryOfsSoSaleOutVo));
            OfsPoOrderBean ofsPoOrderBean = (OfsPoOrderBean) ofsUnifiedService.unified(interfaceParamDto);
            if (ofsPoOrderBean != null) {
                if ("false".equals(ofsPoOrderBean.getError()) && "0".equals(ofsPoOrderBean.getCode()) && "Success".equals(ofsPoOrderBean.getMsg())) {
                    List<OfsPoOrderData> data = ofsPoOrderBean.getData();
                    if (data != null && data.size() > 0) {
                        return data.get(0);
                    }
                } else {
                    logger.error("查询采购订单失败，失败原因:{}", JSON.toJSON(interfaceParamDto));
                }
            } else {
                logger.error("ofsPoOrderBean为空！interfaceParamDto接口入参：{}", JSON.toJSON(interfaceParamDto));
            }
        } else {
            Assert.state(false, "采购订单编码不能为空！");
        }
        return null;
    }

    /**
     * 2024年8月20日 16:42:14
     * 查找对应的采购订单明细行
     * 2024年8月20日 17:42:15
     * 应该通过明细行主键匹配，但是只能根据sku匹配目前的实现逻辑
     * 查找OFS采购订单明细行，主要是为了带出实付金额，通过实付金额/实收数量=含税单价
     *
     * @param ofsPoOrderDataDetails OFS采退订单明细行所有对象
     * @param detailsDto            OFS采退入库单明细行对象
     * @author liuyang
     */
    private PurchaseReturnOrderDetails findOfsPoOrderDetail(List<PurchaseReturnOrderDetails> ofsPoOrderDataDetails, DetailsDto detailsDto) {
        if (ofsPoOrderDataDetails != null && ofsPoOrderDataDetails.size() > 0 && detailsDto != null) {
            for (int i = 0; i < ofsPoOrderDataDetails.size(); i++) {
                Assert.notNull(ofsPoOrderDataDetails.get(i).getId(), "采退订单明细行主键不能为空!");

                Assert.notNull(detailsDto.getRefOrderDetailId(), "采退出库单明细行对应的关联采退订单的明细行主键不能为空！");
                if (ofsPoOrderDataDetails.get(i).getId().equals(detailsDto.getRefOrderDetailId())) {
                    return ofsPoOrderDataDetails.get(0);
                }
            }
        } else {
            logger.error("findOfsPoOrderDetail方法对应的ofsPoOrderDataDetails不能为空！否则业务目标无法完成！");
        }
        Assert.state(false, "无法匹配到采退订单明细行，业务逻辑无法完成！");
        return null;
    }

    /**
     * 2024年8月20日 23:58:13
     * 推送U8C采购订单
     *
     * @author liuyang
     */
    public PoOrderHeadBodyDto sendU8CPoOrder(String param) throws Exception {
        long startLong = System.currentTimeMillis();
        logger.info("代理品牌采购推送开始，推送参数：" + param + ",U8C_URL:" + OverallConstant.getOverAllValue("u8c_url"));
        String apiCode = "8000370004";
        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;
        PoOrderHeadBodyDto poOrderHeadBodyDto = null;
        if (result != null && !"".equals(result)) {
            ReusltStrDto reusltStrDto = JSON.parseObject(result, ReusltStrDto.class);
            if ("success".equals(reusltStrDto.getStatus())) {
                poOrderHeadBodyDto = resultDataHandle(reusltStrDto.getData());
                isSuccess = true;
            }
        }
        if (!isSuccess) {
            Assert.state(false, "代理品牌采购业务推送U8C采购订单失败 接口返回结果：{}", result);
        }
        return poOrderHeadBodyDto;
    }

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

    /**
     * 查询采退订单
     *
     * @param code 采退订单号
     * @author liuyang
     */
    private PurchaseReturnOrder queryPurchaseReturnOrder(String code) throws Exception {
        List<PurchaseReturnOrder> headerDetailsDtoList = new ArrayList<>();
        QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
        queryOfsSoSaleOutVo.setCode(code);
        queryOfsSoSaleOutVo.setClientCode("LETS");
        queryOfsSoSaleOutVo.setPageNo(1L);
        queryOfsSoSaleOutVo.setPageSize(50L);
        ofsStandardUtil.queryPurchaseReturnOrder(queryOfsSoSaleOutVo, headerDetailsDtoList, 1L, "ofs.purchaseReturnOrder.search");
        if (headerDetailsDtoList.size() > 0) {
            return headerDetailsDtoList.get(0);
        }
        Assert.state(false, "根据OFS采购订单号:{}无法查询到OFS采购订单信息", code);
        return null;
    }

    /**
     * 2024年8月23日 10:21:50 只保留代理品牌采购入库单
     *
     * @param returnGoodHeaderDetailsDataDtoArrayList 查询得到的采购入库单
     * @author liuyang
     */
//    private List<HeaderDetailsDto> onlyImplementProxyOrder(List<HeaderDetailsDto> returnGoodHeaderDetailsDataDtoArrayList) {
//        List<HeaderDetailsDto> headerDetailsDtos = new ArrayList<>();
//        // TODO 2024年8月23日 10:27:40 O采购单查询接口，没有采购类型字段，虽然接口文档里有一个类似的类型
//        if (returnGoodHeaderDetailsDataDtoArrayList != null && returnGoodHeaderDetailsDataDtoArrayList.size() > 0) {
//
//        }
//        return headerDetailsDtos;
//    }

    /**
     * 分割日期之后，再进行推送
     *
     * @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.info("记录splitDateAndPush方法抛出的异常", e);
        }
    }
}