package com.jwipc.finance.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.constant.DictCode;
import com.jwipc.finance.convert.ReceiptVoucherApiConvert;
import com.jwipc.finance.dto.OrderApiDTO;
import com.jwipc.finance.dto.ReceiptVoucherApiDTO;
import com.jwipc.finance.dto.ReceiptVoucherBaseApiDTO;
import com.jwipc.finance.entity.ReceiveVoucher;
import com.jwipc.finance.logic.ReceiptVoucherApiLogic;
import com.jwipc.finance.service.IReceiveVoucherService;
import com.jwipc.order.clent.dto.*;
import com.jwipc.order.client.DeliverOrderClient;
import com.jwipc.order.client.PurchaseOrderClient;
import com.jwipc.order.client.SapGoodReceiptClient;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.FactoryClient;
import com.jwipc.sys.client.TaxClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.client.dto.FactoryDTO;
import com.jwipc.sys.client.dto.TaxDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;

/**
 * @author shenyang.ou
 * @date 2024/3/20 11:09
 * @desc
 */
@Service
@RequiredArgsConstructor
public class ReceiptVoucherApiLogicImpl implements ReceiptVoucherApiLogic {
    private final ReceiptVoucherApiConvert receiptVoucherApiConvert;
    private final IReceiveVoucherService receiveVoucherService;
    private final SupplierClient supplierClient;
    private final FactoryClient factoryClient;
    private final PurchaseOrderClient purchaseOrderClient;
    private final DeliverOrderClient deliverOrderClient;
    private final SapGoodReceiptClient sapGoodReceiptClient;
    private final TaxClient taxClient;
    private final DictClient dictClient;

    /**
     * 物料凭证同步
     *
     * @param param 参数
     * @return 结果
     */
    @Override
    @DS(SLAVE)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public ApiResult sync(ReceiptVoucherBaseApiDTO param) {
        if (ObjectUtil.isEmpty(param)){
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("参数不能为空").build();
        }
        List<ReceiveVoucher> insertOrUpdateList = Lists.newArrayList();
        List<UpdateOrderDetailDTO> updateOrderDetailDTOS = Lists.newArrayList();
        List<UpdateOrderDTO> updateOrderDTOS = Lists.newArrayList();
        List<PurchaseOrderDevPlanDTO> purchaseOrderDevPlanDTOS = Lists.newArrayList();
        List<SapGoodReceiptClientDTO> sapGoodReceiptClientDTOS = Lists.newArrayList();
        Set<String> devOrderCodes = new HashSet<>();
        Set<String> need = new HashSet<>();
        //工厂
        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<TaxDTO> taxDTOS = taxClient.getAll();
        final Map<String, TaxDTO> taxCache = taxDTOS.stream().collect(Collectors.toMap(TaxDTO::getTaxCode, a -> a));
        final Set<String> taxCodes = taxCache.keySet();
        //付款条件
        List<DictDTO> paymentMethods = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        final Map<String, DictDTO> paymentMethodCache = paymentMethods.stream().collect(Collectors.toMap(DictDTO::getCode, a -> a));
        final Set<String> paymentMethodCodes = paymentMethodCache.keySet();
        try {
            for (ReceiptVoucherApiDTO receiptVoucherApiDTO : param.getReceiptVoucherApiDTOS()) {
                ReceiveVoucher receiptVoucher = receiptVoucherApiConvert.apiDTO2Entity(receiptVoucherApiDTO);

                //判断是否拥有
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMvCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入物料凭证编号").build();
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMvItemNo())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入物料凭证行号").build();
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMvYear())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入物料凭证的年份").build();
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMvPostDateStr())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入凭证中的过帐日期").build();
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMvDateStr())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入凭证日期").build();
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getMaterialGroupCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入物料组").build();
                }
                //插入送货单号
                if (StringUtils.isNotEmpty(receiptVoucherApiDTO.getHeadUpText())){
                    devOrderCodes.add(receiptVoucherApiDTO.getHeadUpText());
                }
                //置空操作
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getInvoicedCode())){
                    receiptVoucher.setInvoicedCode("");
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getExtendFiled1())){
                    receiptVoucher.setExtendFiled1("");
                }
                receiptVoucher.setOriginalTaxPrice(receiptVoucher.getTaxPrice());
                //凭证过账日期
                receiptVoucher.setMvPostDate(LocalDateTimeUtil.parse(receiptVoucherApiDTO.getMvPostDateStr(), "yyyyMMdd"));
                //凭证创建日期
                receiptVoucher.setMvCreateDate(LocalDateTimeUtil.parse(receiptVoucherApiDTO.getMvDateStr(), "yyyyMMdd"));

                //质检入库日期
                if (StringUtils.isNotEmpty(receiptVoucherApiDTO.getPurPostDateStr())){
                    receiptVoucher.setPurPostDate(LocalDateTimeUtil.parse(receiptVoucherApiDTO.getPurPostDateStr(), "yyyyMMdd"));
                }else {
                    receiptVoucher.setPurPostDate(null);
                }
                if (StringUtils.isNotEmpty(receiptVoucherApiDTO.getPaymentExpireDateStr())){
                    try {
                        receiptVoucher.setPaymentExpireDate(LocalDateTimeUtil.parse(receiptVoucherApiDTO.getPaymentExpireDateStr(),"yyyyMMdd"));
                    }catch (Exception e){
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请输入正确的付款到期日，格式yyyyMMdd").build();
                    }
                }
                //供应商编码
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getSupplierCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入供应商编码").build();
                }
                receiptVoucher.setSupplierCode(receiptVoucherApiDTO.getSupplierCode().replaceAll("^(0+)", ""));
                //查询供应商信息
                final SupplierDTO supplierDTO = supplierClient.getSupplierByCode(receiptVoucher.getSupplierCode());
                if (ObjectUtil.isNull(supplierDTO)){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("供应商：{}在系统中不存在",receiptVoucher.getSupplierCode())).build();
                }
                //供应商名称
                receiptVoucher.setSupplierName(supplierDTO.getSupplierName());
                //查询工厂
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getFactoryCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入工厂").build();
                }
                if (!factoryCodes.contains(receiptVoucher.getFactoryCode())) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("工厂：{}在系统中不存在",receiptVoucher.getFactoryCode())).build();
                }
                FactoryDTO factoryDTO = factoryCache.get(receiptVoucher.getFactoryCode());
                //工厂名称
                receiptVoucher.setFactoryName(factoryDTO.getName());

                receiptVoucher.setVoucherType(1);
                //5000265602是无物料的，所以没有“数量”和“基本单位”这两个值，只会有“辅助单位”和“辅助数量”这两个订单值
                //我们展示和传输都应该使用“辅助单位”和“辅助数量”这两个订单值
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getPoPriceUnit())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入辅助单位").build();
                }
                if (receiptVoucherApiDTO.getMvNum()==null){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入辅助单位").build();
                }
