package com.jwipc.order.api.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.constant.DelFlag;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.FlagConst;
import com.jwipc.log.annotation.ApiOperateLog;
import com.jwipc.log.constant.ApiDirection;
import com.jwipc.log.constant.ThirdSysType;
import com.jwipc.order.api.dto.*;
import com.jwipc.order.api.logic.CreatePurchaseOrderLogic;
import com.jwipc.order.constant.PurchaseOrderStatus;
import com.jwipc.order.convert.PurchaseOrderDetailConvert;
import com.jwipc.order.entity.*;
import com.jwipc.order.service.*;
import com.jwipc.prop.PriceHandle;
import com.jwipc.supplier.clent.dto.SupplierContactsDTO;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.*;
import com.jwipc.sys.client.dto.*;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;
import static com.jwipc.util.DateUtils.yyyyMMdd;
import static com.jwipc.util.DateUtils.yyyyMMddDash;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CreatePurchaseOrderLogicImpl implements CreatePurchaseOrderLogic {
    private final IPurchaseOrderService purchaseOrderService;
    private final IPurchaseOrderDetailService purchaseOrderDetailService;
    private final IDeliveryOrderService deliveryOrderService;
    private final IDeliveryOrderDetailService deliveryOrderDetailService;
    private final IPurchaseOrderDetailComponentService purchaseOrderDetailComponentService;
    private final IPurchaseOrderDetailCostService purchaseOrderDetailCostService;
    private final IPurchaseOrderDevPlanService purchaseOrderDevPlanService;
    private final DictClient dictClient;
    private final SupplierClient supplierClient;
    private final PurchaseOrgClient purchaseOrgClient;
    private final PurchaseGroupClient purchaseGroupClient;
    private final CompanyClient companyClient;
    private final FactoryClient factoryClient;
    private final ProductClient productClient;
    private final TaxClient taxClient;
    private final UserClient userClient;
    private final IPurchaseOrderModifyService purchaseOrderModifyService;
    private final PriceHandle priceHandle;
    private final PurchaseOrderDetailConvert purchaseOrderDetailConvert;
    private final EmailSendClient emailSendClient;
    private final IPurchaseOrderSummaryService purchaseOrderSummaryService;
    Set<String> deliveryFlag = Sets.newHashSet("Z001", "Z006", "Z007", "Z008","Z012");//需要创建送货单的类型
    Set<String> supplierVisible = Sets.newHashSet("Z001", "Z003", "Z005", "Z006", "Z008", "Z004", "Z009","Z012");//供应商可见类型
    Set<String> statusAuto = Sets.newHashSet("Z003", "Z005", "Z006", "Z007", "Z004", "Z009","Z010","Z012");

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ApiOperateLog(code = "createPurchaseOrder", name = "创建采购订单", direction = ApiDirection.OTHER_TO_SRM,
            thirdSysType = ThirdSysType.SAP)
    @DS(SLAVE)
    public ApiResult createPurchaseOrder(CreatePurchaseOrderDTO createPurchaseOrderDTO) {
        final PurchaseOrderDTO itHead = createPurchaseOrderDTO.getIT_HEAD();
        String factoryCode = StrUtil.EMPTY;
        boolean isSendEmailFlag = false;
        boolean isNewlFlag = false;
        //校验币种
        final String waers = itHead.getWAERS();
        final DictDTO cny = dictClient.getDictByTypeAndCode(DictCode.CURRENCY.getCode(), waers);
        if (Objects.isNull(cny)) {
            return ApiResult.builder().message(StrUtil.format("{},币种不存在!", waers))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //校验付款条件
        final String zterm = itHead.getZTERM();
        final DictDTO paymentTermsDTO = dictClient.getDictByTypeAndCode(DictCode.PAYMENT_TERMS.getCode(), zterm);
        if (Objects.isNull(paymentTermsDTO)) {
            return ApiResult.builder().message(StrUtil.format("{},付款条款不存在!", zterm))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //校验供应商编码
        final String lifnr = itHead.getLIFNR();
        ArrayList<String> codes = new ArrayList<>();
        codes.add(lifnr);
        final List<SupplierDTO> supplierByCodes = supplierClient.getSupplierByCodes(codes);
        //  final SupplierDTO supplierByCode = supplierClient.getSupplierByCodes(codes);
        if (CollUtil.isEmpty(supplierByCodes) || supplierByCodes.size() > 1) {
            return ApiResult.builder().message(StrUtil.format("{},供应商不存在!", lifnr))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //采购组织校验
        final String ekorg = itHead.getEKORG();
        final PurchaseOrgDTO purchaseOrgDTO = purchaseOrgClient.getByCode(ekorg);
        if (Objects.isNull(purchaseOrgDTO)) {
            return ApiResult.builder().message(StrUtil.format("{},采购组织不存在!", ekorg))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //采购组校验
        final String ekgrp = itHead.getEKGRP();
        final PurchaseGroupDTO purchaseGroupDTO = purchaseGroupClient.getByCode(ekgrp);
        if (Objects.isNull(purchaseGroupDTO)) {
            return ApiResult.builder().message(StrUtil.format("{},采购组不存在!", ekgrp))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //采购订单类型校验
        final String bsart = itHead.getBSART();
        final DictDTO poType = dictClient.getDictByTypeAndCode(DictCode.PO_TYPE.getCode(), bsart);
        if (Objects.isNull(poType)) {
            return ApiResult.builder().message(StrUtil.format("{},采购订单类型不存在!", bsart))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //公司代码校验
        final String bukrs = itHead.getBUKRS();
        final CompanyDTO companyDTO = companyClient.getByCode(bukrs);
        if (Objects.isNull(companyDTO)) {
            return ApiResult.builder().message(StrUtil.format("{},公司代码不存在!", bukrs))
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //校验明细中的数据
        final List<PurchaseOrderItemDTO> itItem = createPurchaseOrderDTO.getIT_ITEM();
        if (CollUtil.isEmpty(itItem)) {
            return ApiResult.builder().message("订单明细为空！")
                    .code(RestCode.SAP_ERROR.getCode()).build();
        }
        //物料数据缓存 key=factory_code+material_code
        Map<String, ProductInfoDTO> productCache = Maps.newHashMap();
        final List<FactoryDTO> all = factoryClient.getAll();
        final Map<String, FactoryDTO> factoryCache = all.stream()
                .collect(Collectors.toMap(FactoryDTO::getFactory, a -> a));
        final Set<String> factoryCodes = factoryCache.keySet();
        final List<DictDTO> units = dictClient.getDicByType(DictCode.UNIT.getCode());
        final Map<String, DictDTO> unitCache = units.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));
        //税码缓存
        final List<TaxDTO> taxDTOS = taxClient.getAll();
        final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, a -> a));
        final Set<String> taxCodes = taxCache.keySet();
        Map<String, StockLocationDTO> stockLocationCache = Maps.newHashMap();
        final Set<String> unitCodes = unitCache.keySet();
        for (PurchaseOrderItemDTO purchaseOrderItemDTO : itItem) {
            //工厂校验
            final String werks = purchaseOrderItemDTO.getWERKS();
            factoryCode = werks;
            if (!factoryCodes.contains(werks)) {
                return ApiResult.builder().message(StrUtil.format("{},工厂不存在!", werks))
                        .code(RestCode.SAP_ERROR.getCode()).build();
            }
            //物料校验
            final String matnr = purchaseOrderItemDTO.getMATNR();
            if (StrUtil.isNotEmpty(matnr)) {
                final ProductInfoDTO cacheVal = productCache.get(werks + matnr);
                if (Objects.isNull(cacheVal)) {
                    ProductInfoDTO productInfoDTO = productClient.getByMaterialCodeAndFactoryCode(matnr, werks);
                    if (Objects.isNull(productInfoDTO)) {
                        return ApiResult.builder().message(StrUtil.format("{},物料不存在!", matnr))
                                .code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    productCache.put(werks + matnr, productInfoDTO);
                }
            }
            if (StrUtil.isNotEmpty(purchaseOrderItemDTO.getLOEKZ())) {
                continue;
            }
            //校验税码
            final String mwskz = purchaseOrderItemDTO.getMWSKZ();
            if (!taxCodes.contains(mwskz)) {
                return ApiResult.builder().message(StrUtil.format("{},税码不存在!", mwskz))
                        .code(RestCode.SAP_ERROR.getCode()).build();
            }
            //校验单位
            final String meins = purchaseOrderItemDTO.getMEINS();
            if (!unitCodes.contains(meins)) {
                return ApiResult.builder().message(StrUtil.format("{},订单单位不存在!", meins))
                        .code(RestCode.SAP_ERROR.getCode()).build();
            }
            //校验库存地点
//            final String lgort = purchaseOrderItemDTO.getLGORT();
//            if (StrUtil.isNotEmpty(lgort)) {
//                final StockLocationDTO stockLocationDTO = stockLocationCache.get(lgort);
//                if (Objects.isNull(stockLocationDTO)) {
//                    final StockLocationDTO locationDTO = stockLocationClient.getByCode(lgort);
//                    if (Objects.isNull(locationDTO)) {
//                        return ApiResult.builder().message(StrUtil.format("{},库存地点不存在!", lgort))
//                                .code(RestCode.SAP_ERROR.getCode()).build();
//                    }
//                    stockLocationCache.put(lgort, locationDTO);
//                }
//            }
        }
        //需要插入数据

        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setOrderCode(itHead.getEBELN());
        purchaseOrder.setRemark(itHead.getBKTXT());
        purchaseOrder.setMarkFlag(itHead.getZZJHLX());//订单交货类型
        purchaseOrder.setCurrencyCode(waers);
        purchaseOrder.setCurrencyName(cny.getName());
        purchaseOrder.setCreateTime(LocalDateTimeUtil.parse(itHead.getAEDAT(), yyyyMMdd));
        //订单类型，需要关联字典查询
        purchaseOrder.setOrderTypeCode(itHead.getBSART());
        purchaseOrder.setOrderTypeName(poType.getName());

        //供应商账号需要关联供应商查询id和名称
        purchaseOrder.setSupplierErpCode(itHead.getLIFNR());
        purchaseOrder.setSupplierId(supplierByCodes.get(0).getId());
        final String supplierName = supplierByCodes.get(0).getSupplierName();
        purchaseOrder.setSupplierName(supplierName);
        if (StrUtil.isNotEmpty(itHead.getLIFNR2())) {
            final SupplierDTO supplierByCode1 = supplierClient.getSupplierByCode(itHead.getLIFNR2());
            purchaseOrder.setSupplierCode1(itHead.getLIFNR2());
            purchaseOrder.setSupplierName1(supplierByCode1.getSupplierName());
        } else {
            purchaseOrder.setSupplierCode1(StrUtil.EMPTY);
            purchaseOrder.setSupplierName1(StrUtil.EMPTY);
        }
        if (StrUtil.isNotEmpty(itHead.getLIFNR3())) {
            final SupplierDTO supplierByCode1 = supplierClient.getSupplierByCode(itHead.getLIFNR3());
            purchaseOrder.setSupplierCode2(itHead.getLIFNR2());
            purchaseOrder.setSupplierName2(supplierByCode1.getSupplierName());
        } else {
            purchaseOrder.setSupplierCode2(StrUtil.EMPTY);
            purchaseOrder.setSupplierName2(StrUtil.EMPTY);
        }

        //采购组织需要查询采购组织的名称
        purchaseOrder.setPurchaseOrgCode(itHead.getEKORG());
        purchaseOrder.setPurchaseOrgName(purchaseOrgDTO.getPurchaseOrgDesc());
        final String ernam = itHead.getERNAM();//创建人
        purchaseOrder.setCreateWorkNo(ernam);
        final UserDTO byAccount = userClient.getByAccount(ernam);
        if (Objects.nonNull(byAccount)) {
            purchaseOrder.setCreateId(byAccount.getId());
            purchaseOrder.setCreateName(byAccount.getUsername());
        }
        //查询公司代码，需要查询公司名称
        purchaseOrder.setCompanyCode(itHead.getBUKRS());
        purchaseOrder.setCompanyName(companyDTO.getCompanyName());
        purchaseOrder.setOrderDate(itHead.getAEDAT());
        //查询采购组织，需要查询采购组名称
        purchaseOrder.setPurchaseGroupCode(itHead.getEKGRP());
        purchaseOrder.setPurchaseGroupName(purchaseGroupDTO.getPurchaseGroupName());
        purchaseOrder.setOrderAmount(new BigDecimal(itHead.getKWERT()));
        purchaseOrder.setOrderTaxAmount(new BigDecimal(itHead.getKWERT()));
        //查询付款条件，需要查询付款条件名称
        purchaseOrder.setPaymentMethodName(paymentTermsDTO.getName());
        purchaseOrder.setPaymentMethod(paymentTermsDTO.getCode());
        purchaseOrder.setBgFlag(itHead.getZZZLBG());

        //需要查询是否存在之前的数据，如果存在是修改，如果不存在是新增
        final PurchaseOrder dbOrder = purchaseOrderService.getOne(
                new LambdaQueryWrapper<PurchaseOrder>().eq(PurchaseOrder::getOrderCode, purchaseOrder.getOrderCode()));
        //需要处理是否可以创建送货单，和供应商是否能看到
        final String orderTypeCode = purchaseOrder.getOrderTypeCode();
        if (Objects.nonNull(dbOrder)) {
            //抬头工厂取数逻辑：取未删除订单明细的工厂，如果订单明细全部给删除，就取抬头公司
            purchaseOrder.setFactoryCode(itHead.getBUKRS());
            purchaseOrder.setId(dbOrder.getId());
            if (Objects.nonNull(itHead.getZZHQBS()) && itHead.getZZHQBS().equals("X")) {
                final PurchaseOrderModify purchaseOrderModify = new PurchaseOrderModify();
                purchaseOrderModify.setCreateTime(LocalDateTime.now());
                purchaseOrderModify.setOrderId(dbOrder.getId());
                purchaseOrderModifyService.save(purchaseOrderModify);
                //需要处理状态
                if (statusAuto.contains(orderTypeCode)) {
                    if (orderTypeCode.equals("Z006")||orderTypeCode.equals("Z012")) {
                        if (ekgrp.equals("406")) {
                            purchaseOrder.setState(PurchaseOrderStatus.CONFIRMATION_COMPLETED.getStatus());
                        } else {
                            purchaseOrder.setState(PurchaseOrderStatus.AWAITING_SUPPLIER_CONFIRMATION.getStatus());
                            isSendEmailFlag = true;
                            isNewlFlag = false;
                        }
                    } else {
                        purchaseOrder.setState(PurchaseOrderStatus.CONFIRMATION_COMPLETED.getStatus());
                    }
                    purchaseOrder.setFileState(FlagConst.Y.getCode());
                    purchaseOrder.setFinConf(FlagConst.Y.getCode());
                } else {
                    purchaseOrder.setState(PurchaseOrderStatus.AWAITING_SUPPLIER_CONFIRMATION.getStatus());
                    purchaseOrder.setFileState(FlagConst.N.getCode());
                    purchaseOrder.setFinConf(FlagConst.N.getCode());
                    isSendEmailFlag = true;
                    isNewlFlag = false;
                }
                purchaseOrder.setPrintFlag(FlagConst.N.getCode());
                purchaseOrder.setFinUserId(null);
                purchaseOrder.setFinTime(null);
                purchaseOrder.setRefusalRemark(StrUtil.EMPTY);
                //需要单独更新订单中的财务确认人和财务确认时间 2024-08-21注释掉
//                purchaseOrderService.update(new LambdaUpdateWrapper<PurchaseOrder>()
//                        .set(PurchaseOrder::getFinTime, null)
//                        .set(PurchaseOrder::getFinUserId, null)
//                        .eq(PurchaseOrder::getOrderCode, purchaseOrder.getOrderCode()));
                //2024-08-18 增加修改打印批次订单打印标识为未打印,清空批次号,这里是否需要将财务确认时间，财务确认时间等一起清空，财务确认人清空，回签状态，财务确认状态重置???

                purchaseOrderService.update(new LambdaUpdateWrapper<>(PurchaseOrder.class).set(PurchaseOrder::getPrintFlag,FlagConst.N.getCode()).set(PurchaseOrder::getBatchNo,StrUtil.EMPTY).eq(PurchaseOrder::getId,dbOrder.getId()));
                //2024-08-19 增加订单发送变更删除批次汇总表数据
                //   purchaseOrderSummaryService.remove(new LambdaUpdateWrapper<>(PurchaseOrderSummary.class).eq(PurchaseOrderSummary::getOrderId,dbOrder.getCreateId()));
            } else if (Objects.nonNull(itHead.getFRGKE()) && itHead.getFRGKE().equals("R")) {
                if (dbOrder.getState().equals(PurchaseOrderStatus.ORDER_BPM_APPROVAL_IN_PROGRESS.getStatus())) {
                    if (Objects.nonNull(dbOrder.getTmpState())) {
                        purchaseOrder.setState(dbOrder.getTmpState());
                    }
                }
            } else if (Objects.nonNull(itHead.getFRGKE()) && itHead.getFRGKE().equals("B")) {
                final Integer state = dbOrder.getState();
                //增加防止重复传入B的问题
                if (state.equals(PurchaseOrderStatus.ORDER_BPM_APPROVAL_IN_PROGRESS.getStatus())) {
                    //为了后续往下走，对于新增和删除的送货明细可以继续处理
//                    return ApiResult.builder().
//
//                            code(RestCode.SAP_SUCCESS.getCode()).
//
//                            build();
                } else {
                    purchaseOrder.setState(PurchaseOrderStatus.ORDER_BPM_APPROVAL_IN_PROGRESS.getStatus());
                    purchaseOrder.setTmpState(state);
                }
            }
            purchaseOrder.setColumn3( itHead.getZZXHDD());
            purchaseOrderService.saveOrUpdate(purchaseOrder);
        } else {

            if (deliveryFlag.contains(orderTypeCode)) {
                purchaseOrder.setDeliveryFlag(FlagConst.Y.getCode());

            } else {
                purchaseOrder.setDeliveryFlag(FlagConst.N.getCode());
            }
            if (supplierVisible.contains(orderTypeCode)) {
                purchaseOrder.setSupplierVisible(FlagConst.Y.getCode());
            } else {
                purchaseOrder.setSupplierVisible(FlagConst.N.getCode());
            }
            //需要处理状态
            if (statusAuto.contains(orderTypeCode)) {
                if (orderTypeCode.equals("Z006")||orderTypeCode.equals("Z012")) {
                    if (ekgrp.equals("406")) {
                        purchaseOrder.setState(PurchaseOrderStatus.CONFIRMATION_COMPLETED.getStatus());
                    } else {
                        purchaseOrder.setState(PurchaseOrderStatus.AWAITING_SUPPLIER_CONFIRMATION.getStatus());
                        isSendEmailFlag = true;
                        isNewlFlag = true;
                    }
                } else {
                    purchaseOrder.setState(PurchaseOrderStatus.CONFIRMATION_COMPLETED.getStatus());
                }
                purchaseOrder.setFileState(FlagConst.Y.getCode());
                purchaseOrder.setFinConf(FlagConst.Y.getCode());
            } else {
                purchaseOrder.setState(PurchaseOrderStatus.AWAITING_SUPPLIER_CONFIRMATION.getStatus());
                purchaseOrder.setFileState(FlagConst.N.getCode());
                purchaseOrder.setFinConf(FlagConst.N.getCode());
                isSendEmailFlag = true;
                isNewlFlag = true;
            }
            purchaseOrder.setColumn3( itHead.getZZXHDD());

            //抬头工厂取数逻辑：取未删除订单明细的工厂，如果订单明细全部给删除，就取抬头公司
            if(!CollectionUtils.isEmpty(itItem)){
                purchaseOrder.setFactoryCode(itItem.get(0).getWERKS());
            }else{
                purchaseOrder.setFactoryCode(itHead.getBUKRS());
            }
            purchaseOrderService.save(purchaseOrder);
            final PurchaseOrderModify purchaseOrderModify = new PurchaseOrderModify();
            purchaseOrderModify.setCreateTime(LocalDateTime.now());
            purchaseOrderModify.setOrderId(purchaseOrder.getId());
            purchaseOrderModifyService.save(purchaseOrderModify);
        }

        //保存明细
        final Iterator<PurchaseOrderItemDTO> iterator = itItem.iterator();
        Map<String, String> EINDT2Cache = new HashMap<>();
        while (iterator.hasNext()) {
            final PurchaseOrderItemDTO next = iterator.next();
            PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
            //需要查询是否存在如果存在需要把id放进去
            PurchaseOrderDetail dbDetail = purchaseOrderDetailService.getOne(
                    new LambdaQueryWrapper<PurchaseOrderDetail>()
                            .eq(PurchaseOrderDetail::getOrderCode, purchaseOrder.getOrderCode())
//                            .eq(PurchaseOrderDetail::getDelFlag, 0)
                            .eq(PurchaseOrderDetail::getOrderRow, next.getEBELP()), false);
            if (Objects.nonNull(dbDetail)) {
                //判断当前的工厂和传入的工厂是否一致，如果不一致需要做分片迁移
                if (!next.getWERKS().equals(dbDetail.getFactoryCode())) {
                    purchaseOrderDetailService.removeById(dbDetail.getId());
                    dbDetail = null;
                    purchaseOrderDetail = purchaseOrderDetailConvert.fill(dbDetail, purchaseOrderDetail);
                    purchaseOrderDetail.setOrderCode(purchaseOrder.getOrderCode());
                    purchaseOrderDetail.setId(IdWorker.getId());
                } else {
                    purchaseOrderDetail.setOrderCode(purchaseOrder.getOrderCode());
                    purchaseOrderDetail.setId(dbDetail.getId());
                }

            } else {
                purchaseOrderDetail.setOrderCode(purchaseOrder.getOrderCode());
                purchaseOrderDetail.setId(IdWorker.getId());
            }
            purchaseOrderDetail.setOrderId(purchaseOrder.getId());
            purchaseOrderDetail.setMiddleClass(next.getZWLZLMS());
            purchaseOrderDetail.setSupplierErpCode(purchaseOrder.getSupplierErpCode());
            purchaseOrderDetail.setOrderRow(String.valueOf(Integer.parseInt(next.getEBELP())));
            //创建人
            purchaseOrderDetail.setCreateName(purchaseOrder.getCreateName());
            String banfn = next.getBANFN();
            String bnfpo = next.getBNFPO();
            if (Objects.nonNull(banfn)) {
                purchaseOrderDetail.setPurchApplyNo(banfn.trim());
            }
            if (Objects.nonNull(bnfpo)) {
                purchaseOrderDetail.setPurchApplyRow(bnfpo.trim());
            }
            purchaseOrderDetail.setRemark(next.getBUTXT());
            //如果是退货需要把数量变成负数
            if(StringUtils.isNotEmpty(next.getRETPO())){
                purchaseOrderDetail.setReturnFlag(next.getRETPO());//退货标识
            }else{
                purchaseOrderDetail.setReturnFlag("");//退货标识
            }
            purchaseOrderDetail.setNum(new BigDecimal(next.getMENGE().trim()));
            if (StrUtil.isNotEmpty(next.getRETPO()) && next.getRETPO().equals("X")) {
                final BigDecimal num = purchaseOrderDetail.getNum().multiply(BigDecimal.valueOf(-1));
                purchaseOrderDetail.setNum(num);
            }
            purchaseOrderDetail.setReceivedNum(next.getMENGE_SH());
            //计算未清数量
            BigDecimal receivedNum = BigDecimal.ZERO;
            if (StrUtil.isNotEmpty(purchaseOrderDetail.getReceivedNum())) {
                receivedNum = new BigDecimal(purchaseOrderDetail.getReceivedNum());
            }
            if (StrUtil.isNotEmpty(next.getRETPO()) && next.getRETPO().equals("X")) {
                purchaseOrderDetail.setNoClearNum(purchaseOrderDetail.getNum().add(receivedNum));
            } else {
                purchaseOrderDetail.setNoClearNum(purchaseOrderDetail.getNum().subtract(receivedNum));
            }
            purchaseOrderDetail.setMaterialCode(next.getMATNR());
            purchaseOrderDetail.setMaterialName(next.getTXZ01());
            //工厂，需要查询工厂名称
            purchaseOrderDetail.setFactoryCode(next.getWERKS());
            final FactoryDTO factoryDTO = factoryCache.get(purchaseOrderDetail.getFactoryCode());
            purchaseOrderDetail.setFactoryName(factoryDTO.getName());
            //库存地点，需要查询库存地点名称
            purchaseOrderDetail.setStockCode(next.getLGORT());
            if (Objects.nonNull(purchaseOrderDetail.getStockCode())) {
                final StockLocationDTO stockLocationDTO = stockLocationCache.get(next.getLGORT());
                if (Objects.nonNull(stockLocationDTO)) {
                    purchaseOrderDetail.setStockName(stockLocationDTO.getLocationDesc());
                }
            }
            final String productCode = next.getMATKL();
            //需要查询物料组数据
            purchaseOrderDetail.setMaterialGroupCode(productCode);
            purchaseOrderDetail.setMaterialGroupName(next.getWGBEZ());
            //订单单位，需要查询单位名称
            purchaseOrderDetail.setUnitCode(next.getMEINS());
            final DictDTO unitIt = unitCache.get(purchaseOrderDetail.getUnitCode());
            purchaseOrderDetail.setUnitName(unitIt.getName());
            //税码，需要查询名称还有税率值
            final TaxDTO taxDTO = taxCache.get(next.getMWSKZ());
            if (Objects.isNull(taxDTO)) {
                purchaseOrderDetail.setTaxValue(BigDecimal.ZERO);
                purchaseOrderDetail.setTaxName(StrUtil.EMPTY);
                purchaseOrderDetail.setTaxCode(StrUtil.EMPTY);
            } else {
                purchaseOrderDetail.setTaxCode(next.getMWSKZ());
                purchaseOrderDetail.setTaxValue(taxDTO.getTaxValue().multiply(BigDecimal.valueOf(100)));
                final String itemName = taxDTO.getTaxName();
                purchaseOrderDetail.setTaxName(itemName);
            }

            if (StrUtil.isNotEmpty(next.getZKBETR_GS())) {
                purchaseOrderDetail.setTariff(new BigDecimal(next.getZKBETR_GS()).stripTrailingZeros().toPlainString());
            } else {
                purchaseOrderDetail.setTariff(next.getZKBETR_GS());
            }

            purchaseOrderDetail.setWebre(next.getWEBRE());
            //需要计算价格信息
            final BigDecimal netpr = new BigDecimal(next.getKBETR().trim());
            final BigDecimal netwr = new BigDecimal(next.getNETWR().trim());
            final BigDecimal peinh = new BigDecimal(next.getKPEIN().trim());
            if (netpr.compareTo(BigDecimal.ZERO) != 0 && peinh.compareTo(BigDecimal.ZERO) > 0) {
                final BigDecimal price = netpr.divide(peinh, priceHandle.getPrecision(), priceHandle.getRoundingMode());
                final BigDecimal netPrice = netwr.divide(peinh, priceHandle.getPrecision(),
                        priceHandle.getRoundingMode());
                purchaseOrderDetail.setPrice(price);
                purchaseOrderDetail.setNetPrice(netPrice);
            } else if (netpr.compareTo(BigDecimal.ZERO) == 0 || peinh.compareTo(BigDecimal.ZERO) == 0) {
                purchaseOrderDetail.setTaxAmount(BigDecimal.ZERO);
                purchaseOrderDetail.setSumTaxMoney(BigDecimal.ZERO);
                purchaseOrderDetail.setPrice(BigDecimal.ZERO);
                purchaseOrderDetail.setNetPrice(BigDecimal.ZERO);
                purchaseOrderDetail.setAmount(BigDecimal.ZERO);
            }
            purchaseOrderDetail.setTaxAmount(new BigDecimal(next.getKWERT().trim()));
            purchaseOrderDetail.setSumTaxMoney(new BigDecimal(next.getKWERT().trim()));
            final BigDecimal taxRate = purchaseOrderDetail.getTaxValue().add(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(100), priceHandle.getPrecision(), priceHandle.getRoundingMode());
            purchaseOrderDetail.setAmount(
                    purchaseOrderDetail.getTaxAmount()
                            .divide(taxRate, priceHandle.getPrecision(), priceHandle.getRoundingMode()));
//            if (StrUtil.isNotEmpty(next.getEINDT())) {
//                purchaseOrderDetail.setRequireDate(DateUtil.parse(next.getEINDT(), yyyyMMdd).toString(yyyyMMddDash));
//            } else {
//                purchaseOrderDetail.setRequireDate(null);
//            }
            if (StrUtil.isNotEmpty(next.getEINDT2())) {
                final String date = DateUtil.parse(next.getEINDT2(), yyyyMMdd).toString(yyyyMMddDash);
                purchaseOrderDetail.setOriginalRequireDate(
                        date);
                EINDT2Cache.put(purchaseOrderDetail.getOrderCode() + purchaseOrderDetail.getOrderRow(),
                        next.getEINDT2());
            }

            purchaseOrderDetail.setFinishFlag(
                    Objects.nonNull(next.getELIKZ()) &&
                            next.getELIKZ().equals("X") ? FlagConst.Y.getLabel() : FlagConst.N.getLabel());
            if (Objects.nonNull(next.getLOEKZ())) {
                if (StrUtil.isNotEmpty(next.getLOEKZ())) {
                    purchaseOrderDetail.setDelFlag(DelFlag.DELETE.getStatus());
                } else {
                    purchaseOrderDetail.setDelFlag(DelFlag.NORMAL.getStatus());
                }
            } else {
                purchaseOrderDetail.setDelFlag(DelFlag.NORMAL.getStatus());
            }
            purchaseOrderDetail.setDefaultStock(next.getZCHUW());//默认储位
            //科目类别需要查询名称
            purchaseOrderDetail.setSubjectTypeCode(next.getZEKKN());
            //项目类别号需要查询名称
            purchaseOrderDetail.setRowTypeCode(next.getPSTYP());

            if (Objects.nonNull(dbDetail)) {
                //2024-11-13 更新订单信息时不修改需求日期
                purchaseOrderDetail.setRequireDate(null);
                purchaseOrderDetailService.update(purchaseOrderDetail, new LambdaQueryWrapper<PurchaseOrderDetail>()
                        .eq(PurchaseOrderDetail::getId, purchaseOrderDetail.getId())
                        .eq(PurchaseOrderDetail::getFactoryCode, purchaseOrderDetail.getFactoryCode()));
            } else {
                purchaseOrderDetailService.save(purchaseOrderDetail);
            }
        }

        //需要保存组件信息
        final List<PurchaseOrderComponentDTO> PurchaseOrderComponentDTOs = Objects.nonNull(
                createPurchaseOrderDTO.getRESB()) ? createPurchaseOrderDTO.getRESB() : Lists.newArrayList();
        List<PurchaseOrderDetailComponent> purchaseOrderDetailComponents = Lists.newArrayList();
        purchaseOrderDetailComponentService.remove(new LambdaUpdateWrapper<>(PurchaseOrderDetailComponent.class)
                .eq(PurchaseOrderDetailComponent::getPurchaseOrder, purchaseOrder.getOrderCode()));
        for (
                PurchaseOrderComponentDTO purchaseOrderComponentDTO : PurchaseOrderComponentDTOs) {
            PurchaseOrderDetailComponent purchaseOrderDetailComponent = new PurchaseOrderDetailComponent();
            purchaseOrderDetailComponent.setPurchaseOrder(purchaseOrderComponentDTO.getEBELN());
            purchaseOrderDetailComponent.setLineItem(purchaseOrderComponentDTO.getEBELP());
            purchaseOrderDetailComponent.setComponentMaterialName(purchaseOrderComponentDTO.getMAKTX());
            purchaseOrderDetailComponent.setComponentMaterialCode(purchaseOrderComponentDTO.getMATNR());
            purchaseOrderDetailComponent.setUnitOfMeasure(purchaseOrderComponentDTO.getERFME());
            purchaseOrderDetailComponent.setRspos(purchaseOrderComponentDTO.getRSPOS());
            purchaseOrderDetailComponent.setRsnum(purchaseOrderComponentDTO.getRSNUM());
            purchaseOrderDetailComponent.setPlanLine(purchaseOrderComponentDTO.getEBELE());
            purchaseOrderDetailComponent.setRequiredQuantity(purchaseOrderComponentDTO.getERFMG());
            purchaseOrderDetailComponents.add(purchaseOrderDetailComponent);
        }
        if (CollUtil.isNotEmpty(purchaseOrderDetailComponents)) {
            purchaseOrderDetailComponentService.saveBatch(purchaseOrderDetailComponents);
        }

        //保存科目数据
        final List<PurchaseOrderCostDTO> itItem2 = Objects.nonNull(
                createPurchaseOrderDTO.getEKKN()) ? createPurchaseOrderDTO.getEKKN() : Lists.newArrayList();
        List<PurchaseOrderDetailCost> detailCosts = Lists.newArrayList();
        for (
                PurchaseOrderCostDTO purchaseOrderCostDTO : itItem2) {
            PurchaseOrderDetailCost b = new PurchaseOrderDetailCost();
            b.setPurchaseOrder(purchaseOrderCostDTO.getEBELN());
            b.setLineItem(purchaseOrderCostDTO.getEBELP());
            b.setGeneralLedgerAccount(purchaseOrderCostDTO.getSAKTO());
            b.setCostCenter(purchaseOrderCostDTO.getKOSTL());
            b.setAccountAssignmentNumber(purchaseOrderCostDTO.getZEKKN());
            b.setAssetCode(purchaseOrderCostDTO.getANLN1());
            b.setOrderNumber(purchaseOrderCostDTO.getAUFNR());
            final PurchaseOrderDetailCost dbData =
                    purchaseOrderDetailCostService.getOne(
                            new LambdaQueryWrapper<PurchaseOrderDetailCost>().eq(
                                            PurchaseOrderDetailCost::getPurchaseOrder,
                                            b.getPurchaseOrder())
                                    .eq(PurchaseOrderDetailCost::getLineItem, b.getLineItem())
                                    .eq(PurchaseOrderDetailCost::getGeneralLedgerAccount, b.getGeneralLedgerAccount()),
                            false);
            if (Objects.nonNull(dbData)) {
                b.setId(dbData.getId());
            }
            detailCosts.add(b);
        }
        if (CollUtil.isNotEmpty(detailCosts)) {
            purchaseOrderDetailCostService.saveOrUpdateBatch(detailCosts);
        }

        //保存提货计划
        final List<PurchaseOrderPlanDTO> itItem1 = Objects.nonNull(
                createPurchaseOrderDTO.getEKET()) ? createPurchaseOrderDTO.getEKET() : Lists.newArrayList();
        List<PurchaseOrderDevPlan> devPlans = Lists.newArrayList();
        for (PurchaseOrderPlanDTO a : itItem1) {
            PurchaseOrderDevPlan b = new PurchaseOrderDevPlan();
            b.setPurchaseOrder(a.getEBELN());
            b.setLineItem(a.getEBELP());
            b.setDelFlag("X".equals(a.getZDEL())?1:0);
            b.setScheduleLine(a.getETENR());
            final String s = EINDT2Cache.get(b.getPurchaseOrder() + b.getLineItem());
            if (StrUtil.isNotEmpty(s)) {
                b.setLastRequireDate(LocalDateTimeUtil.parse(s, yyyyMMdd).toLocalDate());
            } else {
                b.setLastRequireDate(null);
            }
            if (StrUtil.isNotEmpty(a.getEINDT())) {
                b.setSapPlanDate(LocalDateTimeUtil.parse(a.getEINDT(), yyyyMMdd).toLocalDate());
            } else {
                b.setSapPlanDate(null);
            }
            b.setScheduleDeliveryQuantity(new BigDecimal(a.getMENGE()));
            b.setPurchaseRequest(a.getBANFN());
            b.setPurchaseRequestLine(a.getBNFPO());
            if (Objects.nonNull(a.getWEMNG())) {
                b.setReceivedQuantity(new BigDecimal(a.getWEMNG()));
            }
            final PurchaseOrderDevPlan dbData = purchaseOrderDevPlanService.getOne(
                    new LambdaQueryWrapper<PurchaseOrderDevPlan>()
                            .eq(PurchaseOrderDevPlan::getPurchaseOrder, b.getPurchaseOrder())
                            .eq(PurchaseOrderDevPlan::getLineItem, b.getLineItem())
                            .eq(PurchaseOrderDevPlan::getScheduleLine, b.getScheduleLine()), false);
            if (Objects.nonNull(dbData)) {
                b.setId(dbData.getId());
                b.setLastRequireDate(null);
            }
            devPlans.add(b);
        }
        if (CollUtil.isNotEmpty(devPlans)) {
            try {
                purchaseOrderDevPlanService.saveOrUpdateBatch(devPlans);
            } catch (DuplicateKeyException e) {
                e.printStackTrace();
            }
        }
        //2024-12-04如果存在删除的计划交货行就要更新对应的订单明细上的需求日期和交货日期
        List<PurchaseOrderPlanDTO> collect = itItem1.stream().filter(pop -> "X".equals(pop.getZDEL())).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(collect)){
            //查询所有计划交货行
            for (PurchaseOrderPlanDTO purchaseOrderPlanDTO : collect) {
                final String purchaseOrderCode = purchaseOrderPlanDTO.getEBELN();
                final String orderRow = purchaseOrderPlanDTO.getEBELP();
                List<PurchaseOrderDevPlan> list = purchaseOrderDevPlanService.list(new LambdaQueryWrapper<PurchaseOrderDevPlan>().eq(PurchaseOrderDevPlan::getPurchaseOrder, purchaseOrderPlanDTO.getEBELN()).eq(PurchaseOrderDevPlan::getLineItem, purchaseOrderPlanDTO.getEBELP()));
                final Optional<PurchaseOrderDevPlan> max = list.stream().filter(a -> (a.getDelFlag() == DelFlag.NORMAL.getStatus()) && (a.getScheduleDeliveryQuantity().compareTo(a.getReceivedQuantity()) != 0))
                        .max(Comparator.comparing(PurchaseOrderDevPlan::getScheduleDeliveryDate));

                final Optional<PurchaseOrderDevPlan> min  = list.stream().filter(a -> (a.getDelFlag() == DelFlag.NORMAL.getStatus()) && (a.getScheduleDeliveryQuantity().compareTo(a.getReceivedQuantity() ) != 0) && a.getLastRequireDate() != null)
                        .min(Comparator.comparing(PurchaseOrderDevPlan::getLastRequireDate));
                LocalDate  scheduleDeliveryDate = null;
                String requireDateStr = "";
                //修改订单明细的回复交期
                if (max.isPresent()) {
                    final PurchaseOrderDevPlan planBaseDTO = max.get();
                    scheduleDeliveryDate = planBaseDTO.getScheduleDeliveryDate();
                }
                //修改需求日期
                if(min.isPresent()){
                    final PurchaseOrderDevPlan planBaseDTO = min.get();
                    final LocalDate requireDate = planBaseDTO.getLastRequireDate();
                    requireDateStr = DateUtils.formatYYYYMMDDDash(requireDate);
                }
                if( scheduleDeliveryDate != null && StringUtils.isNotEmpty(requireDateStr)){
                    purchaseOrderDetailService.update(new LambdaUpdateWrapper<>(PurchaseOrderDetail.class)
                            .set(PurchaseOrderDetail::getReplayRequireDate, scheduleDeliveryDate)
                            .set(PurchaseOrderDetail::getRequireDate, requireDateStr)
                            .eq(PurchaseOrderDetail::getOrderCode, purchaseOrderCode)
                            .eq(PurchaseOrderDetail::getOrderRow, orderRow));
                }

            }
        }


        if (isSendEmailFlag) {
            if (isNewlFlag) {
                pushCreateEmail(purchaseOrder);
            } else {
                pushUpdateEmail(purchaseOrder);
            }
        }
        return ApiResult.builder().

                code(RestCode.SAP_SUCCESS.getCode()).

                build();
    }

    @Override
    public ApiResult CreateDeliveryOrder(CreateDeliveryOrderDTO createDeliveryOrderDTO) {
        final List<CreateDeliveryOrderDTO.ITData> itData = createDeliveryOrderDTO.getIT_DATA();
        if (CollUtil.isEmpty(itData)){
            return ApiResult.builder().message("请传入数据").code(RestCode.SAP_ERROR.getCode()).build();
        }
        List<DeliveryOrder> deliveryOrders = new ArrayList<>();
        for (CreateDeliveryOrderDTO.ITData itData1 : itData){
            DeliveryOrder deliveryOrder = new DeliveryOrder();
            final String DJBH = itData1.getDJBH();
            if (StringUtils.isEmpty(DJBH)){
                return ApiResult.builder().message("请传入送货单号").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setOrderCode(DJBH);
            final String GYSBM = itData1.getGYSBM();
            if (StringUtils.isEmpty(GYSBM)){
                return ApiResult.builder().message("请传入供应商编码").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setSupplierErpCode(GYSBM);


            final String GYSMC = itData1.getGYSMC();
            if (StringUtils.isEmpty(GYSMC)){
                return ApiResult.builder().message("请传入供应商名称").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setSupplierName(GYSMC);

            final String THRQ = itData1.getTHRQ();
            if (StringUtils.isEmpty(THRQ)){
                return ApiResult.builder().message("请传入退货日期").code(RestCode.SAP_ERROR.getCode()).build();
            }
            if (StringUtils.isNotEmpty(THRQ)){
                try {
                    LocalDateTimeUtil.parse(THRQ,"yyyy-MM-dd");
                }catch (Exception e){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的退货日期，格式yyyy-MM-dd").build();
                }
                deliveryOrder.setDeliveryDate(THRQ);
                deliveryOrder.setPlanDeliveryDate(LocalDateTimeUtil.parse(THRQ,"yyyy-MM-dd"));
            }

//            final String LXR = itData1.getLXR();
//            if (StringUtils.isEmpty(LXR)){
//                return ApiResult.builder().message("请传入联系人").code(RestCode.SAP_ERROR.getCode()).build();
//            }
            deliveryOrder.setConsigner(itData1.getLXR());

//            final String DH = itData1.getDH();
//            if (StringUtils.isEmpty(DH)){
//                return ApiResult.builder().message("请传入电话").code(RestCode.SAP_ERROR.getCode()).build();
//            }
            deliveryOrder.setPhone(itData1.getDH());
            deliveryOrder.setExpressNo(itData1.getKDDH());

            final String FHFS = itData1.getFHFS();
            if (StringUtils.isEmpty(FHFS)){
                return ApiResult.builder().message("请传入发货方式").code(RestCode.SAP_ERROR.getCode()).build();
            }
            if (!FHFS.equals("1")&&!FHFS.equals("2")&&!FHFS.equals("3")){
                return ApiResult.builder().message("请输入正确的发货方式").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setDirectShipment(Integer.valueOf(FHFS));

            final String GC = itData1.getGC();
            if (StringUtils.isEmpty(GC)){
                return ApiResult.builder().message("请传入工厂").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setFactoryCode(GC);
            final String GS = itData1.getGS();
            if (StringUtils.isEmpty(GS)){
                return ApiResult.builder().message("请传入公司").code(RestCode.SAP_ERROR.getCode()).build();
            }
            CompanyDTO companyDTO = companyClient.getByCode(GS);
            if (ObjectUtil.isNotEmpty(companyDTO)){
                deliveryOrder.setCompanyName(companyDTO.getCompanyName());
            }else {
                return ApiResult.builder().message(StrUtil.format("公司{}在系统中不存在", GS)).code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrder.setCompanyName(companyDTO.getCompanyName());
            deliveryOrder.setCompanyCode(GS);
            deliveryOrder.setDockerCode("A"+GC);
            deliveryOrder.setShipmentSapStatus(1);
            FactoryDTO factoryDTO = factoryClient.getByCode(GC);
            if (ObjectUtil.isNotEmpty(factoryDTO)){
                deliveryOrder.setFactoryName(factoryDTO.getName());
            }else {
                return ApiResult.builder().message(StrUtil.format("工厂{}在系统中不存在", GC)).code(RestCode.SAP_ERROR.getCode()).build();
            }

//            final String DZ = itData1.getDZ();
//            if (StringUtils.isEmpty(DZ)){
//                return ApiResult.builder().message("请传入收货地址").code(RestCode.SAP_ERROR.getCode()).build();
//            }
            deliveryOrder.setReceiverAddress(itData1.getDZ());
            deliveryOrder.setReturnLocation(itData1.getTLKW());

            deliveryOrder.setState(3);
            deliveryOrder.setSyncState(1);
            deliveryOrder.setDelFlag("1".equals(itData1.getSCBJ())?1:0);
            if (StringUtils.isEmpty(itData1.getCGY())){
                return ApiResult.builder().message("请传入采购员").code(RestCode.SAP_ERROR.getCode()).build();
            }
            PurchaseGroupDTO purchaseGroupDTO = purchaseGroupClient.getByName(itData1.getCGY());
            if (ObjectUtil.isNotEmpty(purchaseGroupDTO)){
                deliveryOrder.setPurchaseGroupName(purchaseGroupDTO.getPurchaseGroupName());
                deliveryOrder.setPurchaseGroupCode(purchaseGroupDTO.getPurchaseGroupCode());
            }else {
                return ApiResult.builder().message(StrUtil.format("采购员{}在系统中不存在", itData1.getCGY())).code(RestCode.SAP_ERROR.getCode()).build();
            }
            DeliveryOrder oldDeliveryOrder = deliveryOrderService.getOne(new LambdaQueryWrapper<>(DeliveryOrder.class).eq(DeliveryOrder::getOrderCode, DJBH).last(" limit 1"));
            if (ObjectUtil.isNotEmpty(oldDeliveryOrder)){
                deliveryOrder.setId(oldDeliveryOrder.getId());
                deliveryOrder.setUpdateId(1L);
                deliveryOrder.setUpdateTime(LocalDateTime.now());
                deliveryOrderService.updateById(deliveryOrder);
                deliveryOrderDetailService.remove(new LambdaQueryWrapper<>(DeliveryOrderDetail.class).eq(DeliveryOrderDetail::getOrderId, oldDeliveryOrder.getId()));
            }else {
                deliveryOrder.setCreateId(1L);
                deliveryOrder.setCreateTime(LocalDateTime.now());
                deliveryOrderService.save(deliveryOrder);
            }
            deliveryOrders.add(deliveryOrder);

            DeliveryOrderDetail deliveryOrderDetail = new DeliveryOrderDetail();
            deliveryOrderDetail.setOrderId(deliveryOrder.getId());
            deliveryOrderDetail.setOrderCode(DJBH);
            final String XH = itData1.getXH();
            if (StringUtils.isEmpty(XH)){
                return ApiResult.builder().message("请传入序号").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrderDetail.setOrderRow(itData1.getXH());

            if (StringUtils.isEmpty(itData1.getCGY())){
                return ApiResult.builder().message("请传入采购员").code(RestCode.SAP_ERROR.getCode()).build();
            }

            deliveryOrderDetail.setBuyer(purchaseGroupDTO.getPurchaseGroupName());
            final String THPO = itData1.getTHPO();
            if (StringUtils.isEmpty(THPO)){
                return ApiResult.builder().message("请传入退货PO").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrderDetail.setPurchaseOrderCode(THPO);
            final String THPOH = itData1.getTHPOH();
            if (StringUtils.isEmpty(THPOH)){
                return ApiResult.builder().message("请传入退货PO行").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrderDetail.setPurchaseOrderRow(THPOH);
            PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailService.getOne(new LambdaQueryWrapper<>(PurchaseOrderDetail.class).eq(PurchaseOrderDetail::getOrderCode, THPO).eq(PurchaseOrderDetail::getOrderRow, THPOH).last(" limit 1"));
            if (ObjectUtil.isNotNull(purchaseOrderDetail)){
                deliveryOrderDetail.setPurchaseOrderNum(purchaseOrderDetail.getNum());
                deliveryOrderDetail.setPrice(purchaseOrderDetail.getPrice());
                deliveryOrderDetail.setAmount(purchaseOrderDetail.getAmount());
            }
            deliveryOrderDetail.setFactoryCode(GC);
            deliveryOrderDetail.setFactoryName(factoryDTO.getName());

            if (StringUtils.isEmpty(itData1.getXWLBH())){
                return ApiResult.builder().message("请传入新物料编号").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrderDetail.setMaterialCode(itData1.getXWLBH());

            if (StringUtils.isEmpty(itData1.getGGXH())){
                return ApiResult.builder().message("请传入规格型号").code(RestCode.SAP_ERROR.getCode()).build();
            }
            deliveryOrderDetail.setMaterialName(itData1.getGGXH());

            if (StringUtils.isEmpty(itData1.getTHSL())){
                return ApiResult.builder().message("请传入退货数量").code(RestCode.SAP_ERROR.getCode()).build();
            }
            try {
                new BigDecimal(itData1.getTHSL());
            }catch (Exception e){
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的退货数量").build();
            }
            deliveryOrderDetail.setNum(new BigDecimal(itData1.getTHSL()));
            deliveryOrderDetail.setRemark(itData1.getBZ());
            deliveryOrderDetail.setUnitCode(itData1.getDW());
            deliveryOrderDetail.setUnitName(itData1.getDW());
            deliveryOrderDetail.setState(3);
            deliveryOrderDetail.setDelFlag("1".equals(itData1.getSCBJ())?1:0);
            deliveryOrderDetail.setSupplierCode(itData1.getGYSBM());
            // 退货储位
            deliveryOrderDetail.setReturnStorageLocation(itData1.getCW());
            // 品质签字人
            deliveryOrderDetail.setQualitySigner(itData1.getPZQZR());
            // 旧物料编码
            deliveryOrderDetail.setOldMaterialCode(itData1.getJWLBM());
            // 判退日期（按接口格式，如 "20251118" 或 "2025-11-18"）
            deliveryOrderDetail.setRejectDate(itData1.getPTRQ());
            // 不良原因
            deliveryOrderDetail.setDefectReason(itData1.getBLYY());
            deliveryOrderDetail.setCreateId(1L);
            deliveryOrderDetail.setCreateTime(LocalDateTime.now());
            deliveryOrderDetailService.save(deliveryOrderDetail);

        }
        for (DeliveryOrder deliveryOrder : deliveryOrders){

            for (CreateDeliveryOrderDTO.ITData itData1 : itData){
                if (itData1.getDJBH().equals(deliveryOrder.getOrderCode())){
                    DeliveryOrderDetail deliveryOrderDetail = new DeliveryOrderDetail();
                    deliveryOrderDetail.setOrderId(deliveryOrder.getId());
                    deliveryOrderDetail.setOrderCode(deliveryOrder.getOrderCode());
                    final String XH = itData1.getXH();
                    if (StringUtils.isEmpty(XH)){
                        return ApiResult.builder().message("请传入序号").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setOrderRow(itData1.getXH());

                    if (StringUtils.isEmpty(itData1.getCGY())){
                        return ApiResult.builder().message("请传入采购员").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setBuyer(deliveryOrder.getPurchaseGroupName());
                    final String THPO = itData1.getTHPO();
                    if (StringUtils.isEmpty(THPO)){
                        return ApiResult.builder().message("请传入退货PO").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setPurchaseOrderCode(THPO);
                    final String THPOH = itData1.getTHPOH();
                    if (StringUtils.isEmpty(THPOH)){
                        return ApiResult.builder().message("请传入退货PO行").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setPurchaseOrderRow(THPOH);
                    PurchaseOrderDetail purchaseOrderDetail = purchaseOrderDetailService.getOne(new LambdaQueryWrapper<>(PurchaseOrderDetail.class).eq(PurchaseOrderDetail::getOrderCode, THPO).eq(PurchaseOrderDetail::getOrderRow, THPOH).last(" limit 1"));
                    if (ObjectUtil.isNotNull(purchaseOrderDetail)){
                        deliveryOrderDetail.setPurchaseOrderNum(purchaseOrderDetail.getNum());
                        deliveryOrderDetail.setPrice(purchaseOrderDetail.getPrice());
                        deliveryOrderDetail.setAmount(purchaseOrderDetail.getAmount());
                    }
                    deliveryOrderDetail.setFactoryCode(deliveryOrder.getFactoryCode());
                    deliveryOrderDetail.setFactoryName(deliveryOrder.getFactoryName());

                    if (StringUtils.isEmpty(itData1.getXWLBH())){
                        return ApiResult.builder().message("请传入新物料编号").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setMaterialCode(itData1.getXWLBH());

                    if (StringUtils.isEmpty(itData1.getGGXH())){
                        return ApiResult.builder().message("请传入规格型号").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    deliveryOrderDetail.setMaterialName(itData1.getGGXH());

                    if (StringUtils.isEmpty(itData1.getTHSL())){
                        return ApiResult.builder().message("请传入退货数量").code(RestCode.SAP_ERROR.getCode()).build();
                    }
                    try {
                        new BigDecimal(itData1.getTHSL());
                    }catch (Exception e){
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的退货数量").build();
                    }
                    deliveryOrderDetail.setNum(new BigDecimal(itData1.getTHSL()));
                    deliveryOrderDetail.setRemark(itData1.getBZ());
                    deliveryOrderDetail.setUnitCode(itData1.getDW());
                    deliveryOrderDetail.setUnitName(itData1.getDW());
                    deliveryOrderDetail.setState(3);
                    deliveryOrderDetail.setDelFlag("1".equals(itData1.getSCBJ())?1:0);
                    deliveryOrderDetail.setSupplierCode(itData1.getGYSBM());
                    // 退货储位
                    deliveryOrderDetail.setReturnStorageLocation(itData1.getCW());
                    // 品质签字人
                    deliveryOrderDetail.setQualitySigner(itData1.getPZQZR());
                    // 旧物料编码
                    deliveryOrderDetail.setOldMaterialCode(itData1.getJWLBM());
                    // 判退日期（按接口格式，如 "20251118" 或 "2025-11-18"）
                    deliveryOrderDetail.setRejectDate(itData1.getPTRQ());
                    // 不良原因
                    deliveryOrderDetail.setDefectReason(itData1.getBLYY());

                    DeliveryOrderDetail oldDeliveryOrderDetail = deliveryOrderDetailService.getOne(new LambdaQueryWrapper<>(DeliveryOrderDetail.class).eq(DeliveryOrderDetail::getOrderCode, deliveryOrder.getOrderCode()).eq(DeliveryOrderDetail::getOrderRow, itData1.getXH()));
                    if (ObjectUtil.isNull(oldDeliveryOrderDetail)){
                        deliveryOrderDetail.setCreateId(1L);
                        deliveryOrderDetail.setCreateTime(LocalDateTime.now());
                        deliveryOrderDetailService.save(deliveryOrderDetail);
                    }else {
                        deliveryOrderDetail.setUpdateId(1L);
                        deliveryOrderDetail.setUpdateTime(LocalDateTime.now());
                        deliveryOrderDetail.setId(oldDeliveryOrderDetail.getId());
                        deliveryOrderDetailService.updateById(deliveryOrderDetail);
                    }

                }
            }
        }

        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).message("ok").build();
    }

    /**
     * 订单创建推送邮件
     */
    private void pushCreateEmail(PurchaseOrder purchaseOrder) {
        pushEmail(purchaseOrder, "JW_POST_080");
    }

    /**
     * 订单创建推送邮件
     */
    private void pushUpdateEmail(PurchaseOrder purchaseOrder) {
        pushEmail(purchaseOrder, "JW_POST_090");
    }

    public void pushEmail(PurchaseOrder purchaseOrder, String emailTmpCode) {
        final List<SupplierContactsDTO> contactBySupplierCodeAndType = supplierClient.getContactBySupplierCodeAndType(
                purchaseOrder.getSupplierErpCode(), DictCode.ContactType.BUSINESS.getType());
        if (CollUtil.isNotEmpty(contactBySupplierCodeAndType)) {
            final SupplierDTO supplierByCode = supplierClient.getSupplierByCode(purchaseOrder.getSupplierErpCode());
            final Set<String> receivers = contactBySupplierCodeAndType.stream().map(SupplierContactsDTO::getEmail)
                    .collect(Collectors.toSet());
            Map<String, Object> params = Maps.newHashMap();
            params.put("supplierName", supplierByCode.getSupplierName());
            params.put("orderCode", purchaseOrder.getOrderCode());
            params.put("date", purchaseOrder.getOrderDate());
            params.put("companyName", purchaseOrder.getCompanyName());
            EmailTmpSendDTO b = new EmailTmpSendDTO();
            b.setSender(purchaseOrder.getCreateId());
            b.setTemplateCode(emailTmpCode);
            b.setReceiver(receivers);
            b.setParams(params);
            emailSendClient.async(b);
        }
    }
}