package com.sw.mes.store.api.interfaces.consumer;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.sw.mes.core.api.materialclean.MaterialCleanFeignClients;
import com.sw.mes.core.dto.SeedGroupBracketDto;
import com.sw.mes.core.dto.sap.RecycledReportSapRecordDto;
import com.sw.mes.core.enums.MesToSapTypeEnum;
import com.sw.mes.core.utils.ThreadManager;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.sw.mes.core.api.system.AccessoryFeignClients;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.ApplyAccessoryData;
import com.sw.mes.core.dto.sap.ReportSapChargItemDto;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtDto;
import com.sw.mes.core.dto.wms.RemesstaDto;
import com.sw.mes.core.enums.InputBillTypeEnum;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.store.dto.WarehouseAllotBillDto;
import com.sw.mes.store.entity.WarehouseInputBill;
import com.sw.mes.store.entity.WarehouseInputBillDetail;
import com.sw.mes.store.entity.WarehouseModel;
import com.sw.mes.store.entity.WarehouseOutputBill;
import com.sw.mes.store.entity.WarehouseOutputBillDetail;
import com.sw.mes.store.enums.AllotBillTypeEnum;
import com.sw.mes.store.enums.InputBillStatusEnum;
import com.sw.mes.store.enums.OutputBillTypeEnum;
import com.sw.mes.store.enums.WmsInputStatusEnum;
import com.sw.mes.store.service.WarehouseInputBillDetailService;
import com.sw.mes.store.service.WarehouseModelService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description 需要外部系统提供接口，由线边仓调用
 * @Author wupeng
 * @Date 2023/12/28 14:56
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class WarehouseConsumerServiceImpl implements WarehouseConsumerService {

    @Autowired
    private AccessoryFeignClients accessoryFeignClients;
    @Autowired
    private YbFeignClients ybFeignClients;
    @Autowired
    private WarehouseInputBillDetailService detailService;

    @Autowired
    private WarehouseModelService warehouseModelService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private MaterialCleanFeignClients materialCleanFeignClients;

    @Autowired
//    private WarehouseInputBillDetailService warehouseInputBillDetailService;

    @Override
    public String genInputBillNo() {
        return null;
    }

    @Override
    public String genOutputBillNo() {
        return null;
    }

    @Override
    public void afterAuditInput(WarehouseInputBill inputBill) {
        this.inputFeedback(inputBill);
    }

    @Override
    public void afterAutoInput(WarehouseInputBill inputBill) {
        this.inputFeedback(inputBill);
    }

    @Override
    public void afterInputReject(WarehouseInputBill inputBill) {
        this.inputFeedback(inputBill);
    }

    @Override
    public void afterInputCancel(WarehouseInputBill inputBill) {

    }

    @Override
    public void afterAuditOutput(WarehouseOutputBill outputBill) {
        this.outputFeedback(outputBill, 0);
    }

    @Override
    public void afterAutoOutput(WarehouseOutputBill outputBill) {

    }

    @Override
    public void afterOutputReject(WarehouseOutputBill outputBill) {
        this.outputFeedback(outputBill, 1);
    }

    @Override
    public void afterAuditAllot(WarehouseAllotBillDto warehouseAllotBillDto) {
        this.allotFeedback(warehouseAllotBillDto);
    }

    @Override
    public void afterOutputCancel(WarehouseOutputBill outputBill) {

    }

    private void inputFeedback(WarehouseInputBill inputBill) {
        String type = inputBill.getType();
        Integer status = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //反馈 辅料退库 审核状态
        if (InputBillTypeEnum.辅料退库.getValue().equals(type)) {
            if (InputBillStatusEnum.已取消.getValue().equals(inputBill.getStatus())) {
                status = 2;
            }
            if (InputBillStatusEnum.拒收.getValue().equals(inputBill.getStatus())) {
                status = 1;
            }
            if (InputBillStatusEnum.已入库.getValue().equals(inputBill.getStatus())) {
                status = 0;
            }
            if (status != null) {
                try {
                    Result<Void> voidResult = accessoryFeignClients.stockReturnApplyFeedback(inputBill.getBillNo(), status, BaseContextHandler.getUsername());
                    if (voidResult.getCode() != 200) {
                        throw new BusinessException("辅料退库反馈状态失败，状态码" + voidResult.getCode() + "，反馈信息" + voidResult.getMessage());
                    }
                } catch (Exception e) {
                    throw new BusinessException("反馈【辅料退库】审核状态失败，失败原因：" + e.getMessage());
                }
            }
        }
        if (InputBillTypeEnum.籽晶入库.getValue().equals(type) && InputBillStatusEnum.已入库.getValue().equals(inputBill.getStatus())) {
            inputBill.getInputBillDetails().stream().forEach(details -> {
                ReportSapGoodsmvtDto reportSapGoodsmvtDto = new ReportSapGoodsmvtDto();
                List<ReportSapChargItemDto> reportSapChargItemDtos = new ArrayList<>();
                ReportSapChargItemDto reportSapChargItemDto = new ReportSapChargItemDto();
//        reportSapChargItemDto.setAtnam("P01");
//        reportSapChargItemDto.setAtwrt("JK1");
                reportSapChargItemDtos.add(reportSapChargItemDto);
                reportSapGoodsmvtDto.setChargItems(reportSapChargItemDtos);
                reportSapGoodsmvtDto.setAufnr(inputBill.getWorkOrderNo());
                reportSapGoodsmvtDto.setCharg(details.getBatchNo());
                reportSapGoodsmvtDto.setBwart("101");
                reportSapGoodsmvtDto.setWerks("5041");
                reportSapGoodsmvtDto.setUmcha(details.getBatchNo());
                reportSapGoodsmvtDto.setUmwrk("5041");
                reportSapGoodsmvtDto.setMatnr(details.getMaterialModelCode());
                reportSapGoodsmvtDto.setMenge(details.getCount() == null ? "0" : details.getCount().toString());
                reportSapGoodsmvtDto.setMeins(details.getUnitName());
                reportSapGoodsmvtDto.setZfcpFlag("");
                reportSapGoodsmvtDto.setLgort(details.getWarehouseCode());
                reportSapGoodsmvtDto.setProcName("籽晶收货");
                WarehouseModel warehouseModel = warehouseModelService.getById(details.getWarehouseId());
                if (!ObjectUtils.isEmpty(warehouseModel)) {
                    reportSapGoodsmvtDto.setUmlgo(warehouseModel.getCode());
                } else {
                    throw new BusinessException("未找到【" + details.getWarehouseName() + "】库位数据");
                }
                Result result = ybFeignClients.sendSapGoodsmvt(reportSapGoodsmvtDto);
                if (!result.getCode().equals(200)) {
                    throw new BusinessException("报工接口失败，状态码" + result.getCode() + "，反馈信息" + result.getMessage());
                }
                if (StringUtils.isNotEmpty(details.getSerialNo())) {
                    Result<SeedGroupBracketDto> groupBracketByCode = ybFeignClients.findGroupBracketByCode(details.getSerialNo());
                    if (groupBracketByCode.getCode().equals(200) && null != groupBracketByCode.getData()) {
                        SeedGroupBracketDto seedGroupBracketDto = groupBracketByCode.getData();
                        seedGroupBracketDto.setStatus(inputBill.getStatus());
                        seedGroupBracketDto.getDetailsDtos().forEach(detailsDto -> {
                            detailsDto.setStatus(seedGroupBracketDto.getStatus());
                        });
                        ybFeignClients.updateSeedGroupBracket(seedGroupBracketDto);
                    }
                }
            });
        }
        if (InputBillTypeEnum.籽晶入库.getValue().equals(type) && InputBillStatusEnum.拒收.getValue().equals(inputBill.getStatus())) {
            inputBill.getInputBillDetails().stream().forEach(details -> {
                if (StringUtils.isNotEmpty(details.getSerialNo())) {
                    Result<SeedGroupBracketDto> groupBracketByCode = ybFeignClients.findGroupBracketByCode(details.getSerialNo());
                    if (groupBracketByCode.getCode().equals(200) && null != groupBracketByCode.getData()) {
                        SeedGroupBracketDto seedGroupBracketDto = groupBracketByCode.getData();
                        seedGroupBracketDto.setStatus(inputBill.getStatus());
                        seedGroupBracketDto.getDetailsDtos().forEach(detailsDto -> {
                            detailsDto.setStatus(seedGroupBracketDto.getStatus());
                        });
                        ybFeignClients.updateSeedGroupBracket(seedGroupBracketDto);
                    }
                }
            });
        }

        if (InputBillTypeEnum.原辅料入库.getValue().equals(type)) {
            String wmsStatus;
            if (InputBillStatusEnum.拒收.getValue().equals(inputBill.getStatus())) {
                wmsStatus = WmsInputStatusEnum.拒收.getValue();
            } else if (InputBillStatusEnum.已入库.getValue().equals(inputBill.getStatus())) {
                wmsStatus = WmsInputStatusEnum.接收.getValue();
            } else {
                wmsStatus = "";
            }
            if (!StringUtils.isEmpty(wmsStatus)) {
                try {
                    List<WarehouseInputBillDetail> details = detailService.getByBillId(inputBill.getId());
                    List<RemesstaDto> rematDetailsDto = new ArrayList<RemesstaDto>();
                    if (!ObjectUtils.isEmpty(details)) {
                        details.stream().forEach(entity -> {
                            RemesstaDto remesstaDto = new RemesstaDto();
                            remesstaDto.setOrganizationid("JINKO");
//                            remesstaDto.setOrganizationid(entity.getCustomer());
                            remesstaDto.setWarehouseid(entity.getWarehouseCode());
                            remesstaDto.setCustomerid(entity.getCustomer());
                            remesstaDto.setDocno(inputBill.getBillNo());
                            remesstaDto.setAufn(inputBill.getBillNo());
                            remesstaDto.setTraceid(entity.getTraceid());
                            remesstaDto.setSerialno(entity.getSerialNo());
                            remesstaDto.setBillresult(wmsStatus);
                            remesstaDto.setNotes(inputBill.getRemark());
                            remesstaDto.setSku(entity.getMaterialModelCode());
                            remesstaDto.setLotatt04(entity.getBatchNo());
                            rematDetailsDto.add(remesstaDto);
                        });
                    }
                    List<RemesstaDto> rematDetailsDtos = new ArrayList<>();
                    //需按照托号和箱号进行管理
                    List<RemesstaDto> remesstaDtoList1 = rematDetailsDto.stream().filter(entity -> !entity.getTraceid().equals("*")).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(remesstaDtoList1)) {
                        //去除重复托盘 liru
                        rematDetailsDtos = remesstaDtoList1.stream()
                                .collect(Collectors.collectingAndThen(
                                        Collectors.toMap(RemesstaDto::getTraceid, Function.identity(), (p1, p2) -> p1),
                                        map -> new ArrayList<>(map.values())
                                ));
                    }
                    //不需按照托号和箱号进行管理
                    List<RemesstaDto> remesstaDtoList2 = rematDetailsDto.stream().filter(entity -> entity.getTraceid().equals("*")).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(remesstaDtoList2)) {
                        List<RemesstaDto> rematDetailsDtoList = remesstaDtoList2.stream().collect(Collectors.collectingAndThen(
                                Collectors.toMap(RemesstaDto::getLotatt04, Function.identity(), (p1, p2) -> p1),
                                map -> new ArrayList<>(map.values())
                        ));
                        if (!CollectionUtils.isEmpty(rematDetailsDtoList)) {
                            rematDetailsDtos.addAll(rematDetailsDtoList);
                        }
                    }
                    Result voidResult = ybFeignClients.remessta(rematDetailsDtos);
                    if (voidResult.getCode() != 200) {
                        throw new BusinessException("原辅料入库反馈状态失败，状态码" + voidResult.getCode() + "，反馈信息" + voidResult.getMessage());
                    }
                } catch (Exception e) {
                    log.error("error_in_call_ybFeignClients.remessta", e);
                    throw new BusinessException("反馈【原辅料入库】审核状态失败，失败原因：" + e.getMessage());
                }
            }
        }
       /* if (InputBillTypeEnum.废料入库.getValue().equals(type)) {
            try {
                List<MesasnDto> mesasnDtos = new ArrayList<>();
                //组装对应数据
                MesasnDto mesasnDto = new MesasnDto();
                mesasnDto.setOrganizationid("JINKO");
                mesasnDto.setWarehouseid("5041");
                mesasnDto.setCustomerid("5041");
                mesasnDto.setDocno(inputBill.getBillNo());
                mesasnDto.setAsntype("YL");
                mesasnDto.setAsnstatus("OK");
                mesasnDto.setAsnreferenced("余料入库");
                mesasnDto.setAsnreferencec("P501");
                mesasnDto.setAsncreationtime(sdf.format(inputBill.getCreateTime()));
                mesasnDto.setTraceid(inputBill.getInputBillDetails().get(0).getTraceid());//托盘号
                mesasnDto.setSerialno(inputBill.getInputBillDetails().get(0).getTraceid());//箱号
                mesasnDto.setExpectedqty(String.valueOf(inputBill.getInputBillDetails().size()));//组件数量
                mesasnDto.setLotatt01(sdf.format(new Date()));
                mesasnDto.setLotatt04(inputBill.getInputBillDetails().get(0).getBatchNo());//入库批次
                mesasnDto.setLotatt08("Y");//质量状态
//                mesasnDto.setLotatt09();//厂家
                mesasnDto.setLotatt12(inputBill.getInputBillDetails().get(0).getBatchNo());//生产批次
                mesasnDto.setLotatt19(inputBill.getInputBillDetails().get(0).getLotatt20());//电阻率
                mesasnDto.setLotatt20(inputBill.getInputBillDetails().get(0).getMaterialLevel());//等级
                mesasnDto.setSku(inputBill.getInputBillDetails().get(0).getMaterialModelCode());
                mesasnDto.setCreatesource("MES");
                List<MesasnOrderDto> mesasnOrderDtos = new ArrayList<>();
                inputBill.getInputBillDetails().stream().forEach(detais -> {
                    MesasnOrderDto mesasnOrderDto = new MesasnOrderDto();
                    mesasnOrderDto.setSku(detais.getMaterialModelCode());
                    mesasnOrderDto.setTraceid(detais.getTraceid());
                    mesasnOrderDto.setSerialno(detais.getSerialNo());
                    mesasnOrderDto.setExpectedqty(String.valueOf(detais.getCount()));//箱重量
                    mesasnOrderDto.setLotatt01(sdf.format(new Date()));
                    mesasnOrderDto.setLotatt04(detais.getBatchNo());//入库批次
//                    mesasnOrderDto.setLotatt09();//厂家
                    mesasnOrderDto.setLotatt12(detais.getBatchNo());//生产批次
                    mesasnOrderDto.setLotatt19(detais.getLotatt19());//电阻率
                    mesasnOrderDto.setLotatt20(detais.getMaterialLevel());//等级
                    mesasnOrderDto.setDedi07(String.valueOf(detais.getCount()));//长度,整箱长度
                    mesasnOrderDto.setDedi08(detais.getBatchNo());//批号,MES下线批
                    mesasnOrderDto.setLotatt08("Y");
                    mesasnOrderDtos.add(mesasnOrderDto);
                });
                mesasnDto.setOrderList(mesasnOrderDtos);
                mesasnDtos.add(mesasnDto);
                //发起WMS入库
                Result result = ybFeignClients.mesasn(mesasnDtos);
                if (result.getCode() != 200) {
                    throw new BusinessException("成品MES入库接口，状态码" + result.getCode() + "，反馈信息" + result.getMessage());
                }
            } catch (Exception ex) {
                throw new BusinessException("出库失败->" + ex.getMessage());
            }
        }*/
    }

    private void outputFeedback(WarehouseOutputBill outputBill, int status) {
        if (OutputBillTypeEnum.辅料出库.getValue().equals(outputBill.getType())) {
            try {
                ApplyAccessoryData applyAccessoryData = new ApplyAccessoryData();
                applyAccessoryData.setCode(outputBill.getBillNo());
                applyAccessoryData.setStatus(status);
                applyAccessoryData.setUserConfirm(BaseContextHandler.getUsername());
                applyAccessoryData.setAccessoryDatas(new ArrayList<>());
                if (status == 0) {
                    for (WarehouseOutputBillDetail warehouseOutputBillDetail : outputBill.getOutputBillDetails()) {
                        ApplyAccessoryData.AccessoryData accessoryData = new ApplyAccessoryData.AccessoryData();
                        if (StringUtils.isNotEmpty(warehouseOutputBillDetail.getManualUniqueCode())) {
                            accessoryData.setUniqueCode(warehouseOutputBillDetail.getManualUniqueCode());
                        } else {
                            accessoryData.setUniqueCode(warehouseOutputBillDetail.getUniqueCode());
                        }
                        accessoryData.setBatchCode(warehouseOutputBillDetail.getBatchNo());
                        accessoryData.setSupplier(warehouseOutputBillDetail.getSupplier());
                        applyAccessoryData.getAccessoryDatas().add(accessoryData);
                    }
                }
                Result<Void> voidResult = accessoryFeignClients.applyAccessoryFeedback(applyAccessoryData);
                if (voidResult.getCode() != 200) {
                    throw new BusinessException("辅料出库反馈状态失败，状态码" + voidResult.getCode() + "，反馈信息" + voidResult.getMessage());
                }
            } catch (Exception e) {
                throw new BusinessException("出库失败->" + e.getMessage());
            }
        }
//        if (OutputBillTypeEnum.WMS退料.getValue().equals(outputBill.getType())) {
//            try {
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                RematDto data = new RematDto();
//                RematHeaderDto header = new RematHeaderDto();
//                List<RematDetailsDto> details = new ArrayList<RematDetailsDto>();
//                header.setCustomerid("5041");
//                header.setDocno(outputBill.getBillNo());
//                header.setAsntype("XBTL");
//                header.setCreationtime(sdf.format(new Date()));
//                header.setHedi01(String.valueOf(outputBill.getCreateUserId()));
//                header.setHedi02(outputBill.getCreateUserName());
//                header.setHedi05(outputBill.getOutputBillDetails().get(0).getWarehouseCode());
//                data.setHeader(header);
//                outputBill.getOutputBillDetails().stream().forEach(entity -> {
//                    RematDetailsDto dto = new RematDetailsDto();
//                    dto.setLineno(String.valueOf(entity.getId()));
//                    dto.setCustomerid(entity.getCustomer());
//                    dto.setSku(entity.getMaterialModelCode());
//                    dto.setQty(String.valueOf(entity.getOutputCount()));
//                    dto.setLotatt08("Y");
//                    if (StringUtils.isNotEmpty(entity.getTraceid())) {
//                        dto.setTraceid(entity.getTraceid());
//                    }
//                    if (StringUtils.isNotEmpty(entity.getSerialNo())) {
//                        dto.setSerialno(entity.getSerialNo());
//                    }
//                    details.add(dto);
//                });
//                data.setDetails(details);
//                Result remat = ybFeignClients.remat(data);
//                if (remat.getCode() != 200) {
//                    throw new BusinessException("车间退料入库接口，状态码" + remat.getCode() + "，反馈信息" + remat.getMessage());
//                }
//            } catch (Exception ex) {
//                throw new BusinessException("出库失败->" + ex.getMessage());
//            }
//        }
//        if (OutputBillTypeEnum.籽晶出库.getValue().equals(outputBill.getType())) {
//            WarehouseOutputBillDetail warehouseOutputBillDetail = new WarehouseOutputBillDetail();
//            if (null != outputBill.getOutputBillDetails() && outputBill.getOutputBillDetails().size() > 0) {
//                warehouseOutputBillDetail = outputBill.getOutputBillDetails().get(0);
//            }
//
//            String inputBillNo = warehouseInputBillDetailService.findDetailsByMaterialBatchNoWarehouseType(warehouseOutputBillDetail.getMaterialModelCode(),
//                    warehouseOutputBillDetail.getBatchNo(), warehouseOutputBillDetail.getWarehouseCode(), InputBillTypeEnum.籽晶入库.getValue());
//
//        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void allotFeedback(WarehouseAllotBillDto warehouseAllotBillDto) {
        if (AllotBillTypeEnum.手动新建.getValue().equals(warehouseAllotBillDto.getAllotType()) ||
                AllotBillTypeEnum.硅料成品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                || AllotBillTypeEnum.刀剖余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                || AllotBillTypeEnum.截断余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                || AllotBillTypeEnum.余料籽晶调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                || AllotBillTypeEnum.副产品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                || AllotBillTypeEnum.硅料调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
        ) {
            warehouseAllotBillDto.getAllotBillDetailDtos().stream().forEach(details -> {
                ReportSapGoodsmvtDto reportSapGoodsmvtDto = new ReportSapGoodsmvtDto();
                List<ReportSapChargItemDto> reportSapChargItemDtos = new ArrayList<>();
                ReportSapChargItemDto reportSapChargItemDto = new ReportSapChargItemDto();
                reportSapChargItemDtos.add(reportSapChargItemDto);
                reportSapGoodsmvtDto.setChargItems(reportSapChargItemDtos);
                if (AllotBillTypeEnum.硅料成品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.刀剖余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.截断余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                ) {
                    reportSapGoodsmvtDto.setCharg(details.getCrystalNo());
                } else {
                    reportSapGoodsmvtDto.setCharg(details.getBatchNo());
                }
                reportSapGoodsmvtDto.setBwart("311");
                reportSapGoodsmvtDto.setWerks("5041");
                if (AllotBillTypeEnum.硅料成品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.刀剖余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.截断余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                ) {
                    reportSapGoodsmvtDto.setUmcha(details.getCrystalNo());
                } else {
                    reportSapGoodsmvtDto.setUmcha(details.getBatchNo());
                }
                reportSapGoodsmvtDto.setUmwrk("5041");
                reportSapGoodsmvtDto.setMatnr(details.getMaterialModelCode());
                reportSapGoodsmvtDto.setMenge(details.getCount() == null ? "0" : details.getCount().toString());
                reportSapGoodsmvtDto.setMeins(details.getUnitName());
                if (AllotBillTypeEnum.刀剖余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.截断余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.余料籽晶调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.副产品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                ) {
                    reportSapGoodsmvtDto.setZfcpFlag("X");
                } else {
                    reportSapGoodsmvtDto.setZfcpFlag("");
                }
                reportSapGoodsmvtDto.setLgort(details.getWarehouseCode());
                WarehouseModel warehouseModel = warehouseModelService.getById(details.getAllotWarehouseId());
                if (!ObjectUtils.isEmpty(warehouseModel)) {
                    reportSapGoodsmvtDto.setUmlgo(warehouseModel.getCode());
                } else {
                    throw new BusinessException("未找到【" + details.getAllotWarehouseName() + "】库位数据");
                }
                reportSapGoodsmvtDto.setProcName("线边仓审核调拨");
                //校验手动调拨情况的批次号取值是否是10位的正确SAP日批次
                if (StringUtils.isBlank(reportSapGoodsmvtDto.getCharg())) {
                    throw new BusinessException("对应批次号异常!");
                } else {
                    if (reportSapGoodsmvtDto.getCharg().length() != 10) {
                        //大于10位是内部批次,要重新赋值SAP批次号
                        if (StringUtils.isNotBlank(details.getCrystalNo()) && details.getCrystalNo().length() == 10) {
                            reportSapGoodsmvtDto.setCharg(details.getCrystalNo());
                        }
                    }
                }

                if (StringUtils.isBlank(reportSapGoodsmvtDto.getUmcha())) {
                    throw new BusinessException("对应收货批次号异常!");
                } else {
                    if (reportSapGoodsmvtDto.getUmcha().length() != 10) {
                        if (StringUtils.isNotBlank(details.getCrystalNo()) && details.getCrystalNo().length() == 10) {
                            reportSapGoodsmvtDto.setUmcha(details.getCrystalNo());
                        }
                    }
                }
                if (reportSapGoodsmvtDto.getCharg().length() != 10) {
                    throw new BusinessException("对应批次号【" + reportSapGoodsmvtDto.getCharg() + "】异常!");
                }
                if (reportSapGoodsmvtDto.getUmcha().length() != 10) {
                    throw new BusinessException("对应收货批次号【" + reportSapGoodsmvtDto.getUmcha() + "】异常!");
                }
                Result result = ybFeignClients.sendSapGoodsmvt(reportSapGoodsmvtDto);
                if (!result.getCode().equals(200)) {
                    throw new BusinessException("报工接口失败，状态码" + result.getCode() + "，反馈信息" + result.getMessage());
                }
                if (AllotBillTypeEnum.手动新建.getValue().equals(warehouseAllotBillDto.getAllotType()) ||
                        AllotBillTypeEnum.硅料成品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())
                        || AllotBillTypeEnum.硅料调拨.getValue().equals(warehouseAllotBillDto.getAllotType())) {
                    //通过唯一的托号回调硅料组托入库调拨成功接口,因为分不清是否为硅料成品还是其他物料,所以统一回调
                    materialCleanFeignClients.updateMaterialGroupStates(details.getBatchNo());
                }
                if (AllotBillTypeEnum.硅料成品调拨.getValue().equals(warehouseAllotBillDto.getAllotType())) {
                    //异步记录自动调拨日志
                    ThreadManager.getThreadPollProxy().execute(() -> {
                        try {
                            //异步记录日志
                            RecycledReportSapRecordDto recycledReportSapRecord = fromRecordDto(reportSapGoodsmvtDto);
                            recycledReportSapRecord.setRecordType(MesToSapTypeEnum.硅料成品调拨.getCode());
                            ybFeignClients.sendRecycledSapRecord(recycledReportSapRecord);
                        } catch (Exception e) {
                            log.error("记录mes发送SAP的硅料成品调拨记录失败");
                        }
                    });
                } else if (AllotBillTypeEnum.刀剖余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())) {
                    //异步记录日志
                    ThreadManager.getThreadPollProxy().execute(() -> {
                        try {
                            //异步记录日志
                            RecycledReportSapRecordDto recycledReportSapRecord = fromRecordDto(reportSapGoodsmvtDto);
                            recycledReportSapRecord.setRecordType(MesToSapTypeEnum.刀剖余料调拨籽晶仓.getCode());
                            ybFeignClients.sendRecycledSapRecord(recycledReportSapRecord);
                        } catch (Exception e) {
                            log.error("记录mes发送SAP的刀剖余料调拨记录失败");
                        }
                    });
                } else if (AllotBillTypeEnum.截断余料调拨籽晶仓.getValue().equals(warehouseAllotBillDto.getAllotType())) {
                    //异步记录日志
                    ThreadManager.getThreadPollProxy().execute(() -> {
                        try {
                            //异步记录日志
                            RecycledReportSapRecordDto recycledReportSapRecord = fromRecordDto(reportSapGoodsmvtDto);
                            recycledReportSapRecord.setRecordType(MesToSapTypeEnum.截断余料调拨籽晶仓.getCode());
                            ybFeignClients.sendRecycledSapRecord(recycledReportSapRecord);
                        } catch (Exception e) {
                            log.error("记录mes发送SAP的截断余料调拨记录失败");
                        }
                    });
                } else {
                    //异步记录日志(除了程序自动生成的其他类型)
                    ThreadManager.getThreadPollProxy().execute(() -> {
                        try {
                            //异步记录日志
                            RecycledReportSapRecordDto recycledReportSapRecord = fromRecordDto(reportSapGoodsmvtDto);
                            recycledReportSapRecord.setRecordType(MesToSapTypeEnum.其他调拨.getCode());
                            ybFeignClients.sendRecycledSapRecord(recycledReportSapRecord);
                        } catch (Exception e) {
                            log.error("记录mes发送SAP的其他调拨记录失败");
                        }
                    });
                }
            });
        }

    }

    public RecycledReportSapRecordDto fromRecordDto(ReportSapGoodsmvtDto dto) {
        RecycledReportSapRecordDto reportSapGoodsmvtDto = new RecycledReportSapRecordDto();
        reportSapGoodsmvtDto.setChargItems(dto.getChargItems());
        reportSapGoodsmvtDto.setAufnr(dto.getAufnr());
        reportSapGoodsmvtDto.setCharg(dto.getCharg());
        reportSapGoodsmvtDto.setBwart(dto.getBwart());
        reportSapGoodsmvtDto.setWerks(dto.getWerks());
        reportSapGoodsmvtDto.setUmcha(dto.getUmcha());
        reportSapGoodsmvtDto.setUmwrk(dto.getUmwrk());
        reportSapGoodsmvtDto.setMatnr(dto.getMatnr());
        reportSapGoodsmvtDto.setMenge(dto.getMenge());
        reportSapGoodsmvtDto.setMeins(dto.getMeins());
        reportSapGoodsmvtDto.setZfcpFlag(dto.getZfcpFlag());
        reportSapGoodsmvtDto.setLgort(dto.getLgort());
        reportSapGoodsmvtDto.setUmlgo(dto.getUmlgo());
        reportSapGoodsmvtDto.setProcName(dto.getProcName());
        reportSapGoodsmvtDto.setCreateDate(new Date());
        reportSapGoodsmvtDto.setCreateUser(BaseContextHandler.getUsername());
        return reportSapGoodsmvtDto;
    }
}