//                if (StringUtils.isEmpty(receiptVoucher.getPoMeterUnit())){
                    receiptVoucher.setPoMeterUnit(receiptVoucher.getPoPriceUnit());
//                }
//                if (receiptVoucher.getMvBasicNum()==null){
                    receiptVoucher.setMvBasicNum(receiptVoucher.getMvNum());
//                }
                receiptVoucher.setAccountStatementFlag(0);
                //K+411、412参与对账
//                if ("K".equals(receiptVoucherApiDTO.getSpecialInventoryFlag())&&"411,412".contains(receiptVoucherApiDTO.getSapMoveType())){
//                    receiptVoucher.setAccountStatementFlag(1);
//                    //凭证类型为寄售
//                    receiptVoucher.setVoucherType(2);
//                }if (StringUtils.isEmpty(receiptVoucherApiDTO.getSpecialInventoryFlag())){
//                    receiptVoucher.setAccountStatementFlag(1);
//                }

                if ("411,412".contains(receiptVoucherApiDTO.getSapMoveType())){
                    receiptVoucher.setAccountStatementFlag(1);
                    //凭证类型为寄售
                    receiptVoucher.setVoucherType(2);
                }
                if ("K".equals(receiptVoucherApiDTO.getSpecialInventoryFlag())&&!"411,412".contains(receiptVoucherApiDTO.getSapMoveType())){
                    //凭证类型为寄售
                    receiptVoucher.setVoucherType(2);
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getSpecialInventoryFlag())){
                    receiptVoucher.setAccountStatementFlag(1);
                }

