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.ofspoorder.OfsPoOrderDetails;
import com.hzya.frame.ttxofs.dto.ofspoorder.OfsPoOrderHeader;
import com.hzya.frame.ttxofs.dto.stock.StockinOrderSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * 代理品牌采购业务：（代理品牌采购）OFS采购订单生成U8C采购订单
 * 不需要根据业务流程，自动生成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 ProxyPurchaseWarehousOrder extends PluginBaseEntity {

    Logger logger = LoggerFactory.getLogger(ProxyPurchaseWarehousOrder.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 OnlyImplementProxyOrderUtil onlyImplementProxyOrder;

    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @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 "purchase.ProxyPurchaseWarehousOrder";
    }

    @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)) {
                    startImplementByCode(param);
                }
            } else if (ProfilesActiveConstant.TYPE_TIME_FRAME.equals(requestJson.get("type"))) {
                //前台页面功能日期推送，或者接口调用也行
                String craeteDateStr = offsetTimeTime.computingTime(param);
                if (craeteDateStr != null && !"".equals(craeteDateStr)) {
                    splitDateAndPush(craeteDateStr);
                }
            } else {
                if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(PROD_FILED)) {
                    //默认被定时器执行，实时执行，计算时间偏移量
                    StartAndEndVo startAndEndVo = offsetTimeTime.offsetTime();
                    startImplementByTime(startAndEndVo.getStart_time(), startAndEndVo.getEnd_time());
                }
            }
        } catch (Exception e) {
            logger.error("executeBusiness方法异常", e);
        }
        long endMillis = System.currentTimeMillis();
        logger.info("executeBusiness方法调用结束：" + getPluginName() + "-插件 执行耗时：{}", (endMillis - startMillis));
        return null;
    }

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

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<OfsPoOrderData> allOfsPoOrderList = new ArrayList<>();
                    //TODO 测试，这个查询条件是假的，目前O还没有根据审批时间范围+审批状态查询的接口
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClosedAt_start(startTime);
                    queryOfsSoSaleOutVo.setClosedAt_end(endTime);
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsPoOrder(queryOfsSoSaleOutVo, allOfsPoOrderList, 1L);
                    logger.info("数据返回行数：{}", allOfsPoOrderList.size());
                    if (allOfsPoOrderList.size() > 0) {
                        getSet(allOfsPoOrderList);
                    } 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 startImplementByCode(String code) {
        long startTime = System.currentTimeMillis();
        String threadNameStrStart = StrUtil.format("（代理品牌采购）OFS采购入库单生成U8C采购订单开始 采购入库单号：{}", code);
        logger.info(threadNameStrStart);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<OfsPoOrderData> allOfsPoOrderList = new ArrayList<>();
                    QueryOfsSoSaleOutVo queryOfsSoSaleOutVo = new QueryOfsSoSaleOutVo();
                    queryOfsSoSaleOutVo.setClientCode("LETS");
                    queryOfsSoSaleOutVo.setPageNo(1L);
                    queryOfsSoSaleOutVo.setPageSize(50L);
                    queryOfsSoSaleOutVo.setCode(code);
//                    queryOfsSoSaleOutVo.setStatus(900L);
                    ofsStandardUtil.queryOfsPoOrder(queryOfsSoSaleOutVo, allOfsPoOrderList, 1L);
                    logger.info("数据返回行数：{}", allOfsPoOrderList.size());
                    if (allOfsPoOrderList.size() > 0) {
                        getSet(allOfsPoOrderList);
                    } else {
                        logger.info("没有查询到任何数据！不需要同步");
                    }
                } catch (Exception e) {
                    logger.error("startImplement方法抛出异常", e);
                }
            }
        }, threadNameStrStart);
        thread.start();
        try {
            thread.join();
        } catch (Exception e) {
            logger.error("thread.join()异常", e);
        }
        long endTime = System.currentTimeMillis();
        String threadNameStrEnd = StrUtil.format("（代理品牌采购）OFS采购入库单生成U8C采购订单结束 采购入库单号：{} 耗时：{}", code, (endTime - startTime));
        logger.info(threadNameStrEnd);
    }

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

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

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

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

                for (int i = 0; i < allOfsPoOrderList.size(); i++) {
                    OfsPoOrderData ofsPoOrderData = allOfsPoOrderList.get(i);
                    OfsPoOrderHeader header = ofsPoOrderData.getHeader();
                    List<OfsPoOrderDetails> details = ofsPoOrderData.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(ofsPoOrderData);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("过滤成功的数据抛出异常", e);
            String message = e.getMessage();
            if (message == null || "".equals(message)) {
                message = "未知错误";
            }
            Assert.state(false, "过滤成功的数据抛出异常 原因：{}", message);
        }
        return headerDetailsDtoList1;
    }

    /**
     * 字段拼接
     *
     * @param ofsPoOrderDataList O采购订单
     */
    private String fieldConcaten(List<OfsPoOrderData> ofsPoOrderDataList) {
        if (ofsPoOrderDataList != null && ofsPoOrderDataList.size() > 0) {
            StringBuilder result = new StringBuilder();
            for (OfsPoOrderData obj : ofsPoOrderDataList) {
                OfsPoOrderHeader 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<OfsPoOrderData> returnGoodHeaderDetailsDataDtoList) throws Exception {
        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            try {
                // 查询基本档案
                List<PoOrderSonDtoV2> poOrderSonDtoV2s = queryBasicArchives(returnGoodHeaderDetailsDataDtoList);
                // 代理品牌采购业务流程
                BdBusitypeEntity bdBusitypeEntity = u8cOperationFlow();
                // 查询采购收发类别
                BdRdclEntity bdRdclEntity = rdclUtil.queryRdClObject("102");

                if (poOrderSonDtoV2s != null && poOrderSonDtoV2s.size() > 0) {
                    for (int i = 0; i < poOrderSonDtoV2s.size(); i++) {
                        PoOrderSonDtoV2 poOrderSonDtoV2 = poOrderSonDtoV2s.get(i);
                        List<OfsPoOrderDetails> details = poOrderSonDtoV2.getDetails();

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

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

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

                            //采购订单表头
                            PoOrderParentDto poOrderParentDto = new PoOrderParentDto();
                            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(poOrderSonDtoV2.getCode());//原单单号
                            poOrderParentDto.setVdef20(poOrderSonDtoV2.getId());//原单主键

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

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

                            for (int j = 0; j < details.size(); j++) {
                                OfsPoOrderDetails ofsPoOrderDetails = details.get(j);
//                                OfsPoOrderDetails ofsPoOrderDetail = findOfsPoOrderDetail(ofsPoOrderDataDetails, stockinB);

                                //TODO 测试
//                                stockinB.setReceivedQty("1");
//                                ofsPoOrderDetail.setFulfillAmount("10");

                                //2024年8月20日 16:02:21 已经和妮姐、万万确认，采购公司和收货公司目前是一致的，暂时不用区分取数逻辑
                                BdInvmandocEntity bdInvmandocEntity = queryInventoryMan(ofsPoOrderDetails, bdCorpEntity.getPkCorp());
                                String receivedQty = ofsPoOrderDetails.getRequestQty();//请求数量
                                String buyPrice = ofsPoOrderDetails.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(receivedQty);//订货数量
                                poOrderChildrenDto.setNorgtaxprice(new BigDecimal(buyPrice).setScale(4, BigDecimal.ROUND_HALF_UP).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, bdCorpEntity.getUnitcode(), bdCorpEntity.getUnitname(), vordercode);

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

    /**
     * 档案转换
     *
     * @author liuyang
     */
    private List<PoOrderSonDtoV2> queryBasicArchives(List<OfsPoOrderData> returnGoodHeaderDetailsDataDtoList) {
        List<PoOrderSonDtoV2> poOrderSonDtoArrayList = new ArrayList<>();

        if (returnGoodHeaderDetailsDataDtoList != null && returnGoodHeaderDetailsDataDtoList.size() > 0) {
            try {
                for (int i = 0; i < returnGoodHeaderDetailsDataDtoList.size(); i++) {
                    OfsPoOrderData ofsPoOrderData1 = returnGoodHeaderDetailsDataDtoList.get(i);
                    OfsPoOrderHeader header = ofsPoOrderData1.getHeader();
                    List<OfsPoOrderDetails> details = ofsPoOrderData1.getDetails();

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

                        //查询OFS采购订单
//                        OfsPoOrderData ofsPoOrderData = ofsStandardUtil.queryOfsPoOrder(header.getRefOrderCode());
//                        Assert.notNull(ofsPoOrderData, "根据O表头编码{}，无法匹配到OFS采购订单", header.getRefOrderCode());
                        boolean checkResult = onlyImplementProxyOrder.onlyImplementProxyOrder(ofsPoOrderData1, "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 = header.getVendorName();
                        //TODO 测试
                        shipFromCode = "dy-off";
                        Assert.notNull(shipFromCode, "O供应商编码不能为空，没有办法完成业务逻辑，请配置供应商编码(采购)");
                        Assert.state(!"".equals(shipFromCode.trim()), "O供应商编码不能为空，没有办法完成业务逻辑，请配置供应商编码(采购)！");
                        BdCubasdocEntity bdCubasdocEntity = new BdCubasdocEntity();
                        bdCubasdocEntity.setDataSourceCode("lets_u8c");
                        bdCubasdocEntity.setDr(0L);
                        bdCubasdocEntity.setDef1(shipFromCode);
                        List<BdCubasdocEntity> bdCubasdocEntityList = iBdCubasdocDao.query(bdCubasdocEntity);
                        if (bdCubasdocEntityList == null || bdCubasdocEntityList.size() == 0) {
                            Assert.state(false, "根据OFS供应商业务编码{}，无法查询到U8C客商档案信息(供应商)", shipFromCode);
                        } else if (bdCubasdocEntityList.size() >= 2) {
                            Assert.state(false, "根据OFS供应商业务编码{}，查询到多个U8C客商档案信息(供应商)", shipFromCode);
                        }

                        //客商管理档案
                        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());
                        }

                        PoOrderSonDtoV2 poOrderSonDto = new PoOrderSonDtoV2();
                        poOrderSonDto.setBdCorpEntity(bdCorpEntityList.get(0));
                        poOrderSonDto.setBdDeptdocEntity(bdDeptdocEntityList.get(0));
                        poOrderSonDto.setBdPurorgEntity(bdPurorgEntityList.get(0));
                        poOrderSonDto.setBdCubasdocEntity(bdCubasdocEntityList.get(0));
                        poOrderSonDto.setBdCumandocEntity(bdCumandocEntityList.get(0));
//                        poOrderSonDto.setOfsPoOrderData(ofsPoOrderData);
                        poOrderSonDto.setBdCalbodyEntity(bdCalbodyEntities.get(0));
                        poOrderSonDto.setBdStordocEntity(bdStordocEntityList.get(0));
                        poOrderSonDto.setDetails(details);

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

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

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

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

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

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

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

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

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

            if (param.contains("*")) {
                String[] params = param.split("\\*");
                if (params.length > 0) {
                    for (int i = 0; i < params.length; i++) {
                        String indexStr = params[i];
                        String[] split = indexStr.split(",");
                        startImplementByTime(split[0], split[1]);
                    }
                }
            } else {
                String[] split = param.split(",");
                startImplementByTime(split[0], split[1]);
            }
        } catch (Exception e) {
            logger.info("记录splitDateAndPush方法抛出的异常", e);
        }
    }
}