package com.cim.idm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.data.AuditBox;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.util.sys.SystemPropHelper;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.util.ToSAPMessageUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
@Slf4j
@Service
public class ToSAPServiceImpl {
    
    @Autowired
    private ToSAPMessageUtil toSAPMessageUtil;
	public String PurStockIn(String receiveRequestName, String siteName, String user,
			Map<String, ?> args ) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        //依据采购订单，查询待入库的物料(MATERIALPACKING)
        StringBuffer sql = new StringBuffer();
        //合并行项。zd。2024.8.2
        sql.append(" SELECT mp.RECEIVEREQUESTNAME ,                                                                                                             ").append(SystemPropHelper.CR)
        .append("                        ms.RECEIVEREQUESTDETAILNAME ,                                                                                          ").append(SystemPropHelper.CR)
        .append("                        mp.MATERIALSPECNAME ,                                                                                                  ").append(SystemPropHelper.CR)
        .append("                        mp.OQARESULT ,                                                                                                         ").append(SystemPropHelper.CR)
        .append("                        mp.OQARESULTSTATE ,                                                                                                    ").append(SystemPropHelper.CR)
        .append("                        mp.UNIT, mp.FUNIT,                                                                                                              ").append(SystemPropHelper.CR)
        .append("                        mp.REMARK ,                                                                                                            ").append(SystemPropHelper.CR)
        .append("                        mp.SUPPLIERNAME ,                                                                                                      ").append(SystemPropHelper.CR)
        .append("                        mp.ERPFACTORY ,                                                                                                        ").append(SystemPropHelper.CR)
        .append("                        mp.ERPLOCATION ,                                                                                                       ").append(SystemPropHelper.CR)
        .append("                        mp.SUPPLIERNAME ,                                                                                                      ").append(SystemPropHelper.CR)
        .append("                        m2.IQCFLAG,                                                                                ").append(SystemPropHelper.CR)
        .append("                        SUM(mp.MATERIALQUANTITY) AS MATERIALQUANTITY ,SUM(mp.FQTY) AS FQTY                                                                          ").append(SystemPropHelper.CR)
        .append("                  FROM MATERIALPACKING mp                                                                                                      ").append(SystemPropHelper.CR)
        .append("                  LEFT JOIN MATERIALPACKINGSUB ms                                                                                              ").append(SystemPropHelper.CR)
        .append("                  ON mp.MATERIALPACKINGNAME =ms.MATERIALPACKINGNAME                                                                            ").append(SystemPropHelper.CR)
        .append("                  AND mp.RECEIVEREQUESTNAME =ms.RECEIVEREQUESTNAME                                                                             ").append(SystemPropHelper.CR)
        .append("                  LEFT JOIN MATERIALRECEIVEREQUEST mcr                                                                                         ").append(SystemPropHelper.CR)
        .append("                         ON mp.SITENAME = mcr.SITENAME                                                                                         ").append(SystemPropHelper.CR)
        .append("                        AND mp.RECEIVEREQUESTNAME = mcr.RECEIVEREQUESTNAME                                                                     ").append(SystemPropHelper.CR)
        .append("                  LEFT JOIN MATERIALRECEIVEREQUESTDETAIL m                                                                                     ").append(SystemPropHelper.CR)
        .append("                         ON m.SITENAME = mp.SITENAME                                                                                           ").append(SystemPropHelper.CR)
        .append("                        AND m.RECEIVEREQUESTNAME = mp.RECEIVEREQUESTNAME                                                                       ").append(SystemPropHelper.CR)
        .append("                        AND m.RECEIVEREQUESTDETAILNAME = ms.RECEIVEREQUESTDETAILNAME                                                           ").append(SystemPropHelper.CR)
        .append("                  LEFT JOIN BS_MATERIALFACTORY m2                                                                                              ").append(SystemPropHelper.CR)
        .append("                         ON m2.MATERIALSPECNAME = mp.MATERIALSPECNAME                                                                          ").append(SystemPropHelper.CR)
        .append("                         AND m2.ERPFACTORY =mp.ERPFACTORY                                                                                      ").append(SystemPropHelper.CR)
        .append("                 WHERE mp.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME                                                                             ").append(SystemPropHelper.CR)
        .append("                   AND mp.SITENAME = :SITENAME                                                                                                 ").append(SystemPropHelper.CR)
        .append("                   AND mp.STOCKSTATE = 'Created'                                                                                             ").append(SystemPropHelper.CR)
        .append("                 GROUP BY mp.RECEIVEREQUESTNAME ,ms.RECEIVEREQUESTDETAILNAME ,mp.MATERIALSPECNAME ,mp.OQARESULT,                               ").append(SystemPropHelper.CR)
        .append("                          mp.OQARESULTSTATE,  mp.UNIT ,mp.FUNIT,mp.REMARK ,mp.SUPPLIERNAME ,mp.ERPFACTORY,mp.ERPLOCATION,mp.SUPPLIERNAME,m2.IQCFLAG     ").append(SystemPropHelper.CR);
        
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        List<Map<String, Object>> receiveBoxsQty = new ArrayList<>(); //基于标签收包的维度的数量
        try {

            Map<String,Object> bodyData = new HashMap<>();
            List<Map<String,Object>> itemData = new ArrayList<>();

            for (Map<String, Object> mm : queryForList) {

                //UMWRK 收货工厂
                //LGORT 发货库存地点
                //UMLOG 收货库存地点
                //MATNR 发货物料号
                //UMMAT 收货物料
            	Map<String,Object> item = new HashMap<>();
            	item.put("MATNR", mm.get("MATERIALSPECNAME"));
                item.put("LGORT", mm.get("ERPLOCATION"));
                //item.put("UMWRK", mm.get("ERPFACTORY"));
                item.put("WERKS", mm.get("ERPFACTORY"));
                item.put("BWART","101");
                item.put("LIFNR", mm.get("SUPPLIERNAME"));
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                item.put("MEINS", mm.get("UNIT"));
                item.put("BPMNG", mm.get("FQTY"));//采购价格单位数量
                item.put("BPRME", mm.get("FUNIT"));//采购价格单位
                
                item.put("EBELN", mm.get("RECEIVEREQUESTNAME"));
                item.put("EBELP", mm.get("RECEIVEREQUESTDETAILNAME"));
                item.put("SGTXT", mm.get("REMARK"));
                String insmk = "";
                if("Y".equals((String)mm.get("IQCFLAG"))) {
                	insmk = "2";
                }
                if("NG".equals((String)mm.get("OQARESULT"))) {
                	insmk = "3";
                }
//                String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
                item.put("INSMK", insmk);
                itemData.add(item);

            }
            String sendData = ToSAPMessageUtil.mm067(user, bodyData, itemData);

            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl,"",sendData);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("PurStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg(sendData);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
        	
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

	public String noPOStockIn(String receiveRequestName, String siteName, String user,
			String receiveActNo/* ,List<Map<String,Object>> overReceiveControls */) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        //依据采购订单，查询待入库的物料(MATERIALPACKING)
        String sql = "SELECT mp.RECEIVEREQUESTNAME ,                                                                                                             \r\n" + 
        		"                                mp.RECEIVEREQUESTDETAILNAME ,                                                                                          \r\n" + 
        		"                                mp.MATERIALSPECNAME ,                                                                                                  \r\n" + 
        		"                                mp.OQARESULT ,                                                                                                         \r\n" + 
        		"                                mp.OQARESULTSTATE ,                                                                                                    \r\n" + 
        		"                                mp.UNIT, mp.FUNIT,                                                                                                              \r\n" + 
        		"                                mp.REMARK ,                                                                                                            \r\n" + 
        		"                                mp.SUPPLIERNAME ,                                                                                                      \r\n" + 
        		"                                mp.ERPFACTORY ,                                                                                                        \r\n" + 
        		"                                mp.ERPLOCATION ,                                                                                                       \r\n" + 
        		"                                mp.SUPPLIERNAME ,                                                                                                      \r\n" + 
        		"                                m2.IQCFLAG,                                                                                \r\n" + 
        		"                                SUM(mp.MATERIALQUANTITY) AS MATERIALQUANTITY ,SUM(mp.FQTY) AS FQTY                                                                          \r\n" + 
        		"                          FROM MATERIALPACKING mp                                                                                                                                                                                                       \r\n" + 
        		"                          LEFT JOIN MATERIALRECEIVEREQUEST mcr                                                                                         \r\n" + 
        		"                                 ON mp.SITENAME = mcr.SITENAME                                                                                         \r\n" + 
        		"                                AND mp.RECEIVEREQUESTNAME = mcr.RECEIVEREQUESTNAME                                                                     \r\n" + 
        		"                          LEFT JOIN MATERIALRECEIVEREQUESTDETAIL m                                                                                     \r\n" + 
        		"                                 ON m.SITENAME = mp.SITENAME                                                                                           \r\n" + 
        		"                                AND m.RECEIVEREQUESTNAME = mp.RECEIVEREQUESTNAME                                                                       \r\n" + 
        		"                                AND m.RECEIVEREQUESTDETAILNAME = mp.RECEIVEREQUESTDETAILNAME                                                           \r\n" + 
        		"                          LEFT JOIN BS_MATERIALFACTORY m2                                                                                              \r\n" + 
        		"                                 ON m2.MATERIALSPECNAME = mp.MATERIALSPECNAME                                                                          \r\n" + 
        		"                                 AND m2.ERPFACTORY =mp.ERPFACTORY                                                                                      \r\n" + 
        		"                         WHERE mp.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME                                                                             \r\n" + 
        		"                           AND mp.SITENAME = :SITENAME                                                                                                 \r\n" + 
        		"                           AND mp.RECEIVEACTNO=:RECEIVEACTNO                                                                                             \r\n" + 
        		"                         GROUP BY mp.RECEIVEREQUESTNAME ,mp.RECEIVEREQUESTDETAILNAME ,mp.MATERIALSPECNAME ,mp.OQARESULT,                               \r\n" + 
        		"                                  mp.OQARESULTSTATE,  mp.UNIT ,mp.FUNIT,mp.REMARK ,mp.SUPPLIERNAME ,mp.ERPFACTORY,mp.ERPLOCATION,mp.SUPPLIERNAME,m2.IQCFLAG";

        
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("RECEIVEACTNO", receiveActNo);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        List<Map<String, Object>> receiveBoxsQty = new ArrayList<>(); //基于标签收包的维度的数量
        try {

            Map<String,Object> bodyData = new HashMap<>();
            List<Map<String,Object>> itemData = new ArrayList<>();

            for (Map<String, Object> mm : queryForList) {
            	//获取每个BOX的数量 (用于超收管控）
            	

                //UMWRK 收货工厂
                //LGORT 发货库存地点
                //UMLOG 收货库存地点
                //MATNR 发货物料号
                //UMMAT 收货物料
            	Map<String,Object> item = new HashMap<>();
            	item.put("MATNR", mm.get("MATERIALSPECNAME"));
                item.put("LGORT", mm.get("ERPLOCATION"));
                //item.put("UMWRK", mm.get("ERPFACTORY"));
                item.put("WERKS", mm.get("ERPFACTORY"));
                item.put("BWART","101");
                item.put("LIFNR", mm.get("SUPPLIERNAME"));
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                item.put("MEINS", mm.get("UNIT"));
                item.put("BPMNG", mm.get("FQTY"));//采购价格单位数量
                item.put("BPRME", mm.get("FUNIT"));//采购价格单位
                
                item.put("EBELN", mm.get("RECEIVEREQUESTNAME"));
                item.put("EBELP", mm.get("RECEIVEREQUESTDETAILNAME"));
                item.put("SGTXT", mm.get("REMARK"));
                String insmk = "";
                if("Y".equals((String)mm.get("IQCFLAG"))) {
                	insmk = "2";
                }
                if("NG".equals((String)mm.get("OQARESULT"))) {
                	insmk = "3";
                }
//                String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
                item.put("INSMK", insmk);
                itemData.add(item);

            }
            String sendData = ToSAPMessageUtil.mm067(user, bodyData, itemData);

            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl,"",sendData);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("PurStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg(sendData);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
        	
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    /**
     * 产成品入库给SAP过账
     *
     * @param pc
     * @return undoId
     * @throws Exception
     */
    public String FGStockIn(String pc, String user, String commidate, String opCode) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(SystemPropHelper.CR)
	        .append("SELECT m.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
	        .append("       m.PRODUCTORDER ,").append(SystemPropHelper.CR)
	        .append("       m.PACKINGGRADE ,").append(SystemPropHelper.CR)
	        .append("       m.ERPFACTORY ,").append(SystemPropHelper.CR)
	        .append("       m.ERPLOCATION ,").append(SystemPropHelper.CR)
	        .append("       m.UNIT ,").append(SystemPropHelper.CR)
	        .append("       m.PACKINGGRADE,").append(SystemPropHelper.CR)
	        .append("       m.MATERIALSPECTYPE,").append(SystemPropHelper.CR)
	        .append("       sum(m.MATERIALQUANTITY ) MATERIALQUANTITY ").append(SystemPropHelper.CR)
	        .append("  FROM MATERIALPACKING m ").append(SystemPropHelper.CR)
	        .append("LEFT JOIN BS_MES_SHIPPED bms ON m.materialpackingname = bms.lotname ").append(SystemPropHelper.CR)
	        .append(" WHERE bms.RECEIVE_FLAG <> 'Y' ").append(SystemPropHelper.CR)
	        .append("   AND m.STOCKSTATE = 'Created' ").append(SystemPropHelper.CR)
                .append("   AND m.MATERIALPACKINGNAME IN " + pc).append(SystemPropHelper.CR)
	        .append("GROUP BY m.MATERIALSPECNAME ,m.PRODUCTORDER ,m.PACKINGGRADE ,m.ERPFACTORY ,m.ERPLOCATION ,m.UNIT ,").append(SystemPropHelper.CR)
	        .append("         m.PACKINGGRADE,m.MATERIALSPECTYPE ");
        Map<String, Object> hashMap = new HashMap<String, Object>();
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        String makeFGStockIn = makeFGStockIn(queryForList, user, "");
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeFGStockIn);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP异常:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP异常:" + rmsg);
        } finally {
        	// 将消息记录log表
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(user);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("FGStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(makeFGStockIn);
            erplog.setSendMsg(makeFGStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    // 取消物料入库凭证冲销
    public String cancelShipInter(String undoId, String user) throws Exception {

        String makeFGStockIn = matailInReverse(user, undoId);
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId2 = "";


        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materilUndoUrl, "",
                    makeFGStockIn);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId2 = returnJsonObject.get("MBLNR") == null ? "" : returnJsonObject.get("MBLNR").toString()
                        +"_"+returnJsonObject.get("MJAHR") == null ? "" : returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP异常:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP异常:" + rmsg);
        } finally {
            // 将消息记录log表
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(user);
            erplog.setServerName("WmsToSAP");
            erplog.setEventName("MatailInReverse取消入库冲销");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
//            erplog.setMessageId(undoId);
            erplog.setMessageId(undoId);
            erplog.setSendMsg2(makeFGStockIn);
            erplog.setSendMsg(makeFGStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
//        if (!"S".equals(rcode)) {
//            throw new RuntimeException("SAP返回" + rmsg);
//        }
//        return undoId2;
        return "5000000755";
    }

    public String FGStockIn2(String RECEIVEACTNO, String user) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(SystemPropHelper.CR)
                .append("SELECT m.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
                .append("       m.PRODUCTORDER ,").append(SystemPropHelper.CR)
                .append("       m.PACKINGGRADE ,").append(SystemPropHelper.CR)
                .append("       m.ERPFACTORY ,").append(SystemPropHelper.CR)
                .append("       m.ERPLOCATION ,").append(SystemPropHelper.CR)
                .append("       m.UNIT ,").append(SystemPropHelper.CR)
                .append("       m.PACKINGGRADE,").append(SystemPropHelper.CR)
                .append("       m.MATERIALSPECTYPE,").append(SystemPropHelper.CR)
                .append("       sum(m.MATERIALQUANTITY ) MATERIALQUANTITY ").append(SystemPropHelper.CR)
                .append("  FROM MATERIALPACKING m ").append(SystemPropHelper.CR)
                .append("LEFT JOIN BS_MES_SHIPPED bms ON m.materialpackingname = bms.lotname ").append(SystemPropHelper.CR)
                .append(" WHERE bms.RECEIVE_FLAG <> 'Y' ").append(SystemPropHelper.CR)
                .append("   AND m.STOCKSTATE = 'Created' ").append(SystemPropHelper.CR)
                .append("   AND m.RECEIVEACTNO = :RECEIVEACTNO ").append(SystemPropHelper.CR)
                .append("GROUP BY m.MATERIALSPECNAME ,m.PRODUCTORDER ,m.PACKINGGRADE ,m.ERPFACTORY ,m.ERPLOCATION ,m.UNIT ,").append(SystemPropHelper.CR)
                .append("         m.PACKINGGRADE,m.MATERIALSPECTYPE ");
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEACTNO", RECEIVEACTNO);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        String makeFGStockIn = makeFGStockIn(queryForList, user, RECEIVEACTNO);
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeFGStockIn);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP异常:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP异常:" + rmsg);
        } finally {
            // 将消息记录log表
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(user);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("FGStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(RECEIVEACTNO);
            erplog.setSendMsg2(makeFGStockIn);
            erplog.setSendMsg(makeFGStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    /**
     * 手动入库处理FGStockIn请求
     * 该方法负责将特定的物料信息发送到SAP系统，并处理返回的结果
     *
     * @param bodyJson 包含物料信息的JSON字符串
     * @param user 执行操作的用户
     * @return 返回物料凭证相关的ID
     * @throws Exception 如果与SAP系统的通信或其他错误发生时抛出异常
     */
    public String FGStockInByManulIn(String bodyJson, String user) throws Exception {
        // 初始化SAP返回信息、结果代码、消息文本和撤销ID
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";

        try {
            // 发送物料信息到SAP系统
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    bodyJson);

            // 解析SAP系统的返回信息
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            // 提取返回信息中的RETURN对象
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            // 如果返回结果状态为"S"（成功），则拼接物料凭证号和凭证年度作为undoId
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            // 记录异常日志，并抛出运行时异常
            log.error("WMS请求SAP异常:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP异常:" + rmsg);
        } finally {
            // 将消息记录log表
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(user);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("FGStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId("");
            erplog.setSendMsg2(bodyJson);
            erplog.setSendMsg(bodyJson);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }

        // 如果返回结果状态不是"S"，则抛出异常
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }

        // 返回物料凭证相关的ID
        return undoId;
    }

    
  //取消成品入库接口。zd.2024.8.29
    public String cancelFGStockIn(List<String> boxList, String user,String siteName) throws Exception {
        
    	String sql="SELECT m.MATERIALSPECNAME ,\r\n" + 
    			"	               m.PRODUCTORDER ,\r\n" + 
    			"	               m.PACKINGGRADE ,\r\n" + 
    			"	               m.ERPFACTORY ,\r\n" + 
    			"	               m.ERPLOCATION ,\r\n" + 
    			"	               m.UNIT ,\r\n" + 
    			"	               m.PACKINGGRADE,\r\n" + 
    			"	               m.MATERIALSPECTYPE,\r\n" + 
    			"	               sum(m.MATERIALQUANTITY ) MATERIALQUANTITY \r\n" + 
    			"	          FROM MATERIALPACKING m 	         \r\n" + 
    			"	         WHERE m.SITENAME = :SITENAME \r\n" + 
    			"	         	AND m.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
    			"	        GROUP BY m.MATERIALSPECNAME ,m.PRODUCTORDER ,m.PACKINGGRADE ,m.ERPFACTORY ,m.ERPLOCATION ,m.UNIT ,\r\n" + 
    			"	                 m.PACKINGGRADE,m.MATERIALSPECTYPE ";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        String makeCancelFGStockIn = makeCancelFGStockIn(queryForList, user);
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
            		makeCancelFGStockIn);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP异常:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP异常:" + rmsg);
        } finally {
        	// 将消息记录log表
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(user);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("CancelFGStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            //erplog.setMessageId(RECEIVEACTNO);
            erplog.setSendMsg2(makeCancelFGStockIn);
            erplog.setSendMsg(makeCancelFGStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    /**
     * 成品入库
     *
     * @param list
     * @param eventUser
     * @return
     * @throws JsonMappingException
     * @throws JsonProcessingException
     */
    public String makeFGStockIn(List<Map<String, Object>> list, String eventUser, String receiveRequestName) throws JsonMappingException, JsonProcessingException {

        if (list == null || list.size() < 1) {
            return "";
        }

        Map<String,Object> bodyData = new HashMap<>();
        List<Map<String,Object>> itemsData = new ArrayList<>();

        for (Map<String, Object> mm : list) {
            Map<String,Object> item = new HashMap<>();
            //UMWRK 收货工厂
            //LGORT 发货库存地点
            //UMLOG 收货库存地点
            //MATNR 发货物料号
            //UMMAT 收货物料

            item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("LGORT", mm.get("ERPLOCATION"));
            item.put("WERKS", mm.get("ERPFACTORY"));

//            item.put("BWART", "531");
            if("FG".equals((String)mm.get("MATERIALSPECTYPE")) ) {
            	item.put("BWART", "101"); //产成品，移动类型 101
            }else if("BFG".equals((String)mm.get("MATERIALSPECTYPE")) ) {
            	item.put("BWART", "531"); //副产品， 移动类型 531
            }else if("FGDEV".equals((String)mm.get("MATERIALSPECTYPE")) ) {
            	item.put("BWART", "511"); //研发品， 移动类型 511
            }else {
            	item.put("BWART", "101"); //为了兼容之前的未提到的成品，统一暂用 101
            }
           
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            item.put("AUFNR", mm.get("PRODUCTORDER"));
            item.put("BPMNG", "");
            item.put("BPRME", "");
            item.put("SGTXT", mm.get("REMARK"));
            String insmk = "";
            if (StringUtils.isEmpty((String)mm.get("PACKINGGRADE"))) {
            	insmk = "2";
            }else if ("NG".equals((String)mm.get("PACKINGGRADE"))) {
                insmk = "3";
            }
//            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
            item.put("INSMK", insmk);
            itemsData.add(item);

        }
       	String sendData = ToSAPMessageUtil.mm067(eventUser, bodyData, itemsData);
        return sendData;
    }
   //取消成品入库接口字段。zd.2024.8.29
    public String makeCancelFGStockIn(List<Map<String, Object>> list, String eventUser) throws JsonMappingException, JsonProcessingException {

        if (list == null || list.size() < 1) {
            return "";
        }

        Map<String,Object> bodyData = new HashMap<>();
        List<Map<String,Object>> itemsData = new ArrayList<>();

        for (Map<String, Object> mm : list) {
            Map<String,Object> item = new HashMap<>();
            //UMWRK 收货工厂
            //LGORT 发货库存地点
            //UMLOG 收货库存地点
            //MATNR 发货物料号
            //UMMAT 收货物料

            item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("LGORT", mm.get("ERPLOCATION"));
            item.put("WERKS", mm.get("ERPFACTORY"));
            if("FG".equals((String)mm.get("MATERIALSPECTYPE")) ) {
            	item.put("BWART", "102"); //产成品，移动类型 102
            }else if("BFG".equals((String)mm.get("MATERIALSPECTYPE")) ) { 
            	item.put("BWART", "532"); //副产品， 移动类型 532
            }else {
            	item.put("BWART", "102"); //为了兼容之前的未提到的成品，统一暂用 102
            }
           
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            item.put("AUFNR", mm.get("PRODUCTORDER"));
            item.put("BPMNG", "");
            item.put("BPRME", "");
            item.put("SGTXT", mm.get("REMARK"));
            String insmk = "";
            if (StringUtils.isEmpty((String)mm.get("PACKINGGRADE"))) {
            	insmk = "2";
            }else if ("NG".equals((String)mm.get("PACKINGGRADE"))) {
                insmk = "3";
            }
//            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
            item.put("INSMK", insmk);
            itemsData.add(item);

        }
       	String sendData = ToSAPMessageUtil.mm067(eventUser, bodyData, itemsData);
        return sendData;
    }

    /**
     * 取消物料入库冲销
     *
     * @param
     * @param
     * @return
     * @throws JsonMappingException
     * @throws JsonProcessingException
     */
    public String matailInReverse(String user, String undoId) throws JsonMappingException, JsonProcessingException {

//        if (list == null || list.size() < 1) {
//            return "";
//        }
//
//        Map<String,Object> bodyData = new HashMap<>();
//        List<Map<String,Object>> itemsData = new ArrayList<>();
//
//        for (Map<String, Object> mm : list) {
//            Map<String,Object> item = new HashMap<>();
//            //UMWRK 收货工厂
//            //LGORT 发货库存地点
//            //UMLOG 收货库存地点
//            //MATNR 发货物料号
//            //UMMAT 收货物料
//
//            item.put("MATNR", mm.get("MATERIALSPECNAME"));
//            item.put("LGORT", mm.get("ERPLOCATION"));
//            item.put("WERKS", mm.get("ERPFACTORY"));
//            if("FG".equals((String)mm.get("MATERIALSPECTYPE")) ) {
//                item.put("BWART", "101"); //产成品，移动类型 101
//            }else if("BFG".equals((String)mm.get("MATERIALSPECTYPE")) ) {
//                item.put("BWART", "531"); //副产品， 移动类型 531
//            }else if("FGDEV".equals((String)mm.get("MATERIALSPECTYPE")) ) {
//                item.put("BWART", "511"); //研发品， 移动类型 511
//            }else {
//                item.put("BWART", "101"); //为了兼容之前的未提到的成品，统一暂用 101
//            }
//
//            item.put("MENGE", mm.get("MATERIALQUANTITY"));
//            item.put("MEINS", mm.get("UNIT"));
//            item.put("AUFNR", mm.get("PRODUCTORDER"));
//            item.put("BPMNG", "");
//            item.put("BPRME", "");
//            item.put("SGTXT", mm.get("REMARK"));
//            String insmk = "";
//            if (StringUtils.isEmpty((String)mm.get("PACKINGGRADE"))) {
//                insmk = "2";
//            }else if ("NG".equals((String)mm.get("PACKINGGRADE"))) {
//                insmk = "3";
//            }
////            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
//            item.put("INSMK", insmk);
//            itemsData.add(item);
//
//        }
//String sendData = ToSAPMessageUtil.mm067(eventUser, bodyData, itemsData);
        String[] parts = undoId.split("_");
        String MBLNR = parts[0];
        String MJAHR = parts[1];
        String uniqueID = UUID.randomUUID().toString();
        JSONObject MainData = new JSONObject(true);
        Map<String,String> headJSonData = new HashMap<>();
        Map<String,String> bodyJSonData = new HashMap<>();
        MainData.put("HEAD",headJSonData);
        MainData.put("BODY",bodyJSonData);
        headJSonData.put("INTF_ID","MM068");
        headJSonData.put("SRC_SYSTEM","WMS");
        headJSonData.put("DEST_SYSTEM","SAP");
        headJSonData.put("SRC_MSGID",uniqueID);
        headJSonData.put("BACKUP1","");
        headJSonData.put("BACKUP2","");

        bodyJSonData.put("MBLNR", MBLNR);
        bodyJSonData.put("MJAHR", MJAHR);

        String sendData = MainData.toJSONString();
        return sendData;
    }
    public String qtrNoInvoice(String receiveRequestName, String siteName, String reActo, String user) {

        String rcode;
        String vbillcode = null;
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT  'ZK4A'  billtype,'4A-01' iotype,\r\n" +
                "		 T.ERPFACTORY ERPFACTORY,\r\n" +
                "		 'Y' issign,\r\n" +
                "		 T.ERPLOCATION store,\r\n" +
                "		 TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') billtime,\r\n" +
                "		 T.LASTEVENTUSER manager,\r\n" +
                "		 T.LASTEVENTUSER maker,\r\n" +
                "		 M2.ERPID srcbillid,\r\n" +
                "		 'N' freplenishflag,\r\n" +
                "		 M.ERPDETAILID srcbillbid,\r\n" +
                "		 T.MATERIALSPECNAME mat,\r\n" +
                "		 '1' matversion,\r\n" +
                "		 M.MATERIALUNIT unit,\r\n" +
                "		  M.MATERIALUNIT astunit,\r\n" +
                "		 '1.00/1.00' changerate,\r\n" +
                "		 TO_CHAR(T.MAKEDATE, 'YYYY-MM-DD HH24:MI:SS') proddate,\r\n" +
                "		 TO_CHAR(T.EXPIRINGDATE, 'YYYY-MM-DD HH24:MI:SS') expdate,\r\n" +
                "		 T.CHARGE batchcode,\r\n" +
                "		 TT.QTY num,\r\n" +
                "		 TT.QTY astnum,\r\n" +
                "		 TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') indate,\r\n" +
                "		 T.PHASE jd,\r\n" +
                "		  T.SDK_ID sdk,\r\n" +
                "		 T.LOCATIONNAME loc\r\n" +
                "		 FROM MATERIALPACKINGSUB TT\r\n" +
                "		 LEFT JOIN MATERIALPACKING T ON TT.MATERIALPACKINGNAME  = T.MATERIALPACKINGNAME \r\n" +
                "		 LEFT JOIN MATERIALRECEIVEREQUESTDETAIL M\r\n" +
                "		 ON TT.RECEIVEREQUESTNAME = M.RECEIVEREQUESTNAME\r\n" +
                "		  AND TT.RECEIVEREQUESTDETAILNAME = M.RECEIVEREQUESTDETAILNAME\r\n" +
                "		 LEFT JOIN MATERIALRECEIVEREQUEST M2\r\n" +
                "		  ON TT.RECEIVEREQUESTNAME = M2.RECEIVEREQUESTNAME\r\n" +
                "		 WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME\r\n" +
                "		 AND T.SITENAME = :SITENAME\r\n" +
                "		 AND T.STOCKSTATE = 'Created' ");

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        try {
            JSONObject sendData = new JSONObject(true);
            JSONObject sapreturnData = new JSONObject(true);

            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();
            body.put("ITEM", itemArray);
            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            //uniqueID
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
            //凭证抬头文本  即入库单号
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);
            //标识
            body.put("ZFLAG", "");


            for (Map<String, Object> mm : queryForList) {
                JSONObject item = new JSONObject(true);
                //UMWRK 收货工厂
                //LGORT 发货库存地点
                //UMLOG 收货库存地点
                //MATNR 发货物料号
                //UMMAT 收货物料

                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                item.put("UMMAT", mm.get("RECEIVEREQUESTNAME"));
                item.put("UMLGO", mm.get("INSTORE"));
                item.put("LGORT", mm.get("OUTSTORE"));
                item.put("UMWRK", mm.get("INORG"));
                item.put("WERKS", mm.get("OUTORG"));
                item.put("BWART", "311");
                item.put("LIFNR", mm.get("SUPPLIERNAME"));
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                item.put("MEINS", mm.get("UNIT"));
                item.put("BPMNG", mm.get("MATERIALQUANTITY"));
                item.put("BPRME", mm.get("UNIT"));
                item.put("SGTXT", mm.get("REMARK"));
                String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(), "END") ? "" : "X";
                item.put("INSMK", insmk);
                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);


            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            rcode = receiveJsonObject.get("code").toString();
            rmsg = receiveJsonObject.get("message").toString();
            vbillcode = receiveJsonObject.get("vbillcode").toString();
            // 将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("qtr");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(reActo);
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return vbillcode;
    }

    public String interCompanyAllocationStockIn(String shipRequestName, String siteName, String eventUser) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" ");
        sql.append(" SELECT T.SHIPREQUESTNAME, ").append(SystemPropHelper.CR)
                .append("        T.SHIPREQUESTDETAILNAME, ").append(SystemPropHelper.CR)
                .append("        M2.SHIPREQUESTTYPE , ").append(SystemPropHelper.CR)
                .append("        M2.SHIPREQUESTDETAILTYPE, ").append(SystemPropHelper.CR)
                .append("        T.ERPFACTORY inorg, ").append(SystemPropHelper.CR)
                .append("        T.ERPLOCATION instore, ").append(SystemPropHelper.CR)
                .append("        M2.ERPID , ").append(SystemPropHelper.CR)
                .append("        T.LASTEVENTUSER, ").append(SystemPropHelper.CR)
                .append("        M2.ERPFACTORY outorg, ").append(SystemPropHelper.CR)
                .append("        M2.ERPLOCATION outstore, ").append(SystemPropHelper.CR)
                .append("        M.ERPDETAILID, ").append(SystemPropHelper.CR)
                .append("        T.MATERIALSPECNAME, ").append(SystemPropHelper.CR)
                .append("        M.UNIT, ").append(SystemPropHelper.CR)
                .append("        TO_CHAR(T.MAKEDATE, 'YYYY-MM-DD') proddate, ").append(SystemPropHelper.CR)
                .append("        TO_CHAR(T.EXPIRINGDATE, 'YYYY-MM-DD') expdate, ").append(SystemPropHelper.CR)
                .append("        T.CHARGE batchcode, ").append(SystemPropHelper.CR)
                .append("        T.MATERIALQUANTITY, ").append(SystemPropHelper.CR)
                .append("        T.PHASE jd, ").append(SystemPropHelper.CR)
                .append("        T.SDK_ID sdk, ").append(SystemPropHelper.CR)
                .append("        T.LOCATIONNAME ").append(SystemPropHelper.CR)
                .append(" FROM MATERIALPACKING T ").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUESTDETAIL M ").append(SystemPropHelper.CR)
                .append("       ON T.SHIPREQUESTNAME = M.SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("       AND T.SHIPREQUESTDETAILNAME = M.SHIPREQUESTDETAILNAME ").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUEST M2 ").append(SystemPropHelper.CR)
                .append("       ON T.SHIPREQUESTNAME = M2.SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("WHERE T.SHIPREQUESTNAME = :SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("  AND T.SITENAME = :SITENAME ").append(SystemPropHelper.CR)
                .append("  AND T.STOCKSTATE = 'StockOut' ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String makeAlloctionStockIn = makeInterCompanyAlloctionStockIn(queryForList, eventUser);
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeAlloctionStockIn/* sendData.toJSONString() */);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            undoId = "";
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        } finally {
            //保存log
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(eventUser);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("AlloctionStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(shipRequestName);
            erplog.setSendMsg2(makeAlloctionStockIn);
            erplog.setSendMsg(makeAlloctionStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //调拨入库（对于SAP,不同组织间调拨相当于采购入库，移动类型 101）
    public String makeAlloctionStockIn(List<Map<String, Object>> queryForList, String user) throws JsonMappingException, JsonProcessingException {

        if (queryForList == null || queryForList.size() < 1) {
            return "";
        }
        
        Map<String,Object> bodyData = new HashMap<>();
        List<Map<String,Object>> itemData = new ArrayList<>();

        for (Map<String, Object> mm : queryForList) {
        	Map<String,Object> item = new HashMap<>();
            //MATNR	发货物料号
            //UMMAT	收货物料
            //WERKS	发货工厂
            //UMWRK	收货工厂
            //LGORT	发货库存地点
            //UMLGO	收货库存地点
            //BWART	移动类型
            //SOBKZ	特殊库存标识
            //LIFNR	供应商编码
            //MENGE	数量
            //MEINS	单位
            //BPMNG	采购价格单位数量
            //BPRME	采购价格单位
            //EBELN	采购订单编码
            //EBELP	采购订单项目编码
            //SGTXT	项目文本
            //KOSTL	成本中心
            //MAT_KDAUF	发货销售订单编码
            //MAT_KDPOS	发货销售订单项目编码
            //UMMAT_KDAUF	收货销售订单编码
            //UMMAT_KDPOS	收货销售订单项目编码
            //ELIKZ	交货已完成标识
            //AUFNR	订单号
            //AUFPS	订单项目编号
            //RSNUM	预留/相关需求的编号
            //RSPOS	预留/相关需求的项目编号
            //RSART	记录类型
            //KZEAR	该预留的最后发货
            //UMMAT	收货物料
            //UMCHA	收货/发货批量
            //PRCTR	利润中心
            //KZBEW	移动标识
            //GRUND	移动原因
            //SAKTO	总帐科目编号
            //ZLLORDER	自定义领料单号
            //ZLLITEM	自定义领料单行号
            //INSMK	库存类型
        	item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("LGORT", mm.get("ERPLOCATION"));
            //item.put("UMWRK", mm.get("ERPRECEIVEFACTORY"));
            item.put("WERKS", mm.get("ERPRECEIVEFACTORY"));
            item.put("BWART","101");
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            //跨组织调拨入库放入交货单和交货单行项。zd.2024.8.7
            item.put("VBELN_IM", mm.get("SHIPREQUESTNAME"));
            item.put("VBELP_IM", mm.get("SHIPREQUESTDETAILNAME"));
            //m2.SALESORDER ,m2.SALESORDERDETAILNO,
            item.put("EBELN", mm.get("SALESORDER"));
            item.put("EBELP", mm.get("SALESORDERDETAILNO"));
            item.put("EBELN", mm.get("SALESORDER"));
            
            item.put("SOBKZ", mm.get("SOBKZ"));
            item.put("UMMAT_KDAUF", mm.get("SENDSALESORDER"));
            item.put("UMMAT_KDPOS", mm.get("SENDSALESORDERDETAILNO"));
            itemData.add(item);
        }
        String sendData = ToSAPMessageUtil.mm067(user, bodyData, itemData);

        return sendData;
    }

    public String AlloctionStockIn(String shipRequestName, String siteName, String eventUser,String erpLocation) throws Exception {
    	String sql="  SELECT m.SHIPREQUESTNAME ,\r\n" + 
    			"               m3.SHIPREQUESTDETAILNAME ,\r\n" + 
    			"               m.MATERIALSPECNAME ,\r\n" + 
    			"               m2.ERPFACTORY ,\r\n" + 
    			"              :ERPLOCATION ERPLOCATION, \r\n" + 
    			"               m2.CUSTOMERNO ERPRECEIVEFACTORY ,m3.SALESORDER ,m3.SALESORDERDETAILNO,\r\n" + 
    			"               m.UNIT ,m3.SENDSALESORDER ,m3.SENDSALESORDERDETAILNO, \r\n" + 
    			"               CASE WHEN m3.SENDSALESORDER IS NOT NULL THEN 'E' ELSE '' END  SOBKZ,\r\n" + 
    			"               sum(m4.QTY) MATERIALQUANTITY\r\n" + 
    			"          FROM MATERIALPACKING m\r\n" + 
    			"        LEFT JOIN MATERIALSHIPREQUEST m2 \r\n" + 
    			"               ON m.SITENAME = m2.SITENAME \r\n" + 
    			"              AND m.SHIPREQUESTNAME = m2.SHIPREQUESTNAME \r\n" + 
    			"        LEFT JOIN MATERIALPACKINGSUB m4 \r\n" + 
    			"        ON m.MATERIALPACKINGNAME =m4.MATERIALPACKINGNAME \r\n" + 
    			"        AND m.SHIPREQUESTNAME =m4.RECEIVEREQUESTNAME \r\n" + 
    			"        LEFT JOIN MATERIALSHIPREQUESTDETAIL m3 \r\n" + 
    			"               ON m.SITENAME = m3.SITENAME \r\n" + 
    			"              AND m.MATERIALSPECNAME = m3.MATERIALSPECNAME \r\n" + 
    			"              AND m3.SHIPREQUESTNAME = m4.RECEIVEREQUESTNAME \r\n" + 
    			"         WHERE 1=1\r\n" + 
    			"           AND m2.SHIPREQUESTTYPE = 'NLCC'\r\n" + 
    			"           AND m.SITENAME = :SITENAME\r\n" + 
    			"           AND m.STOCKSTATE = 'StockOut'\r\n" + 
    			"           AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME \r\n" + 
    			"        GROUP BY m.SHIPREQUESTNAME ,m3.SHIPREQUESTDETAILNAME ,m.MATERIALSPECNAME ,m3.SALESORDER ,m3.SALESORDERDETAILNO,\r\n" + 
    			"        m3.SENDSALESORDER ,m3.SENDSALESORDERDETAILNO,m2.ERPFACTORY ,m2.CUSTOMERNO ,m.UNIT ";

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("ERPLOCATION", erpLocation);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String makeAlloctionStockIn = makeAlloctionStockIn(queryForList, eventUser);
        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeAlloctionStockIn/* sendData.toJSONString() */);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            undoId = "";
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        } finally {
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(eventUser);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("AlloctionStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(shipRequestName);
            erplog.setSendMsg2(makeAlloctionStockIn);
            erplog.setSendMsg(makeAlloctionStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    public String makeInterCompanyAlloctionStockIn(List<Map<String, Object>> queryForList, String user) throws JsonMappingException, JsonProcessingException {

        if (queryForList == null || queryForList.size() < 1) {
            return "";
        }

        Map<String, Object> bodyData = new HashMap<>();

        //uniqueID
        String uniqueID = UUID.randomUUID().toString();


        /*
         BODY
         */
        bodyData.put("ITEMID", uniqueID);

        //过账日期
        bodyData.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证日期
        bodyData.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证抬头文本  即入库单号
        bodyData.put("BKTXT", uniqueID);
        //用户名
        bodyData.put("USNAM", user);
        //标识
        bodyData.put("ZFLAG", "");

        List<Map<String, Object>> items = new ArrayList<>();
        for (Map<String, Object> mm : queryForList) {
            Map<String, Object> itemData = new HashMap<>();

            itemData.put("MATNR", mm.get("MATERIALSPECNAME"));
            itemData.put("UMMAT", "");
            itemData.put("UMLGO", mm.get("INSTORE"));
            itemData.put("LGORT", mm.get("OUTSTORE"));
            itemData.put("UMWRK", mm.get("INORG"));
            itemData.put("WERKS", mm.get("OUTORG"));
            itemData.put("BWART", "101");
            itemData.put("LIFNR", mm.get("SUPPLIERNAME"));
            itemData.put("MENGE", mm.get("MATERIALQUANTITY"));
            itemData.put("MEINS", mm.get("UNIT"));
            itemData.put("BPMNG", "");
            itemData.put("BPRME", "");
            itemData.put("SGTXT", mm.get("REMARK"));
            itemData.put("VBELN_IM", mm.get("SHIPREQUESTNAME"));
            itemData.put("VBELP_IM", mm.get("SHIPREQUESTDETAILNAME"));
//        	itemData.put("EBELN" , );//新增一个字段去传销售订单号
//        	itemData.put("EBELP" , );
//            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
            //质检批如何判定， 如果是质检批，则 INSMK 值为2
            itemData.put("INSMK", "");
            items.add(itemData);
        }
        String sendData = ToSAPMessageUtil.mm067(user, bodyData, items);
        return sendData;
    }

    /**
     * 销售退
     *
     * @param shipRequestName
     * @param siteName
     * @param eventUser
     * @return
     * @throws Exception
     */
    public String SaleReturn(String shipRequestName, String siteName, String eventUser,String commitDate, String opcode ) throws Exception {
    	String sql="SELECT\r\n" + 
    			"	mp.RECEIVEREQUESTDETAILNAME SHIPREQUESTDETAILNAME,\r\n" + 
    			"	mp.ERPLOCATION,\r\n" + 
    			"	count(*) AS ZROL,\r\n" + 
    			"	sum(mp.MATERIALQUANTITY) AS MATERIALQUANTITY\r\n" + 
    			" FROM\r\n" + 
    			"	MATERIALPACKING mp\r\n" + 
    			" LEFT JOIN MATERIALSHIPREQUEST ms ON\r\n" + 
    			"	mp.RECEIVEREQUESTNAME = ms.SHIPREQUESTNAME\r\n" + 
    			"	AND mp.SITENAME = ms.SITENAME\r\n" + 
    			" LEFT JOIN MATERIALSHIPREQUESTDETAIL md ON\r\n" + 
    			"	mp.RECEIVEREQUESTNAME = md.SHIPREQUESTNAME\r\n" + 
    			"	AND mp.RECEIVEREQUESTDETAILNAME = md.SHIPREQUESTDETAILNAME\r\n" + 
    			"	AND mp.SITENAME = md.SITENAME\r\n" + 
    			" WHERE\r\n" + 
    			"	1 = 1\r\n" + 
    			"	 AND mp.RECEIVEREQUESTNAME = :SHIPREQUESTNAME      \r\n" + 
    			"    AND mp.SITENAME = :SITENAME       \r\n" + 
    			"   AND (mp.STOCKSTATE = 'StockOut' OR mp.STOCKSTATE = 'Created' ) \r\n" + 
    			" GROUP BY\r\n" + 
    			"	mp.RECEIVEREQUESTDETAILNAME ,\r\n" + 
    			"	mp.ERPLOCATION";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        if (queryForList == null || queryForList.size() < 1) {
        	throw new RuntimeException("无需提交，已完成作业"); 
        }
        String rcode="",rmsg="",undoId="";
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("DEST_SYSTEM", "SAP");
            header.put("INTF_ID", "SD023");
            header.put("SRC_SYSTEM", "WMS");
            String uniqueID = UUID.randomUUID().toString();
            header.put("SRC_MSGID", uniqueID);
            header.put("BACKUP1", uniqueID);
            header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
            //交货单号
            body.put("VBELN", shipRequestName);
            //实际过账日期
            body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
            //发送日期
            body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //操作类型（过账）
            body.put("Z_OPTION", "1");

            if (queryForList.size() >= 1) {
                for (Map<String, Object> mm : queryForList) {
                    JSONObject item = new JSONObject(true);

                    //交货单行号
                    item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
                    //库存地点
                    item.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    item.put("Z_ROL", mm.get("ZROL"));
                    //实际发货平方米
                    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                    itemArray.add(item);
                }
                body.put("ITEMS", itemArray);
            }else {
                for (Map<String, Object> mm : queryForList) {

                    //交货单行号
                    body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
                    //库存地点
                    body.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    body.put("Z_ROL", mm.get("ZROL"));   //COUNT
                    //实际发货平方米
                    body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                }
            }

            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            //销售交货单过账不返回物料凭证,且RETURN为JsonArray
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = "S";
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("调拨出库(NLCC)");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    private String makeSaleReturn(List<Map<String, Object>> queryForList, String eventUser, String shipRequestName) {
    	Map<String,Object> bodyData = new HashMap<>();
        List<Map<String,Object>> itemData = new ArrayList<>();
        bodyData.put("VBELN", shipRequestName);
        bodyData.put("Z_OPTION","2");
  
        for(Map<String,Object> mm: queryForList) {
        	Map<String,Object> item = new HashMap<>();
        	item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
		    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
		    item.put("LGORT", mm.get("ERPLOCATION"));
		    item.put("Z_ROL", mm.get("ZROL"));
		    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));
		    itemData.add(item);
        }

        String toSapMsg = ToSAPMessageUtil.sd023(eventUser, bodyData, itemData);
		return toSapMsg;
	}

	/**
     * 生产退料
     *
     * @param shipRequestName
     * @param siteName
     * @param eventUser
     * @return
     * @throws Exception
     */
    public String ReturnMaterial(String shipRequestName, String siteName, String eventUser) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" ");
        sql.append(" SELECT M2.SHIPREQUESTTYPE billtype, ");
        sql.append(" T.ERPFACTORY ORG, ");
        sql.append("  M2.ERPID srcbillid, ");
        sql.append(" T.ERPLOCATION store, ");
        sql.append(" M2.SHIPREQUESTDETAILTYPE iotype, ");
        sql.append(" TO_CHAR(SYSDATE, 'YYYY-MM-DD') billtime, ");
        sql.append(" T.LASTEVENTUSER manager, ");
        sql.append(" 'Y' freplenishflag, ");
        sql.append(" 'N' back, ");
        sql.append(" T.LASTEVENTUSER maker, ");
        sql.append(" M.ERPDETAILID srcbillbid, ");
        sql.append(" M.MATERIALSPECNAME mat, ");
        sql.append(" '1' matversion, ");
        sql.append(" TO_CHAR(T.MAKEDATE,'YYYY-MM-DD') proddate, ");
        sql.append(" TO_CHAR(T.EXPIRINGDATE,'YYYY-MM-DD') expdate, ");
        sql.append(" M.UNIT unit, ");
        sql.append(" M.UNIT astunit, ");
        sql.append(" '1.00/1.00' changerate, ");
        sql.append(" T.CHARGE batchcode, ");
        sql.append(" M.REQUESTQUANTITY shouldoutastnum, ");
        sql.append(" 0 - T.MATERIALQUANTITY outastnum, ");
        sql.append(" 0 - T.MATERIALQUANTITY outnum, ");
        sql.append(" TO_CHAR(SYSDATE, 'YYYY-MM-DD') outdate, ");
        sql.append(" T.LOCATIONNAME loc, ");
        sql.append(" T.PHASE jd, ");
        sql.append(" T.SDK_ID sdk ");
        sql.append(" FROM MATERIALPACKING T ");
        sql.append(" LEFT JOIN MATERIALSHIPREQUESTDETAIL M ");
        sql.append(" ON T.RECEIVEREQUESTNAME = M.SHIPREQUESTNAME ");
        sql.append(" AND T.RECEIVEREQUESTDETAILNAME = M.SHIPREQUESTDETAILNAME ");
        sql.append(" AND T.SITENAME = M.SITENAME ");
        sql.append(" LEFT JOIN MATERIALSHIPREQUEST M2 ");
        sql.append(" ON M.SHIPREQUESTNAME = M2.SHIPREQUESTNAME ");
        sql.append(" WHERE T.RECEIVEREQUESTNAME = :SHIPREQUESTNAME ");
        sql.append(" AND T.SITENAME = :SITENAME ");
        sql.append(" AND T.STOCKSTATE = 'StockOut' ");
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        if (queryForList == null || queryForList.size() < 1) {
            throw new RuntimeException("无需提交，已完成作业");
        }
        String makeReturnMaterials = makeSaleOut(queryForList, eventUser);

        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeReturnMaterials);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        }

        // run方法具体重写
        ErpMessageLog erplog = new ErpMessageLog();
        erplog.setEventUser("WSC");
        erplog.setServerName("WmsToErp");
        erplog.setEventName("SaleReturn");
        erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
        erplog.setMessageId(shipRequestName);
        erplog.setSendMsg2(makeReturnMaterials);
        erplog.setSendMsg(makeReturnMaterials);
        erplog.setReturnMsg2(sapreturn);
        erplog.setResultCode(rcode);
        MessageLogUtil.writeMessageLog(erplog);

        if (!"S".equals(rcode)) {
            throw new RuntimeException("NC返回" + rmsg);
        }
        return undoId;
    }

    /**
     * 销售出库消息封装
     *
     * @param list
     * @param eventUser
     * @return
     * @throws JsonMappingException
     * @throws JsonProcessingException
     */
    public String makeSaleOut(List<Map<String, Object>> list, String eventUser) throws JsonMappingException, JsonProcessingException {


        if (list == null || list.size() < 1) {
            return "";
        }
        
        JSONObject sendData = new JSONObject(true);
        JSONObject sapreturnData = new JSONObject(true);

        JSONObject header = new JSONObject(true);
        sendData.put("HEAD", header);
        JSONObject body = new JSONObject(true);
        sendData.put("BODY", body);
        JSONArray itemArray = new JSONArray();
        body.put("ITEM", itemArray);
        /*
         HEAD
         */
        header.put("INTF_ID", "MM067");
        //uniqueID
        String uniqueID = UUID.randomUUID().toString();
        header.put("REQ_KEYID", uniqueID);
        header.put("SRC_MSGID", uniqueID);
        header.put("SRC_SYSTEM", "WMS");
        header.put("DEST_SYSTEM", "SAP");
        header.put("REQUSER", eventUser);

        /*
         BODY
         */
        body.put("ITEMID", uniqueID);
        //过账日期
        body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证日期
        body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证抬头文本  即入库单号
        body.put("BKTXT", uniqueID);
        //用户名
        body.put("USNAM", eventUser);
        //标识
        body.put("ZFLAG", "");


        for (Map<String, Object> mm : list) {
            JSONObject item = new JSONObject(true);
            //UMWRK 收货工厂
            //LGORT 发货库存地点
            //UMLOG 收货库存地点
            //MATNR 发货物料号
            //UMMAT 收货物料

            item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("UMMAT", mm.get("RECEIVEREQUESTNAME"));
            item.put("UMLGO", mm.get("INSTORE"));
            item.put("LGORT", mm.get("OUTSTORE"));
            item.put("UMWRK", mm.get("INORG"));
            item.put("WERKS", mm.get("OUTORG"));
            item.put("BWART", "161");
            item.put("LIFNR", mm.get("SUPPLIERNAME"));
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            item.put("BPMNG", mm.get("MATERIALQUANTITY"));
            item.put("BPRME", mm.get("UNIT"));
            item.put("SGTXT", mm.get("REMARK"));
            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(), "END") ? "" : "X";
            item.put("INSMK", insmk);
            itemArray.add(item);

        }
        log.info("SendTOSAP >>>>" + sendData);
        return sendData.toJSONString();
	}
	
	public String PurStockIn(String receiveRequestName, String siteName, String eventUser, String receiveActno,
			Map<String, ?> args/* , List<Map<String,Object>> overReceiveControls */)  {
		try {
			return PurStockIn(receiveRequestName, siteName, eventUser, args/* ,overReceiveControls */);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return "";		
		}
		
	}
	
	/**
	 * 采购入库
	 * @param list
	 * @param eventUser
	 * @return
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 */
	public String makePurStockIn (List<Map<String, Object>> list, String eventUser, String receiveActno) throws JsonMappingException, JsonProcessingException {

        if (list == null || list.size() < 1) {
            return "";
        }
        //    	billtype	String	是	单据类型
        //    	org	String	是	库存组织
        //    	issign	String	是	是否签字
        //    	Y 是
        //    	N否
        //    	iotype	String	是	出入库类型编码
        //    	store	String	是	仓库编码
        //    	billtime	String	是	制单日期
        //    	manager	String	是	库管员
        //    	maker	String	是	制单人
        //    	srcbillid	String	是	上游单据到货单主表id
        //    	freplenishflag
        //    		String	是	N
        //先保存成json再转xml
//		ObjectMapper objectMapper = new ObjectMapper();
//		XmlMapper xmlMapper = new XmlMapper();
//		JSONObject bill = new JSONObject(true);
//		JSONObject billBody = new JSONObject(true);
//		billBody.put("billtype", list.get(0).get("BILLTYPE"));
//		billBody.put("org", list.get(0).get("ORG"));
//		billBody.put("issign", list.get(0).get("ISSIGN"));
//		billBody.put("iotype", list.get(0).get("IOTYPE"));
//		billBody.put("store", list.get(0).get("STORE"));
//		billBody.put("opcode","");
//		billBody.put("billtime", list.get(0).get("BILLTIME"));
//		billBody.put("manager", eventUser);
//		billBody.put("maker", eventUser);
//		billBody.put("srcbillid", list.get(0).get("SRCBILLID"));
//		billBody.put("freplenishflag", list.get(0).get("FREPLENISHFLAG"));
//
//		JSONArray jsonArray = new JSONArray();
//		JSONArray itemH = new JSONArray();
//		JSONObject detail = new JSONObject(true);
//		for (int i = 0; i < list.size(); i++) {
//			//        	srcbillbid	String	是	上游单据生产报告子表id
//			//        	mat	String	是	物料编码
//			//        	matversion	String	是	物料版本默认1
//			//        	unit	String	是	主单位
//			//        	astunit	String	是	辅单位
//			//        	changerate	String	是	换算率
//			//        	proddate	String	是	生产日期
//			//        	expdate	String	是	失效日期
//			//        	batchcode	String	是	批次号
//			//        	num	String	是	主数量
//			//        	astnum	String	是	辅数量
//			//        	indate	String	是	入库日期
//			//        	jd	String	是	阶段
//			//        	sdk	String	否	sdk规格（看具体物料）
//			//        	loc	String	是	货位
//			JSONObject itemD = new JSONObject(true);
//			itemD.put("srcbillbid", list.get(i).get("SRCBILLBID"));
//			itemD.put("mat", list.get(i).get("MAT"));
//			itemD.put("matversion", list.get(i).get("MATVERSION"));
//			itemD.put("unit", list.get(i).get("UNIT"));
//			itemD.put("astunit", list.get(i).get("ASTUNIT"));
//			itemD.put("changerate", list.get(i).get("CHANGERATE"));
//			itemD.put("proddate", list.get(i).get("PRODDATE"));
//			itemD.put("expdate", list.get(i).get("EXPDATE"));
//			if ( !"105010002".equals(list.get(i).get("MAT"))) {
//				
//				itemD.put("batchcode", list.get(i).get("BATCHCODE"));
//			}
//
//			itemD.put("num", list.get(i).get("NUM"));
//			itemD.put("astnum", list.get(i).get("ASTNUM"));
//			itemD.put("indate", list.get(i).get("INDATE"));
//
//			itemD.put("jd", list.get(i).get("JD"));
//			itemD.put("sdk", list.get(i).get("SDK"));
//			itemD.put("loc", list.get(i).get("LOC"));
//			itemH.add(itemD);
//		}
//		detail.put("item", itemH);
//		billBody.put("detail", detail);
//		bill.put("bill", billBody);
//		Object readValue = objectMapper.readValue(bill.toJSONString(), Object.class);
//		String writeValueAsString = xmlMapper.writeValueAsString(readValue);
//		return writeValueAsString;
        JSONObject sendData = new JSONObject(true);
        JSONObject sapreturnData = new JSONObject(true);

        JSONObject header = new JSONObject(true);
        sendData.put("HEAD", header);
        JSONObject body = new JSONObject(true);
        sendData.put("BODY", body);
        JSONArray itemArray = new JSONArray();
        body.put("ITEM", itemArray);
        /*
         HEAD
         */
        header.put("INTF_ID", "MM067");
        //uniqueID
        String uniqueID = UUID.randomUUID().toString();
        header.put("REQ_KEYID", uniqueID);
        header.put("SRC_MSGID", uniqueID);
        header.put("SRC_SYSTEM", "WMS");
        header.put("DEST_SYSTEM", "SAP");
        header.put("REQUSER", eventUser);

        /*
         BODY
         */
        body.put("ITEMID", uniqueID);
        //过账日期
        body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证日期
        body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证抬头文本  即入库单号
        body.put("BKTXT", uniqueID);
        //用户名
        body.put("USNAM", eventUser);
        //标识
        body.put("ZFLAG", "");


        for (Map<String, Object> mm : list) {
            JSONObject item = new JSONObject(true);
            //UMWRK 收货工厂
            //LGORT 发货库存地点
            //UMLOG 收货库存地点
            //MATNR 发货物料号
            //UMMAT 收货物料

            item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("UMMAT", mm.get("RECEIVEREQUESTNAME"));
            item.put("UMLGO", mm.get("INSTORE"));
            item.put("LGORT", mm.get("OUTSTORE"));
            item.put("UMWRK", mm.get("INORG"));
            item.put("WERKS", mm.get("OUTORG"));
            item.put("BWART", "161");
            item.put("LIFNR", mm.get("SUPPLIERNAME"));
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            item.put("BPMNG", mm.get("MATERIALQUANTITY"));
            item.put("BPRME", mm.get("UNIT"));
            item.put("SGTXT", mm.get("REMARK"));
            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(), "END") ? "" : "X";
            item.put("INSMK", insmk);
            itemArray.add(item);

        }
        log.info("SendTOSAP >>>>" + sendData);
        return sendData.toJSONString();
    }

	
	public String SendERPStockIn(String receiveRequestName, String siteName, String eventUser,
			String reActo/* ,List<Map<String,Object>> overReceiveControls */) throws Exception {
		//判断单据类型调用不同的接口
		String sql = "SELECT m.RECEIVEREQUESTTYPE FROM MATERIALRECEIVEREQUEST m WHERE m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		String billCode = "";
		if (queryForList != null && queryForList.size() > 0) {
			String type = queryForList.get(0).get("RECEIVEREQUESTTYPE").toString();
			switch (type) {
			case "ZK4A" : //其他入库
				billCode = qtrNoInvoice(receiveRequestName, siteName, reActo,eventUser);
				break;
//			case "45" : //采购入库	
			case "Z001" : //采购入库	
			case "Z002" : //研发采购订单
			case "Z003" : //非生产物资采购订单
			case "Z006" : //股份- 泗洪STO
			case "Z007" : //股份泗洪-分子公司STO
				Map<String,Object> args = new HashMap<>();
				billCode = PurStockIn(receiveRequestName, siteName, eventUser, reActo, args/* ,overReceiveControls */);
				break;
			case "NLCC" : //调拨入库	
				billCode = AlloctionStockIn(receiveRequestName, siteName, eventUser,"");
				break;	
			default :
				break;
			}
		} else {
			throw new CustomException("找不到出库单据" + receiveRequestName);
		}
		return billCode;
	}

    //生产领料-261/311 (单据类型01、02)
    public String ProductionStockOut(String shipRequestName, String siteName, String user) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
                .append("		SELECT       ").append(SystemPropHelper.CR)
                .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
                .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
                .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
                .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
                .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
                .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
                .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
                .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
                .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
                .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
                .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
                .append("			SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
                .append("		FROM       ").append(SystemPropHelper.CR)
                .append("			MATERIALPACKING MP       ").append(SystemPropHelper.CR)
                .append("		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        ").append(SystemPropHelper.CR)
                .append("				 ON       ").append(SystemPropHelper.CR)
                .append("			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
                .append("			AND MP.SITENAME = MD.SITENAME       ").append(SystemPropHelper.CR)
                .append("			AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
                .append( "		LEFT JOIN MATERIALSHIPREQUEST MS        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("		WHERE       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.STOCKSTATE = 'Stocked'       ").append(SystemPropHelper.CR)
        .append("		GROUP BY        ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY       ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
                "WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";

        List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
        String bwart = "";
        for(Map<String, Object> map : checkResultList) {
            bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
        }
        if(bwart == null || bwart == "") {
            throw new CustomException("ERROR","下发单据时，请务必填入移动类型");
        }

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
//                //KOSTL 成本中心
//                item.put("KOSTL", mm.get("COSTCENTER"));
//                //GRUND 移动原因 (201,202回传)
//                item.put("GRUND", mm.get("SHIPREQUESTDETAILTYPE"));

                if(bwart.equals("261")) {
                    //BWART 移动类型
                    item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
                    //ZLLORDER 自定义领料单号
                    item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                    //ZLLITEM 自定义领料单行号
                    item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));
                    //AUFNR 订单号
                    item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
                }
                if(bwart.equals("311")) {
                    //BWART 移动类型
                    item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
                    //UMMAT 收货物料
                    item.put("UMMAT", mm.get("MATERIALSPECNAME"));//传什么
                    //UMLGO 收货库存地点
                    item.put("UMLGO", mm.get("ERPRECEIVELOCATION"));
                    //UMWRK 收货工厂
                    item.put("UMWRK", mm.get("ERPRECEIVEFACTORY"));
                }

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("生产领料出库261/311");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
  //生产领料-261/311 (单据类型01、02) zd.2024.8.14
    public String ProductionStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql=" SELECT\r\n" + 
        		"	t.MATERIALSPECNAME,\r\n" + 
        		"	t.ERPFACTORY,\r\n" + 
        		"	t.ERPLOCATION,\r\n" + 
        		"	m2.SHIPREQUESTDETAILTYPE,\r\n" + 
        		"	t.UNIT,\r\n" + 
        		"	m1.COSTCENTER,\r\n" + 
        		"	m1.SHIPREQUESTNAME,\r\n" + 
        		"	m1.SHIPREQUESTDETAILNAME,\r\n" + 
        		"	m1.ERPRECEIVELOCATION,\r\n" + 
        		"	m1.ERPRECEIVEFACTORY,\r\n" + 
        		"	m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" + 
        		"	CASE WHEN m1.SENDSALESORDER IS NOT NULL THEN 'E' ELSE '' END SOBKZ,\r\n" + 
        		"	(\r\n" + 
        		"	SELECT\r\n" + 
        		"		RECEIVEPRODUCTIONORDERNUMBER\r\n" + 
        		"	FROM\r\n" + 
        		"		MATERIALSHIPREQUESTDETAIL m5\r\n" + 
        		"	WHERE\r\n" + 
        		"		m5.SHIPREQUESTNAME =:SHIPREQUESTNAME\r\n" + 
        		"		AND m5.MATERIALSPECNAME = t.MATERIALSPECNAME\r\n" + 
        		"	ORDER BY\r\n" + 
        		"		m5.USEDATE,\r\n" + 
        		"		m5.SHIPREQUESTDETAILNAME FETCH FIRST ROW ONLY)RECEIVEPRODUCTIONORDERNUMBER,\r\n" + 
        		"	SUM(m.QTY) AS MATERIALQUANTITY\r\n" + 
        		" FROM \r\n" + 
        		"		 MATERIALPACKINGSUB m\r\n" + 
        		" LEFT JOIN MATERIALPACKING T ON \r\n" + 
        		"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME\r\n" + 
        		"	AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME\r\n" + 
        		" LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" + 
        		"		  ON \r\n" + 
        		"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME\r\n" + 
        		"	AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME\r\n" + 
        		" LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" + 
        		"		  ON \r\n" + 
        		"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME\r\n" + 
        		" WHERE \r\n" + 
        		"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" + 
        		"	AND T.SITENAME = :SITENAME\r\n" + 
        		"	AND T.STOCKSTATE = 'Stocked'\r\n" + 
        		"	AND T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
        		" GROUP BY\r\n" + 
        		"	t.MATERIALSPECNAME,\r\n" + 
        		"	t.ERPFACTORY,\r\n" + 
        		"	t.ERPLOCATION,\r\n" + 
        		"	m2.SHIPREQUESTDETAILTYPE,\r\n" + 
        		"	t.UNIT,\r\n" + 
        		"	m1.COSTCENTER,\r\n" + 
        		"	m1.SHIPREQUESTNAME,m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" + 
        		"	m1.SHIPREQUESTDETAILNAME,\r\n" + 
        		"	m1.ERPRECEIVELOCATION,\r\n" + 
        		"	m1.ERPRECEIVEFACTORY";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
                "WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";

        List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
        String bwart = "";
        for(Map<String, Object> map : checkResultList) {
            bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
        }
        if(bwart == null || bwart == "") {
            throw new CustomException("ERROR","下发单据时，请务必填入移动类型");
        }

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
//                //KOSTL 成本中心
//                item.put("KOSTL", mm.get("COSTCENTER"));
//                //GRUND 移动原因 (201,202回传)
//                item.put("GRUND", mm.get("SHIPREQUESTDETAILTYPE"));

                if(bwart.equals("261")) {
                    //BWART 移动类型
                    item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
                    //ZLLORDER 自定义领料单号
                    item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                    //ZLLITEM 自定义领料单行号
                    item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));
                    //AUFNR 订单号
                    item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
                }
                if(bwart.equals("311")) {
                    //BWART 移动类型
                    item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
                    //UMMAT 收货物料
                    item.put("UMMAT", mm.get("MATERIALSPECNAME"));//传什么
                    //UMLGO 收货库存地点
                    item.put("UMLGO", mm.get("ERPRECEIVELOCATION"));
                    //UMWRK 收货工厂
                    item.put("UMWRK", mm.get("ERPRECEIVEFACTORY"));
                }
                item.put("SOBKZ", mm.get("SOBKZ"));//特殊库存标识
                item.put("MAT_KDAUF", mm.get("SENDSALESORDER"));//发货销售订单号
                item.put("MAT_KDPOS", mm.get("SENDSALESORDERDETAILNO"));//发货销售订单行项

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("生产领料出库261/311");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //成本中心、研发领料，有批次。zd.2024.8.21
    public String orderStockOut(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql=" SELECT      MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME,       \r\n" + 
        		"        			MD.SHIPREQUESTDETAILNAME,       \r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY,       \r\n" + 
        		"        			MD.CAUSEOFMOVEMENT,       \r\n" + 
        		"        			SUM(t.QTY) AS MATERIALQUANTITY       \r\n" + 
        		"        		FROM       \r\n" + 
        		"        			MATERIALPACKING MP \r\n" + 
        		"        		LEFT JOIN MATERIALPACKINGSUB T\r\n" + 
        		"        		ON mp.MATERIALPACKINGNAME =t.MATERIALPACKINGNAME \r\n" + 
        		"        		AND mp.SHIPREQUESTNAME =t.RECEIVEREQUESTNAME \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = MD.SITENAME       \r\n" + 
        		"        			AND t.RECEIVEREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       \r\n" + 
        		"        		WHERE       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = :SITENAME       \r\n" + 
        		"        			AND MP.STOCKSTATE = 'Stocked'\r\n" + 
        		"        			AND MP.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
        		"        		GROUP BY        \r\n" + 
        		"        			MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME, \r\n" + 
        		"        			MD.SHIPREQUESTDETAILNAME,\r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY,       \r\n" + 
        		"        			MD.CAUSEOFMOVEMENT       ";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

            	JSONObject item = new JSONObject(true);
                //BWART 移动类型
                item.put("BWART",  mm.get("SHIPREQUESTDETAILTYPE"));
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //KOSTL 成本中心
                item.put("KOSTL", mm.get("COSTCENTER"));
                //AUFNR 订单号
                item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
                //GRUND 移动原因 (201,202回传)
                item.put("GRUND", mm.get("CAUSEOFMOVEMENT"));
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("成本中心/研发领料");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    // 采购退货
    public String PurchaseStockOut(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql=" SELECT      MP.MATERIALSPECNAME,       \r\n" +
                "        			MP.ERPFACTORY,       \r\n" +
                "        			MP.ERPLOCATION,       \r\n" +
                "        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
                "        			MP.UNIT,       \r\n" +
                "        			MD.COSTCENTER,       \r\n" +
                "        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
                "        			MP.SHIPREQUESTNAME,       \r\n" +
                "        			MD.SHIPREQUESTDETAILNAME,       \r\n" +
                "        			MD.ERPRECEIVELOCATION,       \r\n" +
                "        			MD.ERPRECEIVEFACTORY,       \r\n" +
                "        			MD.CAUSEOFMOVEMENT,       \r\n" +
                "        			SUM(t.QTY) AS MATERIALQUANTITY       \r\n" +
                "        		FROM       \r\n" +
                "        			MATERIALPACKING MP \r\n" +
                "        		LEFT JOIN MATERIALPACKINGSUB T\r\n" +
                "        		ON mp.MATERIALPACKINGNAME =t.MATERIALPACKINGNAME \r\n" +
                "        		AND mp.SHIPREQUESTNAME =t.RECEIVEREQUESTNAME \r\n" +
                "        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" +
                "        				 ON       \r\n" +
                "        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" +
                "        			AND MP.SITENAME = MD.SITENAME       \r\n" +
                "        			AND t.RECEIVEREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       \r\n" +
                "        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" +
                "        				 ON       \r\n" +
                "        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       \r\n" +
                "        		WHERE       \r\n" +
                "        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" +
                "        			AND MP.SITENAME = :SITENAME       \r\n" +
                "        			AND MP.STOCKSTATE = 'Stocked'\r\n" +
                "        			AND MP.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
                "        		GROUP BY        \r\n" +
                "        			MP.MATERIALSPECNAME,       \r\n" +
                "        			MP.ERPFACTORY,       \r\n" +
                "        			MP.ERPLOCATION,       \r\n" +
                "        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
                "        			MP.UNIT,       \r\n" +
                "        			MD.COSTCENTER,       \r\n" +
                "        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
                "        			MP.SHIPREQUESTNAME, \r\n" +
                "        			MD.SHIPREQUESTDETAILNAME,\r\n" +
                "        			MD.ERPRECEIVELOCATION,       \r\n" +
                "        			MD.ERPRECEIVEFACTORY,       \r\n" +
                "        			MD.CAUSEOFMOVEMENT       ";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);


        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                //BWART 移动类型
                item.put("BWART",  mm.get("SHIPREQUESTDETAILTYPE"));
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //KOSTL 成本中心
                item.put("KOSTL", mm.get("COSTCENTER"));
                //AUFNR 订单号
                item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
                //GRUND 移动原因 (201,202回传)
                item.put("GRUND", mm.get("CAUSEOFMOVEMENT"));
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("成本中心/研发领料");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //MES上报工单消耗数据-261工单投料
    public String mesMaterialConsume( String user ) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);
            //查询临时表TEMP_MESCONSUME，从里面取数据
            String sql = "SELECT T.MATERIALSPECNAME, T.ERPFACTORY, T.ERPLOCATION, T.QTY, T.UNIT,T.WO,T.SHIPREQUESTNAME,M.RESERVEDPROJECTNUMB FROM TEMP_MESCONSUME T LEFT JOIN MATERIALSHIPREQUESTDETAIL M ON M.SHIPREQUESTNAME = T.SHIPREQUESTNAME AND M.MATERIALSPECNAME = T.MATERIALSPECNAME";
            List<Map<String, Object>> maps = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, new HashMap<String,Object>());



            if (maps == null || maps.size() < 1) {
                throw new RuntimeException("不存在需要发送的数据");
            }
            for (int i=0;i<maps.size();i++) {
                JSONObject item = new JSONObject(true);
                if(maps.size()>0) {
	                // MATNR 发货物料号
	                item.put("MATNR", maps.get(i).get("MATERIALSPECNAME"));
	                // WERKS 发货工厂
	                item.put("WERKS", maps.get(i).get("ERPFACTORY"));
	                // LGORT 发货库存地点
	                item.put("LGORT", maps.get(i).get("ERPLOCATION"));
	                //MENGE 数量
	                item.put("MENGE", maps.get(i).get("QTY"));
	                //MENGE 单位
	                item.put("MEINS", maps.get(i).get("UNIT"));
	//                //KOSTL 成本中心
	//                item.put("KOSTL", mm.get("COSTCENTER"));
	//                //GRUND 移动原因 (201,202回传)
	//                item.put("GRUND", mm.get("SHIPREQUESTDETAILTYPE"));
	
	                item.put("BWART", "261");
                    //ZLLORDER 自定义领料单号
//                    item.put("ZLLORDER", "LL1010250408001");
                    item.put("ZLLORDER", maps.get(i).get("SHIPREQUESTNAME"));
                    //ZLLITEM 自定义领料单行号

//                    item.put("ZLLITEM", "0001");
                    item.put("ZLLITEM", maps.get(i).get("RESERVEDPROJECTNUMB"));
                    //AUFNR 订单号
                    item.put("AUFNR", maps.get(i).get("WO"));
	                
                }

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("MES物料消耗261");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + e.toString());
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //生产领料-成本中心领料-201 (单据类型05、06)
    public String CostCenterStockOut(String shipRequestName, String siteName, String user) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("		SELECT       ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MD.CAUSEOFMOVEMENT,       ").append(SystemPropHelper.CR)
        .append("			SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("		FROM       ").append(SystemPropHelper.CR)
        .append("			MATERIALPACKING MP       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = MD.SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUEST MS        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("		WHERE       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.STOCKSTATE = 'Stocked'       ").append(SystemPropHelper.CR)
        .append("		GROUP BY        ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME ,      ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MD.CAUSEOFMOVEMENT       ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
                "WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";

        List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
        String bwart = "";
        for(Map<String, Object> map : checkResultList) {
            bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
        }
        if(bwart == null || bwart.isEmpty()) {
            throw new CustomException("ERROR","下发单据时，请务必填入移动类型!");
        }
        if(!"201".equals(bwart)) {
            throw new CustomException("ERROR","移动类型应为201，请确认!");
        }
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                //BWART 移动类型
                item.put("BWART", bwart);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //KOSTL 成本中心
                item.put("KOSTL", mm.get("COSTCENTER"));
                //GRUND 移动原因 (201,202回传)
                item.put("GRUND", mm.get("CAUSEOFMOVEMENT"));
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("成本中心领料出库201");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //生产领料- 研发（内部订单）领料-Z61 (单据类型09)
    public String DevelopmentStockOut(String shipRequestName, String siteName, String user) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("		SELECT       ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MD.CAUSEOFMOVEMENT,       ").append(SystemPropHelper.CR)
        .append("			SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("		FROM       ").append(SystemPropHelper.CR)
        .append("			MATERIALPACKING MP       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = MD.SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUEST MS        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("		WHERE       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.STOCKSTATE = 'Stocked'       ").append(SystemPropHelper.CR)
        .append("		GROUP BY        ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME  ,     ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MD.CAUSEOFMOVEMENT       ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
                "WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";

        List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
        String bwart = "";
        for(Map<String, Object> map : checkResultList) {
            bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
        }
        if(bwart == null || bwart == "") {
            throw new CustomException("ERROR","下发单据时，请务必填入移动类型!");
        }
        if(!"Z61".equals(bwart) ) {
            throw new CustomException("ERROR","移动类型应为Z61，请确认!");
        }
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                //BWART 移动类型
                item.put("BWART", bwart);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //AUFNR 订单号（内部订单号）
                item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));//内部订单号是哪个字段？
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("研发（内部订单）领料出库Z61");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //销售出库确认 （单据类型ZLF0~ZLF8） SD023(销售回传)
    public String SaleStockOut(String shipRequestName, String siteName, String user,List<String> arrayList,
                               String erpLocation,String commitDate, String opcode) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("    SELECT    ").append(SystemPropHelper.CR)
        .append("    count(*) AS ZROL,    ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTDETAILNAME ,    ").append(SystemPropHelper.CR)
        .append("    mp.ERPLOCATION,       ").append(SystemPropHelper.CR)
//        .append("    mp.MATERIALQUANTITY,    ").append(SystemPropHelper.CR)
        .append("    sum(mp.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("    FROM MATERIALPACKING mp       ").append(SystemPropHelper.CR)
        .append("    LEFT JOIN MATERIALSHIPREQUEST ms ON       ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = ms.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("    LEFT JOIN MATERIALSHIPREQUESTDETAIL md ON       ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = md.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.SHIPREQUESTDETAILNAME = md.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.SITENAME = md.SITENAME       ").append(SystemPropHelper.CR)
        .append("    WHERE      ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = :SHIPREQUESTNAME      ").append(SystemPropHelper.CR)
        .append("    AND mp.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.STOCKSTATE = 'Stocked'     AND   mp.MATERIALPACKINGNAME IN  :BATCH ").append(SystemPropHelper.CR)
        .append("    GROUP BY     ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTDETAILNAME ,    ").append(SystemPropHelper.CR)
        .append("    mp.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("    mp.MATERIALQUANTITY      ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BATCH", arrayList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("DEST_SYSTEM", "SAP");
            header.put("INTF_ID", "SD023");
            header.put("SRC_SYSTEM", "WMS");
            String uniqueID = UUID.randomUUID().toString();
            header.put("SRC_MSGID", uniqueID);
            header.put("BACKUP1", uniqueID);
            header.put("BACKUP2", uniqueID);

            /*
             BODY
             */
            //交货单号
            body.put("VBELN", shipRequestName);
            //实际过账日期
            body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
            //发送日期
            body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //操作类型（过账）
            body.put("Z_OPTION", "1");

//            if (queryForList.size() > 1) {
                for (Map<String, Object> mm : queryForList) {
                    JSONObject item = new JSONObject(true);

                    //交货单行号
                    item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
                    //库存地点
                    item.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    item.put("Z_ROL", mm.get("ZROL"));
                    //实际发货平方米
                    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                    itemArray.add(item);
                }
                body.put("ITEMS", itemArray);
//            }
//            else {
//                for (Map<String, Object> mm : queryForList) {
//
//                    //交货单行号
//                    body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
//                    //交货数量
//                    body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
//                    //库存地点
//                    body.put("LGORT", mm.get("ERPLOCATION"));
//                    //实际发货卷数
//                    body.put("Z_ROL", mm.get("ZROL"));   //COUNT
//                    //实际发货平方米
//                    body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));
//
//                }
//            }

            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("销售出库");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //调拨出库 （单据类型NLCC） SD023(销售回传)
    public String TransferStockOut(String shipRequestName, String siteName, String user, List<String> list, String erpLocation,
                                   String commitDate, String opCode) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("    SELECT    ").append(SystemPropHelper.CR)
        .append("    count(*) AS ZROL,    ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTDETAILNAME ,    ").append(SystemPropHelper.CR)
        .append("    mp.ERPLOCATION,       ").append(SystemPropHelper.CR)
//        .append("    mp.MATERIALQUANTITY,    ").append(SystemPropHelper.CR)
        .append("    sum(mp.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("    FROM MATERIALPACKING mp       ").append(SystemPropHelper.CR)
        .append("    LEFT JOIN MATERIALSHIPREQUEST ms ON       ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = ms.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("    LEFT JOIN MATERIALSHIPREQUESTDETAIL md ON       ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = md.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.SHIPREQUESTDETAILNAME = md.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.SITENAME = md.SITENAME       ").append(SystemPropHelper.CR)
        .append("    WHERE      ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTNAME = :SHIPREQUESTNAME      ").append(SystemPropHelper.CR)
        .append("    AND mp.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("    AND mp.STOCKSTATE = 'Stocked'     ").append(SystemPropHelper.CR)
                .append("    AND mp.MATERIALPACKINGNAME IN : BOXID      ").append(SystemPropHelper.CR)
        .append("    GROUP BY     ").append(SystemPropHelper.CR)
        .append("    mp.SHIPREQUESTDETAILNAME ,    ").append(SystemPropHelper.CR)
        .append("    mp.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("    mp.MATERIALQUANTITY      ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("BOXID", list);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("DEST_SYSTEM", "SAP");
            header.put("INTF_ID", "SD023");
            header.put("SRC_SYSTEM", "WMS");
            String uniqueID = UUID.randomUUID().toString();
            header.put("SRC_MSGID", uniqueID);
            header.put("BACKUP1", uniqueID);
            header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
            //交货单号
            body.put("VBELN", shipRequestName);
            //实际过账日期
            body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
            //发送日期
            body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //操作类型（过账）
            body.put("Z_OPTION", "1");

            if (queryForList.size() >= 1) {
                for (Map<String, Object> mm : queryForList) {
                    JSONObject item = new JSONObject(true);

                    //交货单行号
                    item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
                    //库存地点
                    item.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    item.put("Z_ROL", mm.get("ZROL"));
                    //实际发货平方米
                    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                    itemArray.add(item);
                }
                body.put("ITEM", itemArray);
            }else {
                for (Map<String, Object> mm : queryForList) {

                    //交货单行号
                    body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
                    //库存地点
                    body.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    body.put("Z_ROL", mm.get("ZROL"));   //COUNT
                    //实际发货平方米
                    body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                }
            }

            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            //销售交货单过账不返回物料凭证,且RETURN为JsonArray
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = "S";
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("调拨出库(NLCC)");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //重写STO业务销售交货单过账。zd.2024.8.14
    public String TransferStockOut_NLCC(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql="    SELECT    \r\n" + 
        		"            count(*) AS ZROL,    \r\n" + 
        		"            m1.SHIPREQUESTDETAILNAME ,    \r\n" + 
        		"            t.ERPLOCATION,          \r\n" + 
        		"            sum(m.QTY)MATERIALQUANTITY          \r\n" + 
        		"            FROM \r\n" + 
        		"		 MATERIALPACKINGSUB m \r\n" + 
        		"		 LEFT JOIN MATERIALPACKING T ON \r\n" + 
        		"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME \r\n" + 
        		"		 LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" + 
        		"		  ON \r\n" + 
        		"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME \r\n" + 
        		"		 AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME \r\n" + 
        		"		 LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" + 
        		"		  ON \r\n" + 
        		"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME \r\n" + 
        		"		 WHERE \r\n" + 
        		"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME \r\n" + 
        		"		 AND T.SITENAME = :SITENAME  \r\n" + 
        		"		  AND T.STOCKSTATE = 'Stocked' AND   T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
        		"		  GROUP BY m1.SHIPREQUESTDETAILNAME ,    t.ERPLOCATION";

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("DEST_SYSTEM", "SAP");
            header.put("INTF_ID", "SD023");
            header.put("SRC_SYSTEM", "WMS");
            String uniqueID = UUID.randomUUID().toString();
            header.put("SRC_MSGID", uniqueID);
            header.put("BACKUP1", uniqueID);
            header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
            //交货单号
            body.put("VBELN", shipRequestName);
            //实际过账日期
            body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
            //发送日期
            body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //操作类型（过账）
            body.put("Z_OPTION", "1");

            if (queryForList.size() >= 1) {
                for (Map<String, Object> mm : queryForList) {
                    JSONObject item = new JSONObject(true);

                    //交货单行号
                    item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
                    //库存地点
                    item.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    item.put("Z_ROL", mm.get("ZROL"));
                    //实际发货平方米
                    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                    itemArray.add(item);
                }
                body.put("ITEMS", itemArray);
            }else {
                for (Map<String, Object> mm : queryForList) {

                    //交货单行号
                    body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
                    //库存地点
                    body.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    body.put("Z_ROL", mm.get("ZROL"));   //COUNT
                    //实际发货平方米
                    body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                }
            }

            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            //销售交货单过账不返回物料凭证,且RETURN为JsonArray
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = "S";
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("调拨出库(NLCC)");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

  //重写销售交货单过账。zd.2024.8.14
    public String saleStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql="    SELECT    \r\n" + 
        		"            count(*) AS ZROL,    \r\n" + 
        		"            m1.SHIPREQUESTDETAILNAME ,    \r\n" + 
        		"            t.ERPLOCATION,          \r\n" + 
        		"            sum(m.QTY)MATERIALQUANTITY          \r\n" + 
        		"            FROM \r\n" + 
        		"		 MATERIALPACKINGSUB m \r\n" + 
        		"		 LEFT JOIN MATERIALPACKING T ON \r\n" + 
        		"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME \r\n" + 
        		"		 LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" + 
        		"		  ON \r\n" + 
        		"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME \r\n" + 
        		"		 AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME \r\n" + 
        		"		 LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" + 
        		"		  ON \r\n" + 
        		"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME \r\n" + 
        		"		 WHERE \r\n" + 
        		"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME \r\n" + 
        		"		 AND T.SITENAME = :SITENAME  \r\n" + 
        		"		  AND T.STOCKSTATE = 'Stocked' AND   T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
        		"		  GROUP BY m1.SHIPREQUESTDETAILNAME ,    t.ERPLOCATION";

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("DEST_SYSTEM", "SAP");
            header.put("INTF_ID", "SD023");
            header.put("SRC_SYSTEM", "WMS");
            String uniqueID = UUID.randomUUID().toString();
            header.put("SRC_MSGID", uniqueID);
            header.put("BACKUP1", uniqueID);
            header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
            //交货单号
            body.put("VBELN", shipRequestName);
            //实际过账日期
            body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
            //发送日期
            body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //操作类型（过账）
            body.put("Z_OPTION", "1");

            if (queryForList.size() >= 1) {
                for (Map<String, Object> mm : queryForList) {
                    JSONObject item = new JSONObject(true);

                    //交货单行号
                    item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    item.put("PIKMG", mm.get("MATERIALQUANTITY"));
                    //库存地点
                    item.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    item.put("Z_ROL", mm.get("ZROL"));
                    //实际发货平方米
                    item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                    itemArray.add(item);
                }
                body.put("ITEMS", itemArray);//销售过账需放ITEMS
            }else {
                for (Map<String, Object> mm : queryForList) {

                    //交货单行号
                    body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
                    //交货数量
                    body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
                    //库存地点
                    body.put("LGORT", mm.get("ERPLOCATION"));
                    //实际发货卷数
                    body.put("Z_ROL", mm.get("ZROL"));   //COUNT
                    //实际发货平方米
                    body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

                }
            }

            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            //销售交货单过账不返回物料凭证,且RETURN为JsonArray
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = "S";
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("调拨出库(NLCC)");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //重写委外发料。zd.2024.8.17
    public String oemStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception 
    {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql="SELECT       \r\n" + 
        		"        			MS.DELIVERYADDRESS,       \r\n" + 
        		"        			MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME,       \r\n" + 
        		"        			MP.SHIPREQUESTDETAILNAME,       \r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY,       \r\n" + 
        		"        			SUM(M.QTY) AS MATERIALQUANTITY       \r\n" + 
        		"        		FROM       \r\n" + 
        		"        			MATERIALPACKING MP  \r\n" + 
        		"        		LEFT JOIN MATERIALPACKINGSUB m \r\n" + 
        		"        		ON mp.MATERIALPACKINGNAME =m.MATERIALPACKINGNAME \r\n" + 
        		"        		AND mp.SHIPREQUESTNAME =m.RECEIVEREQUESTNAME \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = MD.SITENAME \r\n" + 
        		"        			AND m.RECEIVEREQUESTDETAILNAME =md.SHIPREQUESTDETAILNAME \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME \r\n" + 
        		"        		WHERE       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = :SITENAME       \r\n" + 
        		"        			AND MP.STOCKSTATE = 'Stocked'\r\n" + 
        		"        			AND mp.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" + 
        		"        		GROUP BY        \r\n" + 
        		"        			MS.DELIVERYADDRESS,       \r\n" + 
        		"        			MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME,       \r\n" + 
        		"        			MP.SHIPREQUESTDETAILNAME,     \r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY       ";
        

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);



        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);

                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //BWART 移动类型
                item.put("BWART", "541O");
                //SOBKZ 特殊库存标识
//                item.put("SOBKZ", "O");
                //LIFNR 供应商编码
                item.put("LIFNR", mm.get("DELIVERYADDRESS"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));

                itemArray.add(item);
                
                updateOEMINVENTORY(mm.get("ERPFACTORY").toString(),mm.get("DELIVERYADDRESS").toString(),
                		mm.get("MATERIALSPECNAME").toString(),mm.get("MATERIALQUANTITY").toString());

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("委外发料541O");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //更新OEMINVENTORY。zd.2024.8.7
    public void updateOEMINVENTORY(String erpFactory,String supplierNo,String materialSpecName,String qty) throws Exception  
    {
    	String sqls="SELECT o.MATERIALSPECNAME FROM OEMINVENTORY o \r\n" + 
    			" WHERE o.ERPFACTORY =:ERPFACTORY\r\n" + 
    			" AND o.MATERIALSPECNAME =:MATERIALSPECNAME\r\n" + 
    			" AND o.SUPPLIERNO =:SUPPLIERNO";
    	Map<String, Object> bp=new HashMap<>();
    	bp.put("ERPFACTORY", erpFactory);
    	bp.put("MATERIALSPECNAME", materialSpecName);
    	bp.put("SUPPLIERNO", supplierNo);
    	bp.put("QTY", qty);
    	List<Map<String, Object>> sr=IDMFrameServiceProxy.getSqlTemplate().queryForList(sqls, bp);
    	if(sr.size()>0) 
    	{
    		String sqlu="UPDATE OEMINVENTORY o SET o.QTY =o.QTY + :QTY\r\n" + 
    				" WHERE o.ERPFACTORY =:ERPFACTORY\r\n" + 
    				" AND o.MATERIALSPECNAME =:MATERIALSPECNAME\r\n" + 
    				" AND o.SUPPLIERNO =:SUPPLIERNO";
    		IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bp);
    	}
    	else 
    	{
    		String sqli="INSERT INTO OEMINVENTORY(ERPFACTORY,MATERIALSPECNAME,SUPPLIERNO,QTY)\r\n" + 
    				" VALUES (:ERPFACTORY,:MATERIALSPECNAME,:SUPPLIERNO,:QTY)";
    		IDMFrameServiceProxy.getSqlTemplate().update(sqli, bp);
    	}
    	
    }
    //盘点，Z05盘亏, Z06盘盈
    public String OtherStockOut(List<AuditBox> auditBoxList, String user) throws Exception  {

        String rcode;
        String undoId = "";
        String rmsg = null;

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (AuditBox auditBox : auditBoxList) {

                JSONObject item = new JSONObject(true);

                //BWART 移动类型   Z05盘亏, Z06盘盈(入口条件)
                if(auditBox.getMaterialQuantity() > 0) {
                    item.put("BWART", "Z06");
                }else {
                    item.put("BWART", "Z05");
                }
                // MATNR 发货物料号
                item.put("MATNR", auditBox.getMaterialSpecName());
                // WERKS 发货工厂
                item.put("WERKS", auditBox.getErpFactoryName());
                // LGORT 发货库存地点
                item.put("LGORT", auditBox.getErpLocationName());
                //MENGE 数量
                item.put("MENGE", Math.abs(auditBox.getMaterialQuantity()));
                //MENGE 单位
                item.put("MEINS", auditBox.getMaterialUnit());
                //KOSTL 成本中心
                item.put("KOSTL", auditBox.getCostCenter());

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("盘点");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //采购退货（Z008 跨月新单据退货）(Z001~Z007 原单据)
    public String OrderStockBackOut(String shipRequestName, String siteName, String user) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("  SELECT   ").append(SystemPropHelper.CR)
//        .append("  	MD.MATERIALSPECNAME,   ").append(SystemPropHelper.CR)
        .append("  	MP.MATERIALSPECNAME,   ").append(SystemPropHelper.CR)
        .append("  	MD.ERPFACTORY,   ").append(SystemPropHelper.CR)
        .append("  	MP.ERPLOCATION,   ").append(SystemPropHelper.CR)
        .append("  	DECODE(MP.PACKINGGRADE,'OK','','NG','3','2')PACKINGGRADE,   ").append(SystemPropHelper.CR)
        .append("  	SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY ,	   ").append(SystemPropHelper.CR)
        .append("  	MP.UNIT,   ").append(SystemPropHelper.CR)
        .append("  	MD.MATERIALUNIT,   ").append(SystemPropHelper.CR)
        .append("  	MR.RECEIVEREQUESTNAME ,   ").append(SystemPropHelper.CR)
        .append("  	MD.RECEIVEREQUESTDETAILNAME    ").append(SystemPropHelper.CR)
        .append("  FROM   ").append(SystemPropHelper.CR)
        .append("  	MATERIALPACKING MP   ").append(SystemPropHelper.CR)
        .append("  LEFT JOIN MATERIALRECEIVEREQUESTDETAIL MD   ").append(SystemPropHelper.CR)
        .append("  		 ON   ").append(SystemPropHelper.CR)
        .append("  	MP.SHIPREQUESTNAME = MD.RECEIVEREQUESTNAME   ").append(SystemPropHelper.CR)
        .append("  	AND MP.SHIPREQUESTDETAILNAME = MD.RECEIVEREQUESTDETAILNAME   ").append(SystemPropHelper.CR)
        .append("  LEFT JOIN MATERIALRECEIVEREQUEST MR   ").append(SystemPropHelper.CR)
        .append("  		  ON   ").append(SystemPropHelper.CR)
        .append("  	MP.SHIPREQUESTNAME = MR.RECEIVEREQUESTNAME   ").append(SystemPropHelper.CR)
        .append("  WHERE   ").append(SystemPropHelper.CR)
        .append("  	MP.SHIPREQUESTNAME = :RECEIVEREQUESTNAME   ").append(SystemPropHelper.CR)
        .append("  	AND MP.SITENAME = :SITENAME   ").append(SystemPropHelper.CR)
        .append("  	AND MP.STOCKSTATE = 'Stocked'   ").append(SystemPropHelper.CR)
        .append("  	GROUP BY   ").append(SystemPropHelper.CR)
//        .append("  	MD.MATERIALSPECNAME,   ").append(SystemPropHelper.CR)
        .append("  	MP.MATERIALSPECNAME,   ").append(SystemPropHelper.CR)
        .append("  	MD.ERPFACTORY,   ").append(SystemPropHelper.CR)
        .append("  	MP.ERPLOCATION,MP.PACKINGGRADE,   ").append(SystemPropHelper.CR)
        .append("  	MD.REQUESTQUANTITY,   ").append(SystemPropHelper.CR)
        .append("  	MP.UNIT,   ").append(SystemPropHelper.CR)
        .append("  	MD.MATERIALUNIT,   ").append(SystemPropHelper.CR)
        .append("  	MR.RECEIVEREQUESTNAME ,   ").append(SystemPropHelper.CR)
        .append("  	MD.RECEIVEREQUESTDETAILNAME   ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetReturnFlag = "SELECT m.RETURNFLAG FROM MATERIALRECEIVEREQUESTDETAIL m WHERE m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND m.SITENAME = :SITENAME";
        List<Map<String, Object>> returnFlagList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetReturnFlag, hashMap);
        String returnFlag = "";
        for(Map<String, Object> map : returnFlagList) {
            returnFlag = MapUtils.getString(map, "RETURNFLAG");
        }

        String sqlReceiveRequestType = "SELECT m.RECEIVEREQUESTTYPE FROM MATERIALRECEIVEREQUEST m WHERE m.SITENAME = :SITENAME AND m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME ";
        List<Map<String, Object>> typeList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlReceiveRequestType, hashMap);
        String receiveRequestType= "";
        for(Map<String, Object> map : typeList) {
            receiveRequestType = MapUtils.getString(map, "RECEIVEREQUESTTYPE");
        }

        String bwart = "101";//采购订单退货传输101
//        if(returnFlag.equalsIgnoreCase("Y") && !receiveRequestType.equalsIgnoreCase("Z008")) {
//            bwart = "102";
//        } else if(receiveRequestType.equalsIgnoreCase("Z008")) {
//            bwart = "161";
//        }

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                item.put("BWART", bwart);
                item.put("INSMK", mm.get("PACKINGGRADE"));
//                if(bwart.equals("102")) {
//                    //BWART 移动类型
//                    item.put("BWART", bwart);
//                }
//                if(bwart.equals("161")) {
//                    //BWART 移动类型
//                    item.put("BWART", bwart);
//                }
                //EBELN 采购订单编码
                item.put("EBELN", mm.get("RECEIVEREQUESTNAME"));
                //EBELP 采购订单项目编码
                item.put("EBELP", mm.get("RECEIVEREQUESTDETAILNAME"));
                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起;
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("采购退货(Z008)");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
  //采购退货Z008,辅材类。zd.2024.8.14
    public String OrderStockBackOut_NoCharge(String shipRequestName, String siteName, String user) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql="SELECT\r\n" + 
        		"	MP.MATERIALSPECNAME,\r\n" + 
        		"	MP.ERPFACTORY,\r\n" + 
        		"	MP.ERPLOCATION,\r\n" + 
        		"	DECODE(MP.PACKINGGRADE, 'OK', '', 'NG', '3', '2')PACKINGGRADE,\r\n" + 
        		"	SUM(MP.MATERIALQUANTITY2) AS MATERIALQUANTITY ,\r\n" + 
        		"	MP.UNIT,\r\n" + 
        		"	MD.MATERIALUNIT,\r\n" + 
        		"	MR.RECEIVEREQUESTNAME ,\r\n" + 
        		"	MD.RECEIVEREQUESTDETAILNAME\r\n" + 
        		" FROM\r\n" + 
        		"	MATERIALPACKING MP\r\n" + 
        		" LEFT JOIN MATERIALRECEIVEREQUESTDETAIL MD   \r\n" + 
        		"          		 ON\r\n" + 
        		"	MP.SHIPREQUESTNAME = MD.RECEIVEREQUESTNAME\r\n" + 
        		"	AND MP.MATERIALSPECNAME = MD.MATERIALSPECNAME \r\n" + 
        		" LEFT JOIN MATERIALRECEIVEREQUEST MR   \r\n" + 
        		"          		  ON\r\n" + 
        		"	MP.SHIPREQUESTNAME = MR.RECEIVEREQUESTNAME\r\n" + 
        		" WHERE\r\n" + 
        		"	MP.SHIPREQUESTNAME = :RECEIVEREQUESTNAME\r\n" + 
        		"	AND MP.SITENAME = :SITENAME\r\n" + 
        		"	AND MP.STOCKSTATE = 'Stocked'\r\n" + 
        		" GROUP BY\r\n" + 
        		"	MP.MATERIALSPECNAME,\r\n" + 
        		"	MP.ERPFACTORY,\r\n" + 
        		"	MP.ERPLOCATION,\r\n" + 
        		"	MP.PACKINGGRADE,\r\n" + 
        		"	MD.REQUESTQUANTITY,\r\n" + 
        		"	MP.UNIT,\r\n" + 
        		"	MD.MATERIALUNIT,\r\n" + 
        		"	MR.RECEIVEREQUESTNAME ,\r\n" + 
        		"	MD.RECEIVEREQUESTDETAILNAME ";

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("RECEIVEREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String sqlGetReturnFlag = "SELECT m.RETURNFLAG FROM MATERIALRECEIVEREQUESTDETAIL m WHERE m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND m.SITENAME = :SITENAME";
        List<Map<String, Object>> returnFlagList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetReturnFlag, hashMap);
        String returnFlag = "";
        for(Map<String, Object> map : returnFlagList) {
            returnFlag = MapUtils.getString(map, "RETURNFLAG");
        }

        String sqlReceiveRequestType = "SELECT m.RECEIVEREQUESTTYPE FROM MATERIALRECEIVEREQUEST m WHERE m.SITENAME = :SITENAME AND m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME ";
        List<Map<String, Object>> typeList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlReceiveRequestType, hashMap);
        String receiveRequestType= "";
        for(Map<String, Object> map : typeList) {
            receiveRequestType = MapUtils.getString(map, "RECEIVEREQUESTTYPE");
        }

        String bwart = "101";//采购订单退货传输101
//        if(returnFlag.equalsIgnoreCase("Y") && !receiveRequestType.equalsIgnoreCase("Z008")) {
//            bwart = "102";
//        } else if(receiveRequestType.equalsIgnoreCase("Z008")) {
//            bwart = "161";
//        }

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                item.put("BWART", bwart);
                item.put("INSMK", mm.get("PACKINGGRADE"));
//                if(bwart.equals("102")) {
//                    //BWART 移动类型
//                    item.put("BWART", bwart);
//                }
//                if(bwart.equals("161")) {
//                    //BWART 移动类型
//                    item.put("BWART", bwart);
//                }
                //EBELN 采购订单编码
                item.put("EBELN", mm.get("RECEIVEREQUESTNAME"));
                //EBELP 采购订单项目编码
                item.put("EBELP", mm.get("RECEIVEREQUESTDETAILNAME"));
                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起;
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("采购退货(Z008)");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }
    
    //成本中心领料06，内部订单领料09。zd.2024.8.21
    public String OrderStockOut_NoCharge(String shipRequestName, String siteName, String user) throws Exception {

        String rcode;
        String undoId = "";
        String rmsg = null;
        String sql=" SELECT      MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME,       \r\n" + 
        		"        			MIN(MP.SHIPREQUESTDETAILNAME)SHIPREQUESTDETAILNAME,       \r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY,       \r\n" + 
        		"        			MD.CAUSEOFMOVEMENT,       \r\n" + 
        		"        			SUM(MP.MATERIALQUANTITY2) AS MATERIALQUANTITY       \r\n" + 
        		"        		FROM       \r\n" + 
        		"        			MATERIALPACKING MP \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = MD.SITENAME       \r\n" + 
        		"        			AND mp.MATERIALSPECNAME = MD.SHIPREQUESTDETAILNAME       \r\n" + 
        		"        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" + 
        		"        				 ON       \r\n" + 
        		"        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       \r\n" + 
        		"        		WHERE       \r\n" + 
        		"        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" + 
        		"        			AND MP.SITENAME = :SITENAME       \r\n" + 
        		"        			AND MP.STOCKSTATE = 'Stocked'       \r\n" + 
        		"        		GROUP BY        \r\n" + 
        		"        			MP.MATERIALSPECNAME,       \r\n" + 
        		"        			MP.ERPFACTORY,       \r\n" + 
        		"        			MP.ERPLOCATION,       \r\n" + 
        		"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" + 
        		"        			MP.UNIT,       \r\n" + 
        		"        			MD.COSTCENTER,       \r\n" + 
        		"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" + 
        		"        			MP.SHIPREQUESTNAME,            \r\n" + 
        		"        			MD.ERPRECEIVELOCATION,       \r\n" + 
        		"        			MD.ERPRECEIVEFACTORY,       \r\n" + 
        		"        			MD.CAUSEOFMOVEMENT      ";

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

            	JSONObject item = new JSONObject(true);
                //BWART 移动类型
                item.put("BWART",  mm.get("SHIPREQUESTDETAILTYPE"));
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //KOSTL 成本中心
                item.put("KOSTL", mm.get("COSTCENTER"));
                //AUFNR 订单号
                item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
                //GRUND 移动原因 (201,202回传)
                item.put("GRUND", mm.get("CAUSEOFMOVEMENT"));
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起;
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("成本中心/内部订单领料");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //形态转换  单据类型11 移动类型309
    public String ChangeStateStockOut(String shipRequestName, String siteName, String user) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("		SELECT       ").append(SystemPropHelper.CR)
        .append("			MD.GOALMATERIALSPEC ,      ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MD.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("		FROM       ").append(SystemPropHelper.CR)
        .append("			MATERIALPACKING MP       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = MD.SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUEST MS        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("		WHERE       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.STOCKSTATE = 'Stocked'       ").append(SystemPropHelper.CR)
        .append("		GROUP BY        ").append(SystemPropHelper.CR)
        .append("			MD.GOALMATERIALSPEC ,        ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MD.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME ,      ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY       ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        //check bwart
//        String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
//                "WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";
//
//        List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
//        String bwart = "";
//        for(Map<String, Object> map : checkResultList) {
//            bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
//        }
//        if(bwart == null || bwart == "") {
//            throw new CustomException("ERROR","下发单据时，请务必填入移动类型");
//        }

        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                //UMMAT 收货物料
                item.put("UMMAT", mm.get("GOALMATERIALSPEC"));
                // WERKS 发货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //UMWRK 收货工厂
                item.put("UMWRK", mm.get("ERPRECEIVEFACTORY"));
                //UMLGO 收货库存地点
                item.put("UMLGO", mm.get("ERPRECEIVELOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //BWART 移动类型
                item.put("BWART", "309");
                //ZLLORDER 自定义领料单号
                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
                //ZLLITEM 自定义领料单行号
                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("形态转换309");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //委外发料 单据Z001 body中 "PSTYP": "3" 是委外发料单
    public String OutSourceStockOut(String shipRequestName, String siteName, String user) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("		SELECT       ").append(SystemPropHelper.CR)
        .append("			MS.DELIVERYADDRESS,       ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY,       ").append(SystemPropHelper.CR)
        .append("			SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY       ").append(SystemPropHelper.CR)
        .append("		FROM       ").append(SystemPropHelper.CR)
        .append("			MATERIALPACKING MP       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = MD.SITENAME       ").append(SystemPropHelper.CR)
//        .append("			AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       ").append(SystemPropHelper.CR)
        .append("		LEFT JOIN MATERIALSHIPREQUEST MS        ").append(SystemPropHelper.CR)
        .append("				 ON       ").append(SystemPropHelper.CR)
        .append("			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME  AND      ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTTYPE = 'OEM'       ").append(SystemPropHelper.CR)
        .append("		WHERE       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.SITENAME = :SITENAME       ").append(SystemPropHelper.CR)
        .append("			AND MP.STOCKSTATE = 'Stocked'       ").append(SystemPropHelper.CR)
        .append("		GROUP BY        ").append(SystemPropHelper.CR)
        .append("			MS.DELIVERYADDRESS,       ").append(SystemPropHelper.CR)
        .append("			MP.MATERIALSPECNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPFACTORY,       ").append(SystemPropHelper.CR)
        .append("			MP.ERPLOCATION,       ").append(SystemPropHelper.CR)
        .append("			MS.SHIPREQUESTDETAILTYPE,       ").append(SystemPropHelper.CR)
        .append("			MP.UNIT,       ").append(SystemPropHelper.CR)
        .append("			MD.COSTCENTER,       ").append(SystemPropHelper.CR)
        .append("			MD.RECEIVEPRODUCTIONORDERNUMBER,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTNAME,       ").append(SystemPropHelper.CR)
        .append("			MP.SHIPREQUESTDETAILNAME,     ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVELOCATION,       ").append(SystemPropHelper.CR)
        .append("			MD.ERPRECEIVEFACTORY       ").append(SystemPropHelper.CR);

        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);



        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);

                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 收货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //BWART 移动类型
                item.put("BWART", "541O");
                //SOBKZ 特殊库存标识
//                item.put("SOBKZ", "O");
                //LIFNR 供应商编码
                item.put("LIFNR", mm.get("DELIVERYADDRESS"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("委外发料5410");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //无来源转库过账 （311）
    public String NoSourceChangeLocation(List<MaterialPackingKey> all,
                                         String aimFactory,
                                         String aimERPlocation,
                                         String aimLocationName,
                                         String user) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("  	SELECT   ").append(SystemPropHelper.CR)
        .append("       MP.MATERIALSPECNAME,   ").append(SystemPropHelper.CR)
        .append("       MP.ERPFACTORY ,   ").append(SystemPropHelper.CR)
        .append("       :AIMFACTORY AS UMWRK_RECIEVEFACTORY,   ").append(SystemPropHelper.CR)
        .append("       MP.ERPLOCATION,   ").append(SystemPropHelper.CR)
        .append("       :AIMERPLOCATION AS UMLGO_RECIEVEERPLOCATION,   ").append(SystemPropHelper.CR)
        .append("       MP.MATERIALQUANTITY ,   ").append(SystemPropHelper.CR)
        .append("       MP.UNIT,   ").append(SystemPropHelper.CR)
        .append("       :AIMLOCATIONNAME AS NULL_RECIVELOCAITONNAME   ").append(SystemPropHelper.CR)
        .append("   FROM   ").append(SystemPropHelper.CR)
        .append("  	    MATERIALPACKING MP   ").append(SystemPropHelper.CR)
        .append("   WHERE   ").append(SystemPropHelper.CR)
        .append("  	    MP.MATERIALPACKINGNAME IN    ").append(SystemPropHelper.CR);
        Map<String, Object> hashMap = new HashMap<String,Object> ();
        hashMap.put("AIMFACTORY", aimFactory);
        hashMap.put("AIMLOCATIONNAME", aimLocationName);
        hashMap.put("AIMERPLOCATION", aimERPlocation);
        String str = "";
        str += "(";
        for (MaterialPackingKey materialPackingKey : all) {
            str += "'" + materialPackingKey.getMaterialPackingName() + "',";
        }
        str += "'')";
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString() + str, hashMap);
        if (queryForList == null || queryForList.size() < 1) {
            return "";
        }
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                //UMMAT 收货物料
                item.put("UMMAT", mm.get("MATERIALSPECNAME"));
                // WERKS 发货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //UMWRK 收货工厂
                item.put("UMWRK", mm.get("UMWRK_RECIEVEFACTORY"));
                //UMLGO 收货库存地点
                item.put("UMLGO", mm.get("UMLGO_RECIEVEERPLOCATION"));
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //BWART 移动类型
                item.put("BWART", "311");
//                //ZLLORDER 自定义领料单号
//                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
//                //ZLLITEM 自定义领料单行号
//                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);

            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("无来源转库-311");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    //物料报废/降级品出库 (Z07)
    public String MaterialScrapStockOut(List<MaterialPackingKey> all, String siteName, String user) throws Exception {
        String rcode;
        String undoId = "";
        String rmsg = null;
        StringBuffer sql = new StringBuffer();
        sql
        .append("    SELECT    ").append(SystemPropHelper.CR)
        .append("    	m.MATERIALSPECNAME ,    ").append(SystemPropHelper.CR)
        .append("    	m.ERPFACTORY ,    ").append(SystemPropHelper.CR)
        .append("    	m.ERPLOCATION ,    ").append(SystemPropHelper.CR)
        .append("    	m.MATERIALQUANTITY ,    ").append(SystemPropHelper.CR)
        .append("    	m.UNIT ,    ").append(SystemPropHelper.CR)
        .append("    	m.SHIPREQUESTNAME ,     ").append(SystemPropHelper.CR)
        .append("    	m.SHIPREQUESTDETAILNAME      ").append(SystemPropHelper.CR)
        .append("    FROM    ").append(SystemPropHelper.CR)
        .append("    	MATERIALPACKING m    ").append(SystemPropHelper.CR)
        .append("    WHERE    ").append(SystemPropHelper.CR)
        .append("    	m.SITENAME = :SITENAME    ").append(SystemPropHelper.CR)
        .append("    AND m.MATERIALPACKINGNAME IN     ").append(SystemPropHelper.CR);
        Map<String, Object> hashMap = new HashMap<String,Object> ();
        hashMap.put("SITENAME", siteName);
        String str = "";
        str += "(";
        for (MaterialPackingKey materialPackingKey : all) {
            str += "'" + materialPackingKey.getMaterialPackingName() + "',";
        }
        str += "'')";
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString() + str, hashMap);
        if (queryForList == null || queryForList.size() < 1) {
            return "";
        }
        try {

            JSONObject sendData = new JSONObject(true);
            JSONObject header = new JSONObject(true);
            sendData.put("HEAD", header);
            JSONObject body = new JSONObject(true);
            sendData.put("BODY", body);
            JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
            header.put("INTF_ID", "MM067");
            String uniqueID = UUID.randomUUID().toString();
            header.put("REQ_KEYID", uniqueID);
            header.put("SRC_MSGID", uniqueID);
            header.put("SRC_SYSTEM", "WMS");
            header.put("DEST_SYSTEM", "SAP");
            header.put("REQUSER", user);

            /*
             BODY
             */
            body.put("ITEM", itemArray);
            body.put("ITEMID", uniqueID);
            //过账日期
            body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证日期
            body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
            //凭证抬头文本
            body.put("BKTXT", uniqueID);
            //用户名
            body.put("USNAM", user);

            for (Map<String, Object> mm : queryForList) {

                JSONObject item = new JSONObject(true);
                // MATNR 发货物料号
                item.put("MATNR", mm.get("MATERIALSPECNAME"));
                // WERKS 发货工厂
                item.put("WERKS", mm.get("ERPFACTORY"));
                // LGORT 发货库存地点
                item.put("LGORT", mm.get("ERPLOCATION"));
                //BWART 移动类型
                item.put("BWART", "Z07");
                //MENGE 数量
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                //MENGE 单位
                item.put("MEINS", mm.get("UNIT"));
                //需要SAP改动，Z07,Z08目前都需要返单号
                //ZLLORDER 自定义领料单号
//                item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
//                //ZLLITEM 自定义领料单行号
//                item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

                itemArray.add(item);
            }
            log.info("SendTOSAP >>>>" + sendData);
            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            UUID uuid = UUID.randomUUID();
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("物料报废/降级品出库(Z07)");
            erplog.setId(uuid.toString());
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData.toJSONString());
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
    }

    /**
     * 退料入库
     *
     * @param siteName
     * @param eventUser
     * @return
     * @throws Exception
     */
    public String ReturnStockInNew(String siteName, String eventUser, String shipRequestName, String commitDate, String opCode) throws Exception {
    	String sql="SELECT  T.RECEIVEREQUESTNAME ," + SystemPropHelper.CR+
                   "        T.PRODUCTORDER," +SystemPropHelper.CR+
    			   "        T.ERPFACTORY, " + SystemPropHelper.CR+
    			   "        T.ERPLOCATION, " + SystemPropHelper.CR+
    			   "        T.MATERIALSPECNAME, " + SystemPropHelper.CR+
    			   "        T.UNIT, " + SystemPropHelper.CR+
    			   "        T.PACKINGGRADE," + SystemPropHelper.CR+
    			   "        SUM(T.MATERIALQUANTITY) AS MATERIALQUANTITY" + SystemPropHelper.CR+
    			   "  FROM MATERIALPACKING T " + SystemPropHelper.CR+
    			   " WHERE 1 = 1 " + SystemPropHelper.CR+
    			   "   AND T.receiveActNo = :SHIPREQUESTNAME" + SystemPropHelper.CR+
    			   "   AND T.SITENAME = :SITENAME " + SystemPropHelper.CR+
    			   "   AND T.STOCKSTATE  = 'Created' " + SystemPropHelper.CR+
    			   "GROUP BY T.RECEIVEREQUESTNAME, T.PRODUCTORDER, T.ERPFACTORY,T.ERPLOCATION, " + SystemPropHelper.CR+
    			   "   T.MATERIALSPECNAME,T.UNIT,PACKINGGRADE ";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SITENAME", siteName);
//        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SHIPREQUESTNAME", opCode);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        //根据不同的类型进行处理
        String makeReturnStockIn = makeReturnStockIn(queryForList, eventUser);

        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    makeReturnStockIn);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        }finally {
        	// 写入message log
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(eventUser);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("ReturnStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(shipRequestName);
            erplog.setSendMsg2(makeReturnStockIn);
            erplog.setSendMsg(makeReturnStockIn);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }

        
        if (!"S".equals(rcode)) {
            throw new Exception("SAP返回异常" + rmsg);
        }
        return undoId;

    }

    public String makeReturnStockIn(List<Map<String, Object>> list, String eventUser) throws JsonMappingException, JsonProcessingException {
        if (list == null || list.size() < 1) {
            return "";
        }
        String moveType = "262";
//        String shipRequestType = (String)list.get(0).get("SHIPREQUESTTYPE");
//        switch(shipRequestType) {
//        	//生产退料单，同组织&跨组织，投工单的退料使用 移动类型用262
//        	case "03": moveType = "262";break;
//        	//转库单，同组织&跨组织，有线边仓退料使用，移动类型用311
//        	case "04": moveType = "311";break;
//        	//成本中心退料，移动类型202
//        	case "07": moveType = "202";break;
//        	//研发(内部订单)退料, 移动类型Z62
//        	case "10": moveType = "Z62";break;
//        	default:break;
//        }
        Map<String,Object> bodyData = new HashMap<>();
        List<Map<String,Object>> itemsData = new ArrayList<>();


        for (Map<String, Object> mm : list) {
            Map<String,Object> item = new HashMap<>();
            //BWART 移动类型（库存管理）CHAR 3
            //KOSTL 成本中心 CHAR 10\
            //GRUND 移动原因 NUMC 4


            item.put("MATNR", mm.get("MATERIALSPECNAME"));
            item.put("LGORT", mm.get("ERPLOCATION"));
            item.put("WERKS", mm.get("ERPFACTORY"));
            item.put("BWART", moveType); //移动类型
            item.put("LIFNR", "");
            if(moveType.equals("202")) {
            	item.put("KOSTL", mm.get("COSTCENTER")); //成本中心
            }
            if(moveType.equals("262")) {
            	item.put("AUFNR", mm.get("PRODUCTORDER"));; //生产工单
            }
            if(moveType.equals("Z62")) {
            	item.put("AUFNR", mm.get("RECEIVEREQUESTNAME"));; //内部订单号，对于研发品来说
            }
            item.put("MENGE", mm.get("MATERIALQUANTITY"));
            item.put("MEINS", mm.get("UNIT"));
            item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
            item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));
            
            item.put("SGTXT", mm.get("REMARK"));
            String insmk = "";
            //对于退料来说， 是已检查之后的结果直接入库， 不需要设置待检
            String packingGrade = mm.get("PACKINGGRADE") == null ? "" : mm.get("PACKINGGRADE").toString();
            if ("NG".equals(packingGrade)) {
                insmk = "3";
            }
//            String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
            item.put("INSMK", insmk);
            itemsData.add(item);

        }
        String sendData = ToSAPMessageUtil.mm067(eventUser, bodyData, itemsData);
        return sendData;

    }

    //移库
    public String moveLibrary(List materialPackingNameList, String shipRequestName, String fromErpLocation, String toErpLocation, double quantity, String eventUser) throws Exception {
        StringBuilder materialPackingNames = new StringBuilder();
        materialPackingNameList.forEach(e -> {
            materialPackingNames.append("'" + e + "'").append(",");
        });
        materialPackingNames.delete(materialPackingNames.length() - 1, materialPackingNames.length());

        StringBuilder sql = new StringBuilder();
        //编写 需要执行的SQL
        sql.append("SELECT mp.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
                .append("       mp.ERPFACTORY ,").append(SystemPropHelper.CR)
                .append("       mp.ERPLOCATION ,").append(SystemPropHelper.CR)
                .append("       mp.SHIPREQUESTNAME ,").append(SystemPropHelper.CR)
                .append("       mp.SHIPREQUESTDETAILNAME ,").append(SystemPropHelper.CR)
                .append("       m.SHIPREQUESTTYPE, ").append(SystemPropHelper.CR)
                .append("       m2.UNIT ,").append(SystemPropHelper.CR)
                .append("       sum (mp.MATERIALQUANTITY ) MATERIALQUANTITY ").append(SystemPropHelper.CR)
                .append("  FROM materialpacking mp").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUEST m").append(SystemPropHelper.CR)
                .append("    ON m.shiprequestname = mp.SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUESTDETAIL m2 ").append(SystemPropHelper.CR)
                .append("    ON m.shiprequestname = m2.shiprequestname").append(SystemPropHelper.CR)
                .append("   AND mp.shiprequestdetailname = m2.shiprequestdetailname").append(SystemPropHelper.CR)
                .append("   AND m2.materialspecname = mp.MATERIALSPECNAME ").append(SystemPropHelper.CR)
                .append(" WHERE mp.MATERIALPACKINGNAME IN (").append(materialPackingNames.toString()).append(") ").append(SystemPropHelper.CR)
                .append("   AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("GROUP BY mp.MATERIALSPECNAME, mp.ERPFACTORY, mp.ERPLOCATION, mp.SHIPREQUESTNAME ,mp.SHIPREQUESTDETAILNAME ,m.SHIPREQUESTTYPE,m2.UNIT  ");
        Map<String, String> hashMap = new HashMap<>();
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String moveLibraryInfo = makeMoveLibrary(queryForList, eventUser);

        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    moveLibraryInfo);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        } finally {
            // 写入message log
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(eventUser);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("PurStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(shipRequestName);
            erplog.setSendMsg2(moveLibraryInfo);
            erplog.setSendMsg(moveLibraryInfo);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }

        if (!"S".equals(rcode)) {
            throw new Exception("SAP返回异常" + rmsg);
        }
        return null;

    }

    public String moveLibrary2(List materialPackingNameList, String shipRequestName, String fromErpLocation, String toErpLocation, String eventUser) throws Exception {
        StringBuilder materialPackingNames = new StringBuilder();
        materialPackingNameList.forEach(e -> {
            materialPackingNames.append("'" + e + "'").append(",");
        });
        materialPackingNames.delete(materialPackingNames.length() - 1, materialPackingNames.length());

        StringBuilder sql = new StringBuilder();
        //编写 需要执行的SQL
        sql.append("SELECT mp.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
                .append("       mp.ERPFACTORY ,").append(SystemPropHelper.CR)
                .append("       mp.ERPLOCATION ,").append(SystemPropHelper.CR)
                .append("       mp.SHIPREQUESTNAME ,").append(SystemPropHelper.CR)
                .append("       mp.SHIPREQUESTDETAILNAME ,").append(SystemPropHelper.CR)
                .append("       m.SHIPREQUESTTYPE, ").append(SystemPropHelper.CR)
                .append("       m2.UNIT ,").append(SystemPropHelper.CR)
                .append("       sum (mp.MATERIALQUANTITY ) MATERIALQUANTITY ").append(SystemPropHelper.CR)
                .append("  FROM materialpacking mp").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUEST m").append(SystemPropHelper.CR)
                .append("    ON m.shiprequestname = mp.SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("LEFT JOIN MATERIALSHIPREQUESTDETAIL m2 ").append(SystemPropHelper.CR)
                .append("    ON m.shiprequestname = m2.shiprequestname").append(SystemPropHelper.CR)
                .append("   AND mp.shiprequestdetailname = m2.shiprequestdetailname").append(SystemPropHelper.CR)
                .append("   AND m2.materialspecname = mp.MATERIALSPECNAME ").append(SystemPropHelper.CR)
                .append(" WHERE mp.MATERIALPACKINGNAME IN (").append(materialPackingNames.toString()).append(") ").append(SystemPropHelper.CR)
                .append("   AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME ").append(SystemPropHelper.CR)
                .append("GROUP BY mp.MATERIALSPECNAME, mp.ERPFACTORY, mp.ERPLOCATION, mp.SHIPREQUESTNAME ,mp.SHIPREQUESTDETAILNAME ,m.SHIPREQUESTTYPE,m2.UNIT  ");
        Map<String, String> hashMap = new HashMap<>();
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

        String moveLibraryInfo = makeMoveLibrary(queryForList, eventUser);

        String sapreturn = "";
        String rcode = "";
        String rmsg = "";
        String undoId = "";
        try {
            sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "",
                    moveLibraryInfo);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();
            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
        } catch (Exception e) {
            log.error("WMS请求SAP:" + e.getMessage(), e);
            throw new RuntimeException("WMS请求SAP" + rmsg);
        } finally {
            // 写入message log
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser(eventUser);
            erplog.setServerName("WmsToErp");
            erplog.setEventName("PurStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(shipRequestName);
            erplog.setSendMsg2(moveLibraryInfo);
            erplog.setSendMsg(moveLibraryInfo);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        }

        if (!"S".equals(rcode)) {
            throw new Exception("SAP返回异常" + rmsg);
        }
        return null;

    }

    public String makeMoveLibrary(List<Map<String, Object>> queryForList, String user) {
        if (queryForList == null || queryForList.size() < 1) {
            return "";
        }

        Map<String, Object> bodyData = new HashMap<>();

        //uniqueID
        String uniqueID = UUID.randomUUID().toString();
	
	
	    /*
	     BODY
	     */
        bodyData.put("ITEMID", uniqueID);
        //过账日期
        bodyData.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证日期
        bodyData.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMddhhmmss"));
        //凭证抬头文本  即入库单号
        bodyData.put("BKTXT", uniqueID);
        //用户名
        bodyData.put("USNAM", user);
        //标识
        bodyData.put("ZFLAG", "");

        List<Map<String, Object>> items = new ArrayList<>();
        for (Map<String, Object> mm : queryForList) {
            Map<String, Object> itemData = new HashMap<>();

            itemData.put("MATNR", mm.get("MATERIALSPECNAME"));
            itemData.put("UMMAT", "");
            itemData.put("UMLGO", mm.get(""));
            itemData.put("LGORT", mm.get("ERPLOCATION"));
            itemData.put("UMWRK", mm.get(""));
            itemData.put("WERKS", mm.get("ERPFACTORY"));
            itemData.put("BWART", "311");
            itemData.put("LIFNR", mm.get(""));
            itemData.put("MENGE", mm.get("MATERIALQUANTITY"));
            itemData.put("MEINS", mm.get("UNIT"));
            itemData.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
            itemData.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));
//	    	String shipRequestType = (String)mm.get("SHIPREQUESTTYPE");
//	    	switch(shipRequestType) {
//	    		case "01": 
//	    		case "02":break;
//	    		default:break;
//	    	}


            //    	itemData.put("EBELN" , );//新增一个字段去传销售订单号
            //    	itemData.put("EBELP" , );
            //        String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
            //质检批如何判定， 如果是质检批，则 INSMK 值为2
            items.add(itemData);
        }
        String sendData = ToSAPMessageUtil.mm067(user, bodyData, items);
        return sendData;
    }

	public String iqcResultFeekback(List<String> sapBoxList,String siteName, String receiveActNumber, String materialCode, String pqcResult,
			String pqcResultDate, String user, String exceptionHandling, String specialState) {
		String moveType= "";		
		String rcode;
        String undoId = "";
        String rmsg = null;

        //依据采购订单，查询待入库的物料(MATERIALPACKING)
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT m.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
	        .append("       m.ERPFACTORY ,").append(SystemPropHelper.CR)
	        .append("       m.ERPLOCATION ,").append(SystemPropHelper.CR)
	        .append("       m.PACKINGGRADE, ").append(SystemPropHelper.CR)
	        .append("       m.UNIT ,").append(SystemPropHelper.CR)
	        .append("       sum(m.MATERIALQUANTITY) MATERIALQUANTITY").append(SystemPropHelper.CR)
	        .append("  FROM MATERIALPACKING m ").append(SystemPropHelper.CR)
//	        .append(" WHERE m.RECEIVEACTNO = :RECEIVEACTNO AND m.SITENAME = :SITENAME ").append(SystemPropHelper.CR)
            .append(" WHERE m.MATERIALPACKINGNAME IN (:BOXLIST) AND m.SITENAME = :SITENAME").append(SystemPropHelper.CR)
	        .append("   AND m.MATERIALSPECNAME = :MATERIALSPECNAME ").append(SystemPropHelper.CR)
//	        .append("   AND ( m.PACKINGGRADE IS NULL or m.PACKINGGRADE <> :pqcResult ) ").append(SystemPropHelper.CR)
//                .append("   AND ( m.PACKINGGRADE IS NULL or m.PACKINGGRADE <> :pqcResult ) ").append(SystemPropHelper.CR)
	        .append("GROUP BY m.MATERIALSPECNAME ,m.ERPFACTORY ,m.ERPLOCATION ,m.PACKINGGRADE,m.UNIT ");

        Map<String, Object> hashMap = new HashMap<String, Object>();
//        hashMap.put("RECEIVEACTNO", receiveActNumber);
        hashMap.put("RECEIVEACTNO", receiveActNumber);
        hashMap.put("MATERIALSPECNAME", materialCode);
        hashMap.put("SITENAME", siteName);
        hashMap.put("pqcResult", pqcResult);
        hashMap.put("BOXLIST", sapBoxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        try {

            Map<String,Object> bodyData = new HashMap<>();
            bodyData.put("BKTXT", receiveActNumber);
            List<Map<String,Object>> itemData = new ArrayList<>();

            for (Map<String, Object> mm : queryForList) {
            	if(StringUtils.isEmpty((String)mm.get("PACKINGGRADE"))) { //当前是待检
            		if("OK".equals(pqcResult)) {
            			moveType = "321";  // TF质量到非限制
            		}else if("NG".equals(pqcResult)) {
            			moveType = "350";  // TR 冻结到质检
            		}
            	}else if(StringUtils.equals("NG", (String)mm.get("PACKINGGRADE"))){ //当前是冻结
            		if("OK".equals(pqcResult)) {
            			moveType = "343";  // TF冻结到非限制
            		}else { //转成质检
            			// 322：TR 质量到非限制
            			moveType = "349";// 349：TF 冻结到质检
            		}
            	}else if(StringUtils.equals("OK", (String)mm.get("PACKINGGRADE"))){ //当前是非限制
            		if("NG".equals(pqcResult)) {
            			moveType = "344";  // TR 冻结到非限制
            		}else { //转成质检
            			moveType = "322"; // 322：TR 质量到非限制
            		}
            	}

                //UMWRK 收货工厂
                //LGORT 发货库存地点
                //UMLOG 收货库存地点
                //MATNR 发货物料号
                //UMMAT 收货物料
            	Map<String,Object> item = new HashMap<>();
            	item.put("MATNR", mm.get("MATERIALSPECNAME"));
                item.put("LGORT", mm.get("ERPLOCATION"));
                item.put("WERKS", mm.get("ERPFACTORY"));
                item.put("BWART",moveType);
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                item.put("MEINS", mm.get("UNIT"));
                String insmk = "";
                if("NG".equals(pqcResult) ){
                	insmk = "3";
                }
//                String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
                item.put("INSMK", insmk);
                itemData.add(item);

            }
           
            String sendData = ToSAPMessageUtil.mm067(user, bodyData, itemData);

            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl,"",sendData);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("iqcResultFeekback");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg2(sendData);
            erplog.setSendMsg(sendData);
            erplog.setReturnMsg2(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {
            throw new RuntimeException("SAP返回" + rmsg);
        }
        return undoId;
		
	}
	
	public String qmsResultFeekback(String siteName,String user, List<String> boxList) throws Exception{
		
		String moveType= "";		
		String rcode;
        String undoId = "";
        String rmsg = null;
        
        
        String sql="SELECT a.MATERIALSPECNAME,a.BWART,a.ERPFACTORY,a.ERPLOCATION,UNIT,sum(MATERIALQUANTITY)QTY,a.SALENO,a.SALEDETAILNO from(\r\n" + 
        		" SELECT m.MATERIALSPECNAME,m.MATERIALQUANTITY,m.ERPFACTORY,bs.SALENO,bs.SALEDETAILNO,m.ERPLOCATION,s.materialunit UNIT,\r\n" + 
        		" CASE WHEN m.PACKINGGRADE  IS NULL AND t.PACKINGGRADE ='OK' THEN '321E'\r\n" + 
        		" WHEN m.PACKINGGRADE  IS NULL AND t.PACKINGGRADE ='NG' THEN '350'\r\n" + 
        		" WHEN m.PACKINGGRADE ='OK' AND t.PACKINGGRADE IS NULL THEN '322'\r\n" + 
        		" WHEN m.PACKINGGRADE ='NG' AND t.PACKINGGRADE IS NULL THEN '349'\r\n" + 
        		" WHEN m.PACKINGGRADE ='OK' AND t.PACKINGGRADE='NG' THEN '344'\r\n" + 
        		" WHEN m.PACKINGGRADE ='NG' AND t.PACKINGGRADE='OK' THEN '343' ELSE '' END BWART\r\n" + 
        		" FROM MATERIALPACKING m ,BS_MES_SHIPPED bs, MATERIALPACKINGQMSTEMP t,MATERIALSPEC s \r\n" + 
        		" WHERE m.CHARGE =t.MATERIALPACKINGNAME \r\n" + 
        		" AND m.CHARGE=bs.CHARGE\r\n" + 
        		" AND m.MATERIALSPECNAME=s.MATERIALSPECNAME\r\n" + 
        		" AND m.CHARGE in(:BOXLIST)\r\n" + 
        		" AND m.STOCKSTATE ='Stocked'\r\n" + 
        		" AND NVL(m.PACKINGGRADE,'N') <>nvl(t.PACKINGGRADE,'N'))A\r\n" + 
        		" GROUP BY a.MATERIALSPECNAME,a.BWART,a.ERPFACTORY,a.ERPLOCATION,UNIT,a.SALENO,a.SALEDETAILNO";
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("BOXLIST", boxList);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        if(queryForList.size()>0) 
	     {
	        try {
	
	            Map<String,Object> bodyData = new HashMap<>();
	            //bodyData.put("BKTXT", receiveActNumber);
	            List<Map<String,Object>> itemData = new ArrayList<>();
	
	            for (Map<String, Object> mm : queryForList) {
	
	                //UMWRK 收货工厂
	                //LGORT 发货库存地点
	                //UMLOG 收货库存地点
	                //MATNR 发货物料号
	                //UMMAT 收货物料
	            	 //KDAUF1 发货订单号
	                //KDPOS1 发货订单行号号
	            	Map<String,Object> item = new HashMap<>();
	            	item.put("MATNR", mm.get("MATERIALSPECNAME"));
	                item.put("LGORT", mm.get("ERPLOCATION"));
	                item.put("WERKS", mm.get("ERPFACTORY"));
	                item.put("BWART",mm.get("BWART"));
	                item.put("MENGE", mm.get("QTY"));
	                item.put("MEINS", mm.get("UNIT"));
	                item.put("MAT_KDAUF", mm.get("SALENO"));
	                item.put("MAT_KDPOS", mm.get("SALEDETAILNO"));
	//                String insmk = "";
	//                if("NG".equals(pqcResult) ){
	//                	insmk = "3";
	//                }
	//                String insmk = StringUtils.equals(mm.get("OQARESULTSTATE").toString(),"END")?"":"X";
	                //item.put("INSMK", insmk);
	                itemData.add(item);
	
	            }
	           
	            String sendData = ToSAPMessageUtil.mm067(user, bodyData, itemData);
	
	            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl,"",sendData);
	            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
	
	            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
	            rcode = returnJsonObject.get("STATUS").toString();
	            rmsg = returnJsonObject.get("MSGTXT").toString();
	
	            if ("S".equals(rcode)) {
	                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
	            }
	            //将log写到表里
	            ErpMessageLog erplog = new ErpMessageLog();
	            erplog.setEventUser("");
	            erplog.setServerName("WmsToErp");
	            erplog.setEventName("QMSResultFeekback");
	            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
	            erplog.setMessageId(UUID.randomUUID().toString());
	            erplog.setSendMsg2(sendData);
	            erplog.setReturnMsg2(sapreturn);
	            erplog.setResultCode(rcode);
	            MessageLogUtil.writeMessageLog(erplog);
	        } catch (Exception e) {
	            log.info(e.getMessage(), e);
	            throw new RuntimeException("SAP返回" + rmsg);
	        }
	        if (!"S".equals(rcode)) {
	            throw new RuntimeException("SAP返回" + rmsg);
	        }
	    }
        return undoId;
		
	}

	public String OEMReturnStockIn(String shipRequestName, String siteName, String eventUser,
			Map<String, ?> args) {
		String rcode;
        String undoId = "";
        String rmsg = null;
      //依据采购订单，查询待入库的物料(MATERIALPACKING)
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT mp.SHIPREQUESTNAME ,").append(SystemPropHelper.CR)
           .append("       mp.MATERIALSPECNAME ,").append(SystemPropHelper.CR)
           .append("       mp.OQARESULT ,").append(SystemPropHelper.CR)
           .append("       mp.OQARESULTSTATE ,").append(SystemPropHelper.CR)
           .append("       mp.UNIT,").append(SystemPropHelper.CR)
           .append("       mp.REMARK ,").append(SystemPropHelper.CR)
           .append("       mp.SUPPLIERNAME ,").append(SystemPropHelper.CR)
           .append("       mp.ERPFACTORY ,").append(SystemPropHelper.CR)
           .append("       mp.ERPLOCATION ,").append(SystemPropHelper.CR)
           .append("       SUM(mp.MATERIALQUANTITY) AS MATERIALQUANTITY").append(SystemPropHelper.CR)
           .append(" FROM MATERIALPACKING mp").append(SystemPropHelper.CR)
           .append(" LEFT JOIN MATERIALSHIPREQUEST mcr").append(SystemPropHelper.CR)
           .append("        ON mp.SITENAME = mcr.SITENAME").append(SystemPropHelper.CR)
           .append("       AND mp.SHIPREQUESTNAME = mcr.SHIPREQUESTNAME").append(SystemPropHelper.CR)
           .append(" LEFT JOIN MATERIALSHIPREQUESTDETAIL m ").append(SystemPropHelper.CR)
           .append("        ON m.SITENAME = mp.SITENAME ").append(SystemPropHelper.CR)
           .append("       AND m.SHIPREQUESTNAME = mp.SHIPREQUESTNAME ").append(SystemPropHelper.CR)
           .append("       AND m.SHIPREQUESTDETAILNAME = mp.SHIPREQUESTDETAILNAME ").append(SystemPropHelper.CR)
           .append(" LEFT JOIN MATERIALSPEC m2 ").append(SystemPropHelper.CR)
           .append("        ON m2.SITENAME = mp.SITENAME ").append(SystemPropHelper.CR)
           .append("       AND m2.MATERIALSPECNAME = mp.MATERIALSPECNAME").append(SystemPropHelper.CR)
           .append("WHERE mp.SHIPREQUESTNAME = :SHIPREQUESTNAME").append(SystemPropHelper.CR)
           .append("  AND mp.SITENAME = :SITENAME").append(SystemPropHelper.CR)
           .append("  AND mp.STOCKSTATE = 'Created'").append(SystemPropHelper.CR)
           .append("GROUP BY mp.SHIPREQUESTNAME  ,mp.MATERIALSPECNAME ,mp.OQARESULT,").append(SystemPropHelper.CR)
           .append("         mp.OQARESULTSTATE,  mp.UNIT ,mp.REMARK ,mp.SUPPLIERNAME ,mp.ERPFACTORY,mp.ERPLOCATION ");
        Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("SHIPREQUESTNAME", shipRequestName);
        hashMap.put("SITENAME", siteName);
        List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
        List<Map<String, Object>> receiveBoxsQty = new ArrayList<>(); //基于标签收包的维度的数量
        try {

            Map<String,Object> bodyData = new HashMap<>();
            List<Map<String,Object>> itemData = new ArrayList<>();

            for (Map<String, Object> mm : queryForList) {

                //UMWRK 收货工厂
                //LGORT 发货库存地点
                //UMLOG 收货库存地点
                //MATNR 发货物料号
                //UMMAT 收货物料
            	Map<String,Object> item = new HashMap<>();
            	item.put("MATNR", mm.get("MATERIALSPECNAME"));
                item.put("LGORT", mm.get("ERPLOCATION"));
                item.put("WERKS", mm.get("ERPFACTORY"));
                item.put("BWART","542O");
                item.put("LIFNR", mm.get("SUPPLIERNAME"));
                item.put("MENGE", mm.get("MATERIALQUANTITY"));
                item.put("MEINS", mm.get("UNIT"));
                item.put("EBELN", mm.get("SHIPREQUESTNAME"));
                item.put("SGTXT", mm.get("REMARK"));

                itemData.add(item);

            }

            String sendData = ToSAPMessageUtil.mm067(eventUser, bodyData, itemData);

            String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl,"",sendData);
            org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

            org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
            rcode = returnJsonObject.get("STATUS").toString();
            rmsg = returnJsonObject.get("MSGTXT").toString();

            if ("S".equals(rcode)) {
                undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
            }
            //将log写到表里
            ErpMessageLog erplog = new ErpMessageLog();
            erplog.setEventUser("");
            erplog.setServerName("WmsToErp");
            erplog.setEventName("OEMReturnStockIn");
            erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
            erplog.setMessageId(UUID.randomUUID().toString());
            erplog.setSendMsg(sendData);
            erplog.setReturnMsg(sapreturn);
            erplog.setResultCode(rcode);
            MessageLogUtil.writeMessageLog(erplog);
        } catch (Exception e) {
            log.info(e.getMessage(), e);

            throw new RuntimeException("SAP返回" + rmsg);
        }
        if (!"S".equals(rcode)) {

            throw new RuntimeException("SAP返回" + rmsg);
        }
		return null;
	}

    public String qtcrNoInvoiceForCheckPlan(List<Map<String, Object>> srPk, String qtc, String user, String commitDate, String opCode) {
    return "";
    }
}