//                if (StringUtils.isEmpty(receiptVoucher.getMaterialCode())&& "Z99002".equals(receiptVoucher.getMaterialGroupCode())){
//                    receiptVoucher.setVoucherType(4);
//                }
//
//                if (StringUtils.isEmpty(receiptVoucher.getMaterialCode())&& !"Z99002".equals(receiptVoucher.getMaterialGroupCode())){
//                    receiptVoucher.setVoucherType(3);
//                }

                if (StringUtils.isEmpty(receiptVoucher.getMaterialCode())){
                    receiptVoucher.setVoucherType(3);
                }

                if ("101,105,162,123,411".contains(receiptVoucherApiDTO.getSapMoveType())) {
                    receiptVoucher.setVoucherFlag("S");
                } else if ("102,106,161,122,123,412".contains(receiptVoucherApiDTO.getSapMoveType())) {
                    receiptVoucher.setVoucherFlag("H");
                } else {
                    //如果是不是上面的几种类型，不做任何处理，直接
                    continue;
                }

                if ("161,122".contains(receiptVoucherApiDTO.getSapMoveType())) {
                    if (StrUtil.isNotEmpty(receiptVoucher.getHeadUpText())){
                        UpdateOrderDTO updateOrderDTO = new UpdateOrderDTO();
                        updateOrderDTO.setOrderCode(receiptVoucher.getHeadUpText());
                        updateOrderDTO.setReturnConfirmStatus(1);
                        updateOrderDTO.setMvPostDate(receiptVoucher.getMvPostDate());
                        updateOrderDTOS.add(updateOrderDTO);
                    }

                }
                if ("162,123".contains(receiptVoucherApiDTO.getSapMoveType())) {
                    if (StrUtil.isNotEmpty(receiptVoucher.getHeadUpText())){
                        UpdateOrderDTO updateOrderDTO = new UpdateOrderDTO();
                        updateOrderDTO.setOrderCode(receiptVoucher.getHeadUpText());
                        updateOrderDTO.setReturnConfirmStatus(0);
                        updateOrderDTO.setMvPostDate(receiptVoucher.getMvPostDate());
                        updateOrderDTOS.add(updateOrderDTO);
                    }

                }


//            receiptVoucher.setCurrencyCode(purchaseOrderDTO.getCurrencyCode());
                //凭证类型不为寄售查询采购订单明细
                if (receiptVoucher.getVoucherType()!=2&&StringUtils.isEmpty(receiptVoucherApiDTO.getPoCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入采购凭证编号").build();
                }

                if (receiptVoucher.getVoucherType()!=2){
                    final PurchaseOrderDTO purchaseOrderDTO = purchaseOrderClient.getOrderByCode(receiptVoucher.getPoCode());
                    if (ObjectUtil.isNull(purchaseOrderDTO)){
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("采购凭证编号：{}在系统中不存在",receiptVoucher.getPoCode())).build();
                    }
                    //SAP订单号
//                    receiptVoucher.setPoCode(receiptVoucherApiDTO.getPoCode().replaceAll("^(0+)", ""));
                    receiptVoucher.setPoCode(receiptVoucherApiDTO.getPoCode());
                    //采购订单类型和类型名称
                    receiptVoucher.setPoType(purchaseOrderDTO.getOrderTypeCode());
                    receiptVoucher.setPoTypeName(purchaseOrderDTO.getOrderTypeName());
                    //SC订单号
                    receiptVoucher.setZlsdh(purchaseOrderDTO.getZlsdh());
                    //付款条件描述
                    receiptVoucher.setPaymentTermName(purchaseOrderDTO.getPaymentMethodName());
                    //付款条件编码
                    receiptVoucher.setPaymentTermCode(purchaseOrderDTO.getPaymentMethod());

                    //采购组编码
                    receiptVoucher.setPgCode(purchaseOrderDTO.getPurchaseGroupCode());
                    //采购组名称
                    receiptVoucher.setPgName(purchaseOrderDTO.getPurchaseGroupName());
                    //采购组织编码
                    receiptVoucher.setPurchaseOrgCode(purchaseOrderDTO.getPurchaseOrgCode());
                    //采购组织名称
                    receiptVoucher.setPurchaseOrgName(purchaseOrderDTO.getPurchaseOrgName());
                    //公司编码
                    receiptVoucher.setCompanyCode(purchaseOrderDTO.getCompanyCode());
                    //公司名称
                    receiptVoucher.setCompanyName(purchaseOrderDTO.getCompanyName());

                    receiptVoucher.setSupplierCode2(purchaseOrderDTO.getSupplierCode1());
                    receiptVoucher.setSupplierName2(purchaseOrderDTO.getSupplierName1());
                    final PurchaseDetailDTO purchaseDetailDTO = purchaseOrderClient.getOrderDetailByCodeAndItemNoAndFactoryCode(receiptVoucher.getPoCode(),receiptVoucher.getPoItemNo(),receiptVoucher.getFactoryCode());
                    if (ObjectUtil.isNull(purchaseDetailDTO)){
                        return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("采购凭证编号：{}，采购凭证的项目编号：{}在系统中不存在",receiptVoucher.getPoCode(),receiptVoucher.getPoItemNo())).build();
                    }
//                    receiptVoucher.setPoItemNo(receiptVoucherApiDTO.getPoItemNo().replaceAll("^(0+)", ""));
                    receiptVoucher.setPoItemNo(receiptVoucherApiDTO.getPoItemNo());
                    //货币代码-默认
                    //订单含税金额
                    receiptVoucher.setPoTaxAmount(purchaseDetailDTO.getTaxAmount());
                    //订单未税金额
                    receiptVoucher.setPoNotTaxAmount(purchaseDetailDTO.getAmount());
                    //采购订单数量
                    receiptVoucher.setPoNum(purchaseDetailDTO.getNum());


                    //以下为更新采购订单明细
                    UpdateOrderDetailDTO  updateOrderDetailDTO = new UpdateOrderDetailDTO();
                    updateOrderDetailDTO.setOrderCode(purchaseDetailDTO.getOrderCode());
                    updateOrderDetailDTO.setOrderRow(purchaseDetailDTO.getOrderRow());
                    updateOrderDetailDTO.setReceivedNum(receiptVoucherApiDTO.getReceivedNum().toPlainString());
                    updateOrderDetailDTO.setFinishFlag("X".equals(receiptVoucherApiDTO.getFinishFlag())?1:0);
                    updateOrderDetailDTO.setFactoryCode(receiptVoucherApiDTO.getFactoryCode());
                    updateOrderDetailDTOS.add(updateOrderDetailDTO);


                }else {
                    //入库凭证 如果订单为空时，去根据供应商+工厂去取品类的第一条付款条件
                    Pair<String, SupplierPurchaseCategoryDTO> stringSupplierPurchaseCategoryDTOPair =  supplierClient.getSupplierPurchaseCategory(receiptVoucher.getSupplierCode(),receiptVoucher.getFactoryCode());
                    if (ObjectUtil.isNotEmpty(stringSupplierPurchaseCategoryDTOPair.getValue())){
                        receiptVoucher.setPaymentTermCode(stringSupplierPurchaseCategoryDTOPair.getValue().getPaymentTerms());
                        DictDTO dictDTO = paymentMethodCache.get(stringSupplierPurchaseCategoryDTOPair.getValue().getPaymentTerms());
                        if (ObjectUtil.isNotEmpty(dictDTO)){
                            receiptVoucher.setPaymentTermName(dictDTO.getName());
                        }
                    }
                }
                if (StringUtils.isEmpty(receiptVoucherApiDTO.getTaxCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入税率").build();
                }
                if (!taxCodes.contains(receiptVoucherApiDTO.getTaxCode())){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("税率：{}在系统中不存在",receiptVoucher.getTaxCode())).build();
                }
                TaxDTO taxDTO = taxCache.get(receiptVoucherApiDTO.getTaxCode());
                //税率描述
                receiptVoucher.setTaxDesc(taxDTO.getTaxName());
                //税率值
                receiptVoucher.setTaxValue(taxDTO.getTaxValue());
                if (receiptVoucherApiDTO.getTaxAmount()==null){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入含税金额").build();
                }
                if (receiptVoucherApiDTO.getNotTaxAmount()==null){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入入库金额").build();
                }
                if (receiptVoucherApiDTO.getMvNum()==null){
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入辅助数量").build();
                }
                //税额 含税金额-未税金额
                receiptVoucher.setDiffTaxAmount(receiptVoucherApiDTO.getTaxAmount().subtract(receiptVoucherApiDTO.getNotTaxAmount()));
                //不含税单价 未税金额/数量
                receiptVoucher.setNotTaxPrice(receiptVoucherApiDTO.getNotTaxAmount().divide(receiptVoucherApiDTO.getMvNum(), 6, BigDecimal.ROUND_DOWN));
                //数据组合键 供应商编码+物料凭证年度+物料凭证号+行号
                receiptVoucher.setDataKey(
                        receiptVoucher.getSupplierCode() + "-" + receiptVoucher.getMvYear() + "-" +
                                receiptVoucher.getMvCode() + "-" + receiptVoucher.getMvItemNo());
                insertOrUpdateList.add(receiptVoucher);

                //插入退货凭证表
                if ("122,123".contains(receiptVoucherApiDTO.getSapMoveType())) {
                    SapGoodReceiptClientDTO sapGoodReceiptClientDTO = new SapGoodReceiptClientDTO();
                    sapGoodReceiptClientDTO.setLfbnr(receiptVoucherApiDTO.getCvCode());
                    sapGoodReceiptClientDTO.setBwart(receiptVoucherApiDTO.getSapMoveType());
                    sapGoodReceiptClientDTO.setWerks(receiptVoucherApiDTO.getFactoryCode());
                    sapGoodReceiptClientDTO.setMblnr(receiptVoucherApiDTO.getMvCode());
                    sapGoodReceiptClientDTO.setUsnam(receiptVoucherApiDTO.getCreator());
                    sapGoodReceiptClientDTO.setMenge(receiptVoucherApiDTO.getMvBasicNum().toPlainString());
                    sapGoodReceiptClientDTO.setBudat(receiptVoucherApiDTO.getMvPostDateStr());
                    sapGoodReceiptClientDTO.setLicha("");
                    sapGoodReceiptClientDTO.setSgtxt(receiptVoucherApiDTO.getSapRemark());
                    sapGoodReceiptClientDTO.setMjahr(receiptVoucherApiDTO.getMvYear());
                    sapGoodReceiptClientDTO.setZKostl("");
                    sapGoodReceiptClientDTO.setHsdat("");
                    sapGoodReceiptClientDTO.setZkkbl("");
                    sapGoodReceiptClientDTO.setVfdat("");
                    sapGoodReceiptClientDTO.setZzshdhxm(receiptVoucherApiDTO.getDeliveryItemNo());
                    sapGoodReceiptClientDTO.setAblad("");
                    sapGoodReceiptClientDTO.setMatnr(receiptVoucherApiDTO.getMaterialCode());
                    sapGoodReceiptClientDTO.setWempf("");
                    sapGoodReceiptClientDTO.setMaktx("");
                    sapGoodReceiptClientDTO.setCharg(receiptVoucherApiDTO.getBatch());
                    sapGoodReceiptClientDTO.setEbeln(receiptVoucherApiDTO.getPoCode());
                    sapGoodReceiptClientDTO.setErfmg(receiptVoucherApiDTO.getMvNum().toPlainString());
                    sapGoodReceiptClientDTO.setBktxt(receiptVoucherApiDTO.getHeadUpText());
                    sapGoodReceiptClientDTO.setZeile(receiptVoucherApiDTO.getMvItemNo());
                    sapGoodReceiptClientDTO.setErfme(receiptVoucherApiDTO.getPoPriceUnit());
                    sapGoodReceiptClientDTO.setLgort(receiptVoucherApiDTO.getInventoryLocation());
                    sapGoodReceiptClientDTO.setEbelp(receiptVoucherApiDTO.getPoItemNo());
                    sapGoodReceiptClientDTO.setBldat(DateUtil.format(new Date(),"yyyy-MM-dd"));
                    sapGoodReceiptClientDTO.setPrueflos(receiptVoucherApiDTO.getQualityTestingNo());
                    sapGoodReceiptClientDTO.setLfpos(receiptVoucherApiDTO.getCvItemNo());
                    sapGoodReceiptClientDTO.setMeins(receiptVoucherApiDTO.getPoMeterUnit());
                    sapGoodReceiptClientDTO.setShkzg(receiptVoucherApiDTO.getMetonymyItem());
                    sapGoodReceiptClientDTO.setLfbja(receiptVoucherApiDTO.getCvYear());
                    sapGoodReceiptClientDTO.setZzshdh(receiptVoucherApiDTO.getDeliveryOrderNo());
                    sapGoodReceiptClientDTO.setLifnr(receiptVoucherApiDTO.getSupplierCode());
                    sapGoodReceiptClientDTO.setZhsdj(receiptVoucherApiDTO.getTaxPrice().toPlainString());
                    sapGoodReceiptClientDTO.setMwskz(receiptVoucherApiDTO.getTaxCode());
                    sapGoodReceiptClientDTO.setLwedt("");
                    sapGoodReceiptClientDTO.setCreateTime(new Date());
                    sapGoodReceiptClientDTO.setZlsdh("");
                    sapGoodReceiptClientDTO.setZremark(receiptVoucherApiDTO.getAdverseCauses());
                    sapGoodReceiptClientDTOS.add(sapGoodReceiptClientDTO);
                }

                try {
                    ReceiveVoucher result = receiveVoucherService.findByMvCodeAndFactoryCode(receiptVoucherApiDTO.getMvYear(),
                            receiptVoucherApiDTO.getMvCode(), receiptVoucherApiDTO.getMvItemNo(), receiptVoucherApiDTO.getFactoryCode());
                    if (ObjectUtil.isNotNull(result)) {
                        receiptVoucher.setId(result.getId());
                        receiptVoucher.setLastUpdateTime(LocalDateTime.now());
                        receiptVoucher.setSupplierCode2(null);
                        receiptVoucher.setSupplierName2(null);
                        receiveVoucherService.update(receiptVoucher, Wrappers.lambdaQuery(ReceiveVoucher.class)
                                .eq(ReceiveVoucher::getId,result.getId()).eq(ReceiveVoucher::getFactoryCode,receiptVoucher.getFactoryCode()));
                    } else {
                        // 尝试插入新记录
                        receiptVoucher.setId(IdWorker.getId());
                        receiptVoucher.setLastUpdateTime(LocalDateTime.now());
                        receiptVoucher.setSyncTime(LocalDateTime.now());
                        receiveVoucherService.save(receiptVoucher);
                    }
                } catch (DuplicateKeyException e) {
                    // 唯一冲突时转为更新
                    ReceiveVoucher existing = receiveVoucherService.findByMvCodeAndFactoryCode(receiptVoucherApiDTO.getMvYear(),
                            receiptVoucherApiDTO.getMvCode(), receiptVoucherApiDTO.getMvItemNo(), receiptVoucherApiDTO.getFactoryCode());
                    if (ObjectUtil.isNotNull(existing)) {
                        receiptVoucher.setId(existing.getId());
                        receiptVoucher.setLastUpdateTime(LocalDateTime.now());
                        //2024-08-13修改
                        receiptVoucher.setSupplierCode2(null);
                        receiptVoucher.setSupplierName2(null);
                        receiveVoucherService.update(receiptVoucher, Wrappers.lambdaQuery(ReceiveVoucher.class)
                                .eq(ReceiveVoucher::getId, existing.getId()).eq(ReceiveVoucher::getFactoryCode, receiptVoucher.getFactoryCode()));
                    } else {
                        // 理论上不应该走到这里，但为了安全起见
                        throw new RuntimeException("数据冲突处理失败", e);
                    }
                }
            }
//            if (CollectionUtil.isNotEmpty(insertOrUpdateList)){
//                receiveVoucherService.saveOrUpdateBatch(insertOrUpdateList);
//            }

            if (CollectionUtil.isNotEmpty(param.getOrderApiDTOList())){
                for (OrderApiDTO orderApiDTO : param.getOrderApiDTOList()){
                    PurchaseOrderDevPlanDTO planDTO = new PurchaseOrderDevPlanDTO();
                    planDTO.setPurchaseOrder(orderApiDTO.getOrderCode());
                    planDTO.setLineItem(orderApiDTO.getOrderRow());
                    planDTO.setScheduleLine(orderApiDTO.getScheduleLine());
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    planDTO.setScheduleDeliveryDate(LocalDate.parse(orderApiDTO.getScheduleDeliveryDateStr(),formatter));
                    planDTO.setScheduleDeliveryQuantity(orderApiDTO.getScheduleDeliveryQuantity());
                    planDTO.setPurchaseRequest(orderApiDTO.getPurchaseRequest());
                    planDTO.setPurchaseRequestLine(orderApiDTO.getPurchaseRequestLine());
                    planDTO.setReceivedQuantity(orderApiDTO.getReceivedQuantity());
                    purchaseOrderDevPlanDTOS.add(planDTO);
                }
            }

            if (CollectionUtil.isNotEmpty(updateOrderDetailDTOS)){
                purchaseOrderClient.updatePurchaseDetail(updateOrderDetailDTOS,purchaseOrderDevPlanDTOS);
            }
            if (CollectionUtil.isNotEmpty(sapGoodReceiptClientDTOS)){
                sapGoodReceiptClient.saveOrUpdate(sapGoodReceiptClientDTOS);
            }
            //调用送货单接口
            if (CollectionUtil.isNotEmpty(devOrderCodes)){
                deliverOrderClient.complateDelivery(devOrderCodes);
            }
            if (CollectionUtil.isNotEmpty(updateOrderDTOS)){
                deliverOrderClient.updateDeliveryReturnConfirmStatus(updateOrderDTOS);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(e.getMessage()).build();
        }
        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).message("成功").build();
    }
}
