package com.cim.idm.mwmsextend.erpinterface.service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.mwmsextend.generic.util.CommonValidation;
import com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestDetailServiceImpl;
import com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl;
import com.cim.idm.mwmsextend.materialshiprequest.service.MaterialShipRequestDetailServiceImpl;
import com.cim.idm.mwmsextend.materialshiprequest.service.MaterialShipRequestServiceImpl;
import com.cim.idm.mwmsextend.materialshiprequestToOEM.service.MaterialShipRequestToOEMServiceImpl;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingStockInfo;
import com.cim.idm.wmspackage.materialshiprequest.MaterialShipRequestServiceProxy;
import com.cim.idm.wmspackage.materialshiprequest.management.info.CreateMaterialShipRequestInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.MaterialShipRequestDetailServiceProxy;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.data.MaterialShipRequestDetail;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.CreateMaterialShipRequestDetailInfo;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.data.MaterialShipRequestToOEM;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.data.MaterialShipRequestToOEMKey;
//import com.cim.idm.wmspackage.productshiprequest.management.ShipRequestDetailService;
import com.cim.idm.wmspackage.receiverequestdetail.ReceiveRequestDetailServiceProxy;
import com.cim.idm.wmspackage.receiverequestdetail.management.data.MaterialReceiveRequestDetail;
import com.cim.idm.wmspackage.receiverequestdetail.management.data.MaterialReceiveRequestDetailKey;

public class ERPInterfaceServiceUtil {
	private static Log log = LogFactory.getLog(ERPInterfaceServiceImpl.class);


	// 2024.09.26
	// 用于处理物料发货请求（Material Ship Request）的创建、修改和删除操作
	public void INT_WMS25(String flag, EventInfo eventInfo,
            String erpFactoryName, String shipRequestName,
            String shipRequestDetailName, String materialSpecName,
            String grade, String domesticExport, String requestQuantity,
            String assignedQuantity, String shipRequestState,
            String shipRequestType, String shipRequestDetailType,
            String customerNO, String deliveryType, String shipPlanDate,
            String exportNo, String saleReason, String saleReasonDescription,
            String workOrderId, String erpReceiveFactory,
            String erpReceiveLocation, String charge, String erpLocation,
            String customsDeclare, String erpFactoryName2, String messageName, String costCenter, String receiver,
            String remark, String loadPosition, String grund, String grtxt, String POSID)
            throws CustomException {
        MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();
        MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
        String systemType = "ERP";
        String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
                .getSiteName(erpFactoryName);
        // B11区分F1材料和其余材料
        if (siteName.equals("B11")) {
            List<String> templist = new ArrayList<String>();
            String tempErpFactory = "";
            if (erpFactoryName.equals("2800")) {

                String[] array = { "107B", "107N", "110B", "110N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2811";
            } else if (erpFactoryName.equals("2809")) {

                String[] array = { "906B", "906N", "922B", "922N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2812";
            }

            if (templist.contains(erpLocation)) {
                siteName = "BBF1";
                erpFactoryName = tempErpFactory;
            }
        }
        // B4工单只有一个工厂add by mxh
        if (erpFactoryName2 == null || erpFactoryName2.equals("")) {
            erpFactoryName2 = erpFactoryName;
        }
        // B4工单行项目有值，防止其他现地为null add by mxh
        if (shipRequestDetailName == null || shipRequestDetailName.equals("")) {
            shipRequestDetailName = materialSpecName;
        }
        if (shipRequestName.startsWith("CT")) {
            shipRequestDetailType = "Z68";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("CL")) {
            shipRequestDetailType = "Z67";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("L")) {
            shipRequestDetailType = "261";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("T")) {
            shipRequestDetailType = "262";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("E")) {
            shipRequestDetailType = "521";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("F")) {
            shipRequestDetailType = "522";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("pms"))// 接收PMS系统退库入库预留
        {
            systemType = "PMS";
            shipRequestType = "StockOut";
        }
        if (shipRequestDetailType.equals("311")) {
            shipRequestType = "StockOut";
        }
        // 919移动类型特殊处理
        if (shipRequestDetailType.equals("Z32")) {
            String erpLoctionZ32 = erpLocation;
            String erpFactoryZ32 = erpFactoryName;
            erpLocation = erpReceiveLocation;
            erpFactoryName = erpReceiveFactory;
            erpReceiveLocation = erpLoctionZ32;
            erpReceiveFactory = erpFactoryZ32;
        }
        // GET SHIPREQUEST
        String sql = "SELECT * FROM MATERIALSHIPREQUEST "
                + "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";

        Map<String, String> bindMap = new HashMap<String, String>();
        bindMap.put("siteName", siteName);
        bindMap.put("shipRequestName", shipRequestName);

        List<Map<String, Object>> queryResult = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql, bindMap);

        // GET SHIPREQUESTDETAIL
        String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
                + "WHERE SITENAME = :siteName "
                + "and SHIPREQUESTNAME = :shipRequestName "
                + "and SHIPREQUESTDETAILNAME = :shipRequestDetailName ";

        Map<String, String> bindMap2 = new HashMap<String, String>();
        bindMap2.put("siteName", siteName);
        bindMap2.put("shipRequestName", shipRequestName);
        bindMap2.put("shipRequestDetailName", shipRequestDetailName);

        List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql2, bindMap2);

        /*
         * if(eventInfo.getEventName().equals("INT_WMS01")){ erpFactoryName =
         * erpFactoryName2; }
         */

        // Create
        if (flag.equals("1")) {
            if (queryResult == null || queryResult.isEmpty()) {
                shipRequestImpl.create4WMS25(eventInfo, siteName, shipRequestName,
                        shipRequestState, shipRequestType,
                        shipRequestDetailType, customerNO, deliveryType,
                        shipPlanDate, exportNo, saleReason,
                        saleReasonDescription, workOrderId, erpReceiveFactory,
                        erpReceiveLocation, systemType, erpFactoryName,
                        customsDeclare, costCenter, receiver, grund, grtxt);
            }
            if (queryResult2 == null || queryResult2.isEmpty()) {
                shipRequestDetailImpl.create4WMS25(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, charge, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        (messageName
                                .equals("INT_WMS01")
                                || messageName
                                        .equals("INT_PI061")) ? erpFactoryName : "",
                        remark, loadPosition, POSID);
            }
        }

        // Modfiy
        if (flag.equals("2")) {

            if (queryResult == null || queryResult.isEmpty())
                // throw new CustomException("INT-0003", shipRequestName);
                shipRequestImpl.create4WMS25(eventInfo, siteName, shipRequestName,
                        shipRequestState, shipRequestType,
                        shipRequestDetailType, customerNO, deliveryType,
                        shipPlanDate, exportNo, saleReason,
                        saleReasonDescription, workOrderId, erpReceiveFactory,
                        erpReceiveLocation, systemType, erpFactoryName,
                        customsDeclare, costCenter, receiver, grund, grtxt);
            /*
             * if (queryResult != null && !queryResult.isEmpty()) {
             * String state = queryResult.get(0).get("SHIPREQUESTSTATE")
             * .toString();
             * if (!state.equals("Created"))
             * throw new CustomException("INT-0007", shipRequestName);
             * 
             * }
             */
            if (queryResult != null && !queryResult.isEmpty() && receiver != "") {// PMS预留需要完整的成本中心信息和申请人信息，存在修改
                shipRequestImpl.modifyReceiver(eventInfo, siteName, shipRequestName, costCenter, receiver);
            }

            if (queryResult2 == null || queryResult2.isEmpty())
                // throw new CustomException("INT-0004",
                // shipRequestName,shipRequestDetailName);
                shipRequestDetailImpl.create4WMS25(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, charge, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        (messageName
                                .equals("INT_WMS01")
                                || messageName
                                        .equals("INT_PI061")) ? erpFactoryName : "",
                        remark, loadPosition, POSID);
            if (queryResult2 != null && !queryResult2.isEmpty()) {
                // 判断预留单拣配绑定的数量是否为0
                String assignedQuantity1 = queryResult2.get(0).get("ASSIGNEDQUANTITY")
                        .toString();
                if (!assignedQuantity1.equals("0"))
                    throw new CustomException("INT-0007", shipRequestName);

                shipRequestDetailImpl.modify4WMS25(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        charge, remark, POSID);
                // 已经拣配的BOX全部解绑
                String updateBox = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
                Map<String, String> bindMapBox = new HashMap<String, String>();
                bindMapBox.put("shiprequestname", shipRequestName);
                bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(updateBox, bindMapBox);
                String sql9 = "UPDATE MATERIALSHIPREQUEST SET SHIPREQUESTSTATE='Created' WHERE SHIPREQUESTNAME= :shipRequestName";
                Map<String, String> bindMap9 = new HashMap<String, String>();
                bindMap9.put("shipRequestName", shipRequestName);
                IDMFrameServiceProxy.getSqlTemplate()
                        .getJdbcTemplate().update(sql9, bindMap9);

            }

        }
        // Remove
        if (flag.equals("3")) {

            if (queryResult == null || queryResult.isEmpty()) {
            }
            // throw new CustomException("INT-0003", shipRequestName);

            if (queryResult2 == null || queryResult2.isEmpty()) {
            }
            // throw new CustomException("INT-0004",
            // shipRequestName,shipRequestDetailName);
            else {
                if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
                        .equals("0")) {
                    shipRequestDetailImpl.remove(eventInfo, siteName,
                            shipRequestName, shipRequestDetailName);
                    // 行项目下已经拣配的BOX全部解绑
                    String updateBox1 = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
                    Map<String, String> bindMapBox = new HashMap<String, String>();
                    bindMapBox.put("shiprequestname", shipRequestName);
                    bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
                    IDMFrameServiceProxy.getSqlTemplate()
                            .update(updateBox1, bindMapBox);

                    // GET SHIPREQUEST
                    String sql4 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
                            + "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";
                    Map<String, String> bindMap4 = new HashMap<String, String>();
                    bindMap4.put("siteName", siteName);
                    bindMap4.put("shipRequestName", shipRequestName);
                    List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
                            .getSqlTemplate()
                            .queryForList(sql4, bindMap4);
                    if (queryResult4 == null || queryResult4.isEmpty()) {
                        shipRequestImpl.remove(eventInfo, siteName,
                                shipRequestName);
                        String sql7 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName";
                        Map<String, String> bindMap7 = new HashMap<String, String>();
                        bindMap7.put("shipRequestName", shipRequestName);
                        IDMFrameServiceProxy.getSqlTemplate()
                                .getJdbcTemplate().update(sql7, bindMap7);
                    }

                } else {
                    throw new CustomException("INT-0015", shipRequestName,
                            shipRequestDetailName);
                }
            }

        }
    }


	public void INT_WMS10(String flag, EventInfo eventInfo,
			String erpFactoryName, String shipRequestName,
			String shipRequestDetailName, String materialSpecName,
			String grade, String domesticExport, String requestQuantity,
			String assignedQuantity, String shipRequestState,
			String shipRequestType, String shipRequestDetailType,
			String customerNO, String deliveryType, String shipPlanDate,
			String exportNo, String saleReason, String saleReasonDescription,
			String workOrderId, String erpReceiveFactory,
			String erpReceiveLocation, String charge, String erpLocation,
			String customsDeclare, String erpFactoryName2, String messageName,String costCenter,String receiver,String remark,String loadPosition)
			throws CustomException {
		MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();
		MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
        String systemType="ERP";
		String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
				.getSiteName(erpFactoryName);
		//B11区分F1材料和其余材料
		if(siteName.equals("B11"))
		{
			List<String> templist=new ArrayList<String>();
			String tempErpFactory="";
			if(erpFactoryName.equals("2800")){
				
				String[] array={"107B","107N","110B","110N"};
				templist=Arrays.asList(array);
				tempErpFactory="2811";
			}else if(erpFactoryName.equals("2809")){
				
				String[] array={"906B","906N","922B","922N"};
				templist=Arrays.asList(array);
				tempErpFactory="2812";
			}
			
			if(templist.contains(erpLocation))
			{
				siteName="BBF1";
				erpFactoryName=tempErpFactory;
			}
		}
		//B4工单只有一个工厂add by mxh
		if(erpFactoryName2==null||erpFactoryName2.equals(""))
		{
			erpFactoryName2=erpFactoryName;
		}
		//B4工单行项目有值，防止其他现地为null add by mxh
		if(shipRequestDetailName==null||shipRequestDetailName.equals(""))
		{
			shipRequestDetailName=materialSpecName;
		}
		if(shipRequestName.startsWith("CT"))
		{
			shipRequestDetailType="Z68";
			shipRequestType="Refund";
		}
		if(shipRequestName.startsWith("CL"))
		{
			shipRequestDetailType="Z67";
			shipRequestType="StockOut";
		}
		if(shipRequestName.startsWith("L"))
		{
			shipRequestDetailType="261";
			shipRequestType="StockOut";
		}
		if(shipRequestName.startsWith("T"))
		{
			shipRequestDetailType="262";
			shipRequestType="Refund";
		}
		if(shipRequestName.startsWith("E"))
		{
			shipRequestDetailType="521";
			shipRequestType="Refund";
		}
		if(shipRequestName.startsWith("F"))
		{
			shipRequestDetailType="522";
			shipRequestType="StockOut";
		}
		if(shipRequestName.startsWith("pms"))//接收PMS系统退库入库预留
		{
			systemType="PMS";
			shipRequestType="StockOut";
		}
		if(shipRequestDetailType.equals("311")){
			shipRequestType="StockOut";
		}
		// GET SHIPREQUEST
		String sql = "SELECT * FROM MATERIALSHIPREQUEST "
				+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET SHIPREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName "
				+ "and SHIPREQUESTNAME = :shipRequestName "
				+ "and SHIPREQUESTDETAILNAME = :shipRequestDetailName ";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("shipRequestName", shipRequestName);
		bindMap2.put("shipRequestDetailName", shipRequestDetailName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);

		/*
		 * if(eventInfo.getEventName().equals("INT_WMS01")){ erpFactoryName =
		 * erpFactoryName2; }
		 */

		// Create
		if (flag.equals("1")) {
			if (queryResult == null || queryResult.isEmpty()) {
				shipRequestImpl.create(eventInfo, siteName, shipRequestName,
						shipRequestState, shipRequestType,
						shipRequestDetailType, customerNO, deliveryType,
						shipPlanDate, exportNo, saleReason,
						saleReasonDescription, workOrderId, erpReceiveFactory,
						erpReceiveLocation, systemType, erpFactoryName,
						customsDeclare,costCenter,receiver);
			}
			if (queryResult2 == null || queryResult2.isEmpty()) {
				shipRequestDetailImpl.create(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,
						materialSpecName, grade, domesticExport,
						requestQuantity, assignedQuantity, charge, erpLocation,
						(messageName.equals("INT_WMS01") || messageName
								.equals("INT_PI061")) ? erpFactoryName2
								: erpFactoryName, (messageName
								.equals("INT_WMS01") || messageName
								.equals("INT_PI061")) ? erpFactoryName : "",remark,loadPosition);
			}
		}

		// Modfiy
		if (flag.equals("2")) {

			if (queryResult == null || queryResult.isEmpty())
				// throw new CustomException("INT-0003", shipRequestName);
				shipRequestImpl.create(eventInfo, siteName, shipRequestName,
						shipRequestState, shipRequestType,
						shipRequestDetailType, customerNO, deliveryType,
						shipPlanDate, exportNo, saleReason,
						saleReasonDescription, workOrderId, erpReceiveFactory,
						erpReceiveLocation, systemType, erpFactoryName,
						customsDeclare,costCenter,receiver);
			/*if (queryResult != null && !queryResult.isEmpty()) {
				String state = queryResult.get(0).get("SHIPREQUESTSTATE")
						.toString();
				if (!state.equals("Created"))
					throw new CustomException("INT-0007", shipRequestName);
			
			}*/
			if (queryResult != null && !queryResult.isEmpty()&&receiver!="") {//PMS预留需要完整的成本中心信息和申请人信息，存在修改
				shipRequestImpl.modifyReceiver(eventInfo, siteName, shipRequestName, costCenter, receiver);
			}

			if (queryResult2 == null || queryResult2.isEmpty())
				// throw new CustomException("INT-0004",
				// shipRequestName,shipRequestDetailName);
				shipRequestDetailImpl.create(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,
						materialSpecName, grade, domesticExport,
						requestQuantity, assignedQuantity, charge, erpLocation , 
						(messageName.equals("INT_WMS01") || messageName
								.equals("INT_PI061")) ? erpFactoryName2
								: erpFactoryName, (messageName
								.equals("INT_WMS01") || messageName
								.equals("INT_PI061")) ? erpFactoryName : "",remark,loadPosition);
			if (queryResult2 != null && !queryResult2.isEmpty()) {
                //判断预留单拣配绑定的数量是否为0
				 String assignedQuantity1=queryResult2.get(0).get("ASSIGNEDQUANTITY")
							.toString();
				 if(!assignedQuantity1.equals("0"))
					 throw new CustomException("INT-0007", shipRequestName);
				 
				shipRequestDetailImpl.modifyForB17(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,
						materialSpecName, grade, domesticExport,
						requestQuantity, assignedQuantity, erpLocation,
						(messageName.equals("INT_WMS01") || messageName
								.equals("INT_PI061")) ? erpFactoryName2
								: erpFactoryName, charge,remark);
				    //已经拣配的BOX全部解绑
					String updateBox = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
					Map<String, String> bindMapBox = new HashMap<String, String>();
					bindMapBox.put("shiprequestname", shipRequestName);
					bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
					IDMFrameServiceProxy.getSqlTemplate()
							.update(updateBox, bindMapBox);
					String sql9 = "UPDATE MATERIALSHIPREQUEST SET SHIPREQUESTSTATE='Created' WHERE SHIPREQUESTNAME= :shipRequestName";
					Map<String, String> bindMap9 = new HashMap<String, String>();
					bindMap9.put("shipRequestName", shipRequestName);
					IDMFrameServiceProxy.getSqlTemplate()
							.update(sql9, bindMap9);
				
			}

		}
		// Remove
		if (flag.equals("3")) {

			if (queryResult == null || queryResult.isEmpty()) {
			}
			// throw new CustomException("INT-0003", shipRequestName);
			
			if (queryResult2 == null || queryResult2.isEmpty()) {
			}
			// throw new CustomException("INT-0004",
			// shipRequestName,shipRequestDetailName);
			else {
				if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
						.equals("0")) {
					shipRequestDetailImpl.remove(eventInfo, siteName,
							shipRequestName, shipRequestDetailName);
					//行项目下已经拣配的BOX全部解绑
					String updateBox1 = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
					Map<String, String> bindMapBox = new HashMap<String, String>();
					bindMapBox.put("shiprequestname", shipRequestName);
					bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
					IDMFrameServiceProxy.getSqlTemplate()
							.update(updateBox1, bindMapBox);
					
					
					// GET SHIPREQUEST
					String sql4 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
							+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";
					Map<String, String> bindMap4 = new HashMap<String, String>();
					bindMap4.put("siteName", siteName);
					bindMap4.put("shipRequestName", shipRequestName);
					List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql4, bindMap4);
					if (queryResult4 == null || queryResult4.isEmpty()) {
						shipRequestImpl.remove(eventInfo, siteName,
								shipRequestName);
						String sql7 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName";
						Map<String, String> bindMap7 = new HashMap<String, String>();
						bindMap7.put("shipRequestName", shipRequestName);
						IDMFrameServiceProxy.getSqlTemplate()
								.update(sql7, bindMap7);	
					}

				} else {
					throw new CustomException("INT-0015", shipRequestName,
							shipRequestDetailName);
				}
			}

		}
	}

	
	//（由ERPInterfaceServiceUtil INT_WMS10更改）
    public void INT_14340(String flag, EventInfo eventInfo,
            String erpFactoryName, String shipRequestName,
            String shipRequestDetailName, String materialSpecName,
            String grade, String domesticExport, String requestQuantity,
            String assignedQuantity, String shipRequestState,
            String shipRequestType, String shipRequestDetailType,
            String customerNO, String deliveryType, String shipPlanDate,
            String exportNo, String saleReason, String saleReasonDescription,
            String workOrderId, String erpReceiveFactory,
            String erpReceiveLocation, String charge, String erpLocation,
            String customsDeclare, String erpFactoryName2, String messageName, String costCenter,
            String receiver, String remark, String loadPosition, String grund,
            String zf_State, String seq, String wbs_O, String wbs_N, String meIns, String erfMe, String xloEk,
            String kzEar,
            String xwaOk, String liFnr, String name1, String bwtar, String sobkz)
            throws CustomException {
        MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();
        MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
        String systemType = "ERP";
        String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
                .getSiteName(erpFactoryName);
        // B11区分F1材料和其余材料
        if (siteName.equals("B11")) {
            List<String> templist = new ArrayList<String>();
            String tempErpFactory = "";
            if (erpFactoryName.equals("2800")) {

                String[] array = { "107B", "107N", "110B", "110N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2811";
            } else if (erpFactoryName.equals("2809")) {

                String[] array = { "906B", "906N", "922B", "922N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2812";
            }

            if (templist.contains(erpLocation)) {
                siteName = "BBF1";
                erpFactoryName = tempErpFactory;
            }
        }
        // B4工单只有一个工厂add by mxh
        if (erpFactoryName2 == null || erpFactoryName2.equals("")) {
            erpFactoryName2 = erpFactoryName;
        }
        // B4工单行项目有值，防止其他现地为null add by mxh
        if (shipRequestDetailName == null || shipRequestDetailName.equals("")) {
            shipRequestDetailName = materialSpecName;
        }
        if (shipRequestName.startsWith("CT")) {
            shipRequestDetailType = "Z68";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("CL")) {
            shipRequestDetailType = "Z67";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("L")) {
            shipRequestDetailType = "261";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("T")) {
            shipRequestDetailType = "262";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("E")) {
            shipRequestDetailType = "521";
            shipRequestType = "Refund";
        }
        if (shipRequestName.startsWith("F")) {
            shipRequestDetailType = "522";
            shipRequestType = "StockOut";
        }
        if (shipRequestName.startsWith("pms"))// 接收PMS系统退库入库预留
        {
            systemType = "PMS";
            shipRequestType = "StockOut";
        }
        if (shipRequestDetailType.equals("311")&&grund.equals("0000")) {
            shipRequestType = "StockOut";
        }
        // GET SHIPREQUEST
        String sql = "SELECT * FROM MATERIALSHIPREQUEST "
                + "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";

        Map<String, String> bindMap = new HashMap<String, String>();
        bindMap.put("siteName", siteName);
        bindMap.put("shipRequestName", shipRequestName);

        List<Map<String, Object>> queryResult = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql, bindMap);

        // GET SHIPREQUESTDETAIL
        String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
                + "WHERE SITENAME = :siteName "
                + "and SHIPREQUESTNAME = :shipRequestName "
                + "and SHIPREQUESTDETAILNAME = :shipRequestDetailName ";

        Map<String, String> bindMap2 = new HashMap<String, String>();
        bindMap2.put("siteName", siteName);
        bindMap2.put("shipRequestName", shipRequestName);
        bindMap2.put("shipRequestDetailName", shipRequestDetailName);

        List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql2, bindMap2);

        /*
         * if(eventInfo.getEventName().equals("INT_WMS01")){ erpFactoryName =
         * erpFactoryName2; }
         */

        // Create
        if (flag.equals("1")) {
            if (queryResult == null || queryResult.isEmpty()) {
                shipRequestImpl.create(eventInfo, siteName, shipRequestName,
                        shipRequestState, shipRequestType,
                        shipRequestDetailType, customerNO, deliveryType,
                        shipPlanDate, exportNo, saleReason,
                        saleReasonDescription, workOrderId, erpReceiveFactory,
                        erpReceiveLocation, systemType, erpFactoryName,
                        customsDeclare, costCenter, receiver, grund, zf_State);
            }
            if (queryResult2 == null || queryResult2.isEmpty()) {
                shipRequestDetailImpl.create(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, charge, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        (messageName
                                .equals("INT_WMS01")
                                || messageName
                                        .equals("INT_PI061")) ? erpFactoryName : "",
                        remark, loadPosition, seq, wbs_O, wbs_N,
                        meIns, erfMe, xloEk, kzEar, xwaOk, liFnr, name1, bwtar, sobkz);
            }
        }

        // Modfiy
        if (flag.equals("2")) {

            if (queryResult == null || queryResult.isEmpty())
                // throw new CustomException("INT-0003", shipRequestName);
                shipRequestImpl.create(eventInfo, siteName, shipRequestName,
                        shipRequestState, shipRequestType,
                        shipRequestDetailType, customerNO, deliveryType,
                        shipPlanDate, exportNo, saleReason,
                        saleReasonDescription, workOrderId, erpReceiveFactory,
                        erpReceiveLocation, systemType, erpFactoryName,
                        customsDeclare, costCenter, receiver, grund, zf_State);
            /*
             * if (queryResult != null && !queryResult.isEmpty()) {
             * String state = queryResult.get(0).get("SHIPREQUESTSTATE")
             * .toString();
             * if (!state.equals("Created"))
             * throw new CustomException("INT-0007", shipRequestName);
             * 
             * }
             */
            if (queryResult != null && !queryResult.isEmpty() && receiver != "") {// PMS预留需要完整的成本中心信息和申请人信息，存在修改
                shipRequestImpl.modifyReceiver(eventInfo, siteName, shipRequestName, costCenter, receiver);
            }

            if (queryResult2 == null || queryResult2.isEmpty())
                // throw new CustomException("INT-0004",
                // shipRequestName,shipRequestDetailName);
                shipRequestDetailImpl.create(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, charge, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        (messageName
                                .equals("INT_WMS01")
                                || messageName
                                        .equals("INT_PI061")) ? erpFactoryName : "",
                        remark, loadPosition, seq, wbs_O, wbs_N,
                        meIns, erfMe, xloEk, kzEar, xwaOk, liFnr, name1, bwtar, sobkz);
            if (queryResult2 != null && !queryResult2.isEmpty()) {
                // 判断预留单拣配绑定的数量是否为0
                String assignedQuantity1 = queryResult2.get(0).get("ASSIGNEDQUANTITY")
                        .toString();
                if (!assignedQuantity1.equals("0"))
                    throw new CustomException("INT-0007", shipRequestName);

                shipRequestDetailImpl.modify1(eventInfo, siteName,
                        shipRequestName, shipRequestDetailName,
                        materialSpecName, grade, domesticExport,
                        requestQuantity, assignedQuantity, erpLocation,
                        (messageName.equals("INT_WMS01") || messageName
                                .equals("INT_PI061")) ? erpFactoryName2
                                        : erpFactoryName,
                        charge);
                // 已经拣配的BOX全部解绑
                String updateBox = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
                Map<String, String> bindMapBox = new HashMap<String, String>();
                bindMapBox.put("shiprequestname", shipRequestName);
                bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(updateBox, bindMapBox);
                String sql9 = "UPDATE MATERIALSHIPREQUEST SET SHIPREQUESTSTATE='Created' WHERE SHIPREQUESTNAME= :shipRequestName";
                Map<String, String> bindMap9 = new HashMap<String, String>();
                bindMap9.put("shipRequestName", shipRequestName);
                IDMFrameServiceProxy.getSqlTemplate()
                        .getJdbcTemplate().update(sql9, bindMap9);

            }

        }
        // Remove
        if (flag.equals("3")) {

            if (queryResult == null || queryResult.isEmpty()) {
            }
            // throw new CustomException("INT-0003", shipRequestName);

            if (queryResult2 == null || queryResult2.isEmpty()) {
            }
            // throw new CustomException("INT-0004",
            // shipRequestName,shipRequestDetailName);
            else {
                if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
                        .equals("0")) {
                    shipRequestDetailImpl.remove(eventInfo, siteName,
                            shipRequestName, shipRequestDetailName);
                    // 行项目下已经拣配的BOX全部解绑
                    String updateBox1 = "update materialpacking set shiprequestname=null,shiprequestdetailname=null where shiprequestname=:shiprequestname and shiprequestdetailname=:shiprequestdetailname";
                    Map<String, String> bindMapBox = new HashMap<String, String>();
                    bindMapBox.put("shiprequestname", shipRequestName);
                    bindMapBox.put("shiprequestdetailname", shipRequestDetailName);
                    IDMFrameServiceProxy.getSqlTemplate()
                            .update(updateBox1, bindMapBox);

                    // GET SHIPREQUEST
                    String sql4 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
                            + "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";
                    Map<String, String> bindMap4 = new HashMap<String, String>();
                    bindMap4.put("siteName", siteName);
                    bindMap4.put("shipRequestName", shipRequestName);
                    List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
                            .getSqlTemplate()
                            .queryForList(sql4, bindMap4);
                    if (queryResult4 == null || queryResult4.isEmpty()) {
                        shipRequestImpl.remove(eventInfo, siteName,
                                shipRequestName);
                        String sql7 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName";
                        Map<String, String> bindMap7 = new HashMap<String, String>();
                        bindMap7.put("shipRequestName", shipRequestName);
                        IDMFrameServiceProxy.getSqlTemplate()
                                .getJdbcTemplate().update(sql7, bindMap7);
                    }

                } else {
                    throw new CustomException("INT-0015", shipRequestName,
                            shipRequestDetailName);
                }
            }

        }
    }

	
	
	
	// INT_WMS01 also use INT_WMS10

	public void INT_WMS04(String flag, EventInfo eventInfo,
			String erpFactoryName, String shipRequestName,
			String shipRequestDetailName, String materialSpecName,
			String grade, String domesticExport, String requestQuantity,
			String assignedQuantity, String shipRequestState,
			String shipRequestType, String shipRequestDetailType,
			String customerNO, String deliveryType, String shipPlanDate,
			String exportNo, String saleReason, String saleReasonDescription,
			String workOrderId, String erpReceiveFactory,
			String erpReceiveLocation, String charge, String erpLocation,
			String customerName, String destination, String address,
			String customsDeclare) throws CustomException {
		MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();
		MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
		String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
				.getSiteName(erpFactoryName);

		// GET SHIPREQUEST
		String sql = "SELECT * FROM MATERIALSHIPREQUEST " + "WHERE 1=1 "
		// + "and SITENAME = :siteName "
				+ "and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET SHIPREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL " + "WHERE 1=1 "
		/* + "and SITENAME = :siteName " */
		+ "and SHIPREQUESTNAME = :shipRequestName "
				+ "and SHIPREQUESTDETAILNAME = :shipRequestDetailName ";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("shipRequestName", shipRequestName);
		bindMap2.put("shipRequestDetailName", shipRequestDetailName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);

		// GET SHIPREQUESTDETAIL LIST
		String sql3 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL " + "WHERE 1=1 "
		// + "and SITENAME = :siteName "
				+ "and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap3 = new HashMap<String, String>();
		bindMap3.put("siteName", siteName);
		bindMap3.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult3 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql3, bindMap3);

		// Create
		if (flag.equals("CRT")) {
			if (queryResult == null || queryResult.isEmpty()) {
				shipRequestImpl.create(eventInfo, siteName, shipRequestName,
						shipRequestState, shipRequestType,
						shipRequestDetailType, customerNO, deliveryType,
						shipPlanDate, exportNo, saleReason,
						saleReasonDescription, workOrderId, erpReceiveFactory,
						erpReceiveLocation, "ERP", erpFactoryName,
						customsDeclare,"","");
			}
			if (queryResult2 == null || queryResult2.isEmpty()) {
				shipRequestDetailImpl.create(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,
						materialSpecName, grade, domesticExport,
						requestQuantity, assignedQuantity, charge, erpLocation,
						erpFactoryName, "","","");
			} else
				throw new CustomException("INT-0005", shipRequestName,
						shipRequestDetailName);

			shipRequestImpl.createCustomer(customerNO, customerName,
					destination, address);
		}

		// Modfiy or Remove
		if (flag.equals("CHG") || flag.equals("DEL")) {

			if (queryResult == null || queryResult.isEmpty()) {
			}
			// throw new CustomException("INT-0003", shipRequestName);

			if (flag.equals("CHG")) {
				if (queryResult == null || queryResult.isEmpty())
					throw new CustomException("INT-0003", shipRequestName);
				shipRequestImpl.modifyInterface(eventInfo, siteName,
						shipRequestName, exportNo);
//				if (queryResult2.size() > 0) {
//					shipRequestDetailImpl.modify1(eventInfo, siteName,
//							shipRequestName, shipRequestDetailName,
//							materialSpecName, grade, domesticExport,
//							requestQuantity, assignedQuantity, erpLocation,
//							erpFactoryName, charge);
					String sql6="select  * from materialshiprequestdetail where SHIPREQUESTNAME= :shipRequestName  and SHIPREQUESTDETAILNAME= :shipRequestDetailName";
					Map<String, String> bindMap6 = new HashMap<String, String>();
					bindMap6.put("shipRequestName", shipRequestName);
					bindMap6.put("shipRequestDetailName", shipRequestDetailName);
					List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
							.getSqlTemplate().queryForList(sql6, bindMap6);
					if(Double.parseDouble(queryResult4.get(0).get("REQUESTQUANTITY").toString())!=Double.parseDouble(requestQuantity.toString()))
					{
					String sql7 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName  and SHIPREQUESTDETAILNAME= :shipRequestDetailName";
					Map<String, String> bindMap7 = new HashMap<String, String>();
					bindMap7.put("shipRequestName", shipRequestName);
					bindMap7.put("shipRequestDetailName", shipRequestDetailName);
					IDMFrameServiceProxy.getSqlTemplate()
							.update(sql7, bindMap7);
					String sql9 = "UPDATE MATERIALSHIPREQUEST SET SHIPREQUESTSTATE='Created' WHERE SHIPREQUESTNAME= :shipRequestName";
					Map<String, String> bindMap9 = new HashMap<String, String>();
					bindMap9.put("shipRequestName", shipRequestName);
					IDMFrameServiceProxy.getSqlTemplate()
							.update(sql9, bindMap9);
					if (queryResult2.size() > 0) {		
					}
						shipRequestDetailImpl.modify1(eventInfo, siteName,
								shipRequestName, shipRequestDetailName,
								materialSpecName, grade, domesticExport,
								requestQuantity, assignedQuantity, erpLocation,
								erpFactoryName, charge);
					}else{
						if (queryResult2.size() > 0) {
							 assignedQuantity=queryResult2.get(0).get("ASSIGNEDQUANTITY")
										.toString();
							shipRequestDetailImpl.modify1(eventInfo, siteName,
									shipRequestName, shipRequestDetailName,
									materialSpecName, grade, domesticExport,
									requestQuantity, assignedQuantity, erpLocation,
									erpFactoryName, charge);
					}
					}
				}

			if (flag.equals("DEL")) {
				// 当行项目为000000时，为删除单号和所有行项目操作
				if (shipRequestDetailName.equals("000000")) {
					if (queryResult.size() > 0) {
						shipRequestImpl.remove(eventInfo, siteName,
								shipRequestName);
					}
					if (queryResult3.size() > 0) {
						String sql6 = "DELETE FROM MATERIALSHIPREQUESTDETAIL "
								+ "WHERE 1=1 "
								+ "and SHIPREQUESTNAME = :shipRequestName ";

						Map<String, String> bindMap6 = new HashMap<String, String>();
						bindMap6.put("shipRequestName", shipRequestName);
						IDMFrameServiceProxy.getSqlTemplate()
								.update(sql6, bindMap6);
						String sql8 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName";
						Map<String, String> bindMap8 = new HashMap<String, String>();
						bindMap8.put("shipRequestName", shipRequestName);						
						IDMFrameServiceProxy.getSqlTemplate()
								.update(sql8, bindMap8);
					}
				} else {
					if (queryResult3.size() > 0) {
						if (queryResult3.size() == 1) {
							// 当前交货单删除所有行项目时，删除单号信息
							shipRequestImpl.remove(eventInfo, siteName,
									shipRequestName);
						}
						if (queryResult2 != null && !queryResult2.isEmpty()) {

							String sql4 = "DELETE FROM MATERIALSHIPREQUESTDETAIL "
									+ "WHERE 1=1 "
									+ "and SHIPREQUESTNAME = :shipRequestName "
									+ "and SHIPREQUESTDETAILNAME = :shipRequestDetailName";

							Map<String, String> bindMap4 = new HashMap<String, String>();
							bindMap4.put("shipRequestName", shipRequestName);
							bindMap4.put("shipRequestDetailName",
									shipRequestDetailName);
							String sql7 = "update materialpacking set SHIPREQUESTNAME=null,SHIPREQUESTDETAILNAME=null where SHIPREQUESTNAME= :shipRequestName  and SHIPREQUESTDETAILNAME= :shipRequestDetailName";
							Map<String, String> bindMap7 = new HashMap<String, String>();
							bindMap7.put("shipRequestName", shipRequestName);
							bindMap7.put("shipRequestDetailName", shipRequestDetailName);
							IDMFrameServiceProxy.getSqlTemplate()
									.update(sql7, bindMap7);
							try {
								IDMFrameServiceProxy.getSqlTemplate()
										
										.update(sql4, bindMap4);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
				}

			}
		}
	}

	// else{
	// throw new CustomException("INT-0008", flag);
	// }

	public void INT_WMS09(String flag, EventInfo eventInfo,
			String erpFactoryName, String receiveRequestName,
			String receiveRequestDetailName, String purchaseOrderGroup,
			String receiveRequestState, String pocategory,
			String receiveRequestDetailType, String materialSpecName,
			String description2, String requestQuantity,
			String receivedQuantity, String erpLocation, String returnFlag,
			String freeFlag, String forceCompletedFlag,
			String receiveRequestDetailState, String holdState, String iqcFlag,
			String planDate, String applicant, String charge,
			String supplierNo, String address, String city, String fax,
			String tel, String postCode, String nationalNo, String description,
			String subMaterialSpecName, String requestQuantity2,String innerFlag,String passState,String innerOrder)
			throws CustomException, ParseException {
		MaterialReceiveRequestServiceImpl receiveRequestImpl = new MaterialReceiveRequestServiceImpl();
		MaterialReceiveRequestDetailServiceImpl receiveRequestDetailImpl = new MaterialReceiveRequestDetailServiceImpl();
		MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();
		String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
				.getSiteName(erpFactoryName);
		//B11区分F1材料和其余材料
		if(siteName.equals("B11"))
		{
			List<String> templist=new ArrayList<String>();
			String tempErpFactory="";
			if(erpFactoryName.equals("2800")){
				
				String[] array={"107B","107N","110B","110N"};
				templist=Arrays.asList(array);
				tempErpFactory="2811";
			}else if(erpFactoryName.equals("2809")){
				
				String[] array={"906B","906N","922B","922N"};
				templist=Arrays.asList(array);
				tempErpFactory="2812";
			}
			
			if(templist.contains(erpLocation))
			{
				siteName="BBF1";
				erpFactoryName=tempErpFactory;
			}
		}
		// GET RECEIVEREQUEST
		String sql = "SELECT * FROM MATERIALRECEIVEREQUEST "
				+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("receiveRequestName", receiveRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET RECEIVEREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName and RECEIVEREQUESTNAME = :receiveRequestName";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("receiveRequestDetailName", receiveRequestDetailName);
		bindMap2.put("receiveRequestName", receiveRequestName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);

		// GET OEM
		String sql3 = "SELECT * FROM MATERIALSHIPREQUESTTOOEM "
				+ "WHERE SITENAME = :siteName  and RECEIVEREQUESTNAME = :receiveRequestName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName"
				+ " and SUBMATERIALSPECNAME = :subMaterialSpecName";

		Map<String, String> bindMap3 = new HashMap<String, String>();
		bindMap3.put("siteName", siteName);
		bindMap3.put("receiveRequestName", receiveRequestName);
		bindMap3.put("receiveRequestDetailName", receiveRequestDetailName);
		bindMap3.put("subMaterialSpecName", subMaterialSpecName);

		List<Map<String, Object>> queryResult3 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql3, bindMap3);

		// Create
		if (flag.equals("1")) {
			if (queryResult == null || queryResult.isEmpty()) {
				
				if(passState==null||passState.equals(""))
					passState="Created";
				if(passState.equals("XX"))
					passState="Completed";
				receiveRequestImpl.create(eventInfo, siteName,
						receiveRequestName, purchaseOrderGroup,
						receiveRequestState, supplierNo, "ERP", "", "", "", "",passState);
			}else {
				//if((queryResult.get(0).get("PASSSTATE")==null?"":queryResult.get(0).get("PASSSTATE").toString()).equals("Created"))
//					{
					receiveRequestImpl.modify(eventInfo, siteName, receiveRequestName, purchaseOrderGroup, receiveRequestState, supplierNo, "ERP", "", "", "", "");
				
					
			}
			//Updateed By WH 2017/1/10 materialreceiverequestdetail表添加innerflag字段  原API不满足需求
			if (queryResult2 == null || queryResult2.isEmpty()) {
//				receiveRequestDetailImpl.create(eventInfo, siteName,
//						receiveRequestName, receiveRequestDetailName,
//						pocategory, receiveRequestDetailType, materialSpecName,
//						description2, requestQuantity, receivedQuantity,
//						erpLocation, returnFlag, freeFlag, forceCompletedFlag,
//						receiveRequestDetailState, holdState, iqcFlag,
//						planDate, applicant, charge, erpFactoryName);				
				MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
				MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
				mrdk.setSiteName(siteName);
				mrdk.setReceiveRequestName(receiveRequestName);
				mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
				mrd.setKey(mrdk);					
				mrd.setPocategory(pocategory);
				mrd.setReceiveRequestDetailType(receiveRequestDetailType);
				mrd.setMaterialSpecName(materialSpecName);
				mrd.setDescription(description2);
				if(!receivedQuantity.isEmpty())
					mrd.setRequestQuantity(Double.valueOf(requestQuantity));
				if(!receivedQuantity.isEmpty())
					mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
				mrd.setErpLocation(erpLocation);
				mrd.setErpFactory(erpFactoryName);
				mrd.setReturnFlag(returnFlag);
				mrd.setFreeFlag(freeFlag);
				mrd.setForceCompletedFlag(forceCompletedFlag);
				mrd.setReceiveRequestDetailState(receiveRequestDetailState);
				mrd.setHoldState(holdState);
				mrd.setIqcFlag(iqcFlag);
				if(!(planDate ==null || planDate.isEmpty() || planDate.equals("0000-00-00")))
				{
					planDate+=" 00:00:00";
					mrd.setPlanDate(Timestamp.valueOf(planDate));
				}
				mrd.setApplicant(applicant);
				mrd.setCharge(charge);
				mrd.setInnerFlag(innerFlag);
				mrd.setInnerOrder(innerOrder);//内部订单号，EN确认生产计划
				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);								
			}
			// else{
			if (receiveRequestDetailType.equals("3")) {
				if (queryResult3 == null || queryResult3.isEmpty()) {
					MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
					MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
					key.setSiteName(siteName);
					key.setReceiveRequestName(receiveRequestName);
					key.setReceiveRequestDetailName(receiveRequestDetailName);
					key.setSubMaterialSpecName(subMaterialSpecName);
					dataInfo.setKey(key);
					dataInfo.setRequestQuantity(Double
							.parseDouble(requestQuantity2));
					dataInfo.setLastEventTimeKey(TimeStampUtil
							.getCurrentEventTimeKey());
					dataInfo.setLastEventName("Create");
					dataInfo.setLastEventTime(TimeStampUtil
							.getCurrentTimestamp());
					dataInfo.setLastEventUser(eventInfo.getEventUser());
					dataInfo.setLastEventComment(eventInfo.getEventComment());
					shipRequestToOEMImpl.insert(dataInfo);
				}// else throw new CustomException("INT-0012",
					// receiveRequestName, receiveRequestDetailName,
					// subMaterialSpecName);
			}// else throw new CustomException("INT-0009", receiveRequestName,
				// receiveRequestDetailName);
				// }

			receiveRequestImpl.createSupplier(supplierNo, description, address,
					city, fax, tel, postCode, nationalNo);
		}

		// Modfiy
		else if (flag.equals("2")) {

			if (queryResult == null || queryResult.isEmpty()) {
				if(passState==null||passState.equals(""))
					passState="Create";
				if(passState.equals("XX"))
					passState="Completed";
				receiveRequestImpl.create(eventInfo, siteName,
						receiveRequestName, purchaseOrderGroup,
						receiveRequestState, supplierNo, "ERP", "", "", "", "",passState);
			}else {
				//if(queryResult.get(0).get("PASSSTATE").toString().equals("Created"))
				//{
					receiveRequestImpl.modify(eventInfo, siteName, receiveRequestName, purchaseOrderGroup, receiveRequestState, supplierNo, "ERP", "", "", "", "");
				//}
					
			}

			if (!receiveRequestDetailType.equals("3")) {
				if (queryResult2 != null && !queryResult2.isEmpty()) {
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(siteName);
					mrdk.setReceiveRequestName(receiveRequestName);
					mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
					mrd.setKey(mrdk);					
					mrd.setPocategory(pocategory);
					mrd.setReceiveRequestDetailType(receiveRequestDetailType);
					mrd.setMaterialSpecName(materialSpecName);
					mrd.setDescription(description2);
					if(!receivedQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					//po订单修改之后，对于已经收到的数量不变;
					if(!receivedQuantity.isEmpty())
						mrd.setReceivedQuantity(Double.valueOf(queryResult2.get(0).get("RECEIVEDQUANTITY").toString()));
					mrd.setErpLocation(erpLocation);
					mrd.setErpFactory(erpFactoryName);
					mrd.setReturnFlag(returnFlag);
					mrd.setFreeFlag(freeFlag);
					mrd.setForceCompletedFlag(forceCompletedFlag);
					mrd.setReceiveRequestDetailState(receiveRequestDetailState);
					mrd.setHoldState(holdState);
					mrd.setIqcFlag(iqcFlag);
					if(!(planDate ==null || planDate.isEmpty() || planDate.equals("0000-00-00")))
					{
						planDate+=" 00:00:00";
						mrd.setPlanDate(Timestamp.valueOf(planDate));
					}
					mrd.setApplicant(applicant);
					mrd.setCharge(charge);
					mrd.setInnerFlag(innerFlag);
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
//					receiveRequestDetailImpl.modify(eventInfo, siteName,
//							receiveRequestName, receiveRequestDetailName,
//							pocategory, receiveRequestDetailType,
//							materialSpecName, description2, requestQuantity,
//							receivedQuantity, erpLocation, returnFlag,
//							freeFlag, forceCompletedFlag,
//							receiveRequestDetailState, holdState, iqcFlag,
//							planDate, applicant, charge);					
				} else // throw new CustomException("INT-0011",
						// receiveRequestName, receiveRequestDetailName);

				{
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(siteName);
					mrdk.setReceiveRequestName(receiveRequestName);
					mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
					mrd.setKey(mrdk);					
					mrd.setPocategory(pocategory);
					mrd.setReceiveRequestDetailType(receiveRequestDetailType);
					mrd.setMaterialSpecName(materialSpecName);
					mrd.setDescription(description2);
					if(!receivedQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					if(!receivedQuantity.isEmpty())
						mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
					mrd.setErpLocation(erpLocation);
					mrd.setErpFactory(erpFactoryName);
					mrd.setReturnFlag(returnFlag);
					mrd.setFreeFlag(freeFlag);
					mrd.setForceCompletedFlag(forceCompletedFlag);
					mrd.setReceiveRequestDetailState(receiveRequestDetailState);
					mrd.setHoldState(holdState);
					mrd.setIqcFlag(iqcFlag);
					if(!(planDate ==null || planDate.isEmpty() || planDate.equals("0000-00-00")))
					{
						planDate+=" 00:00:00";
						mrd.setPlanDate(Timestamp.valueOf(planDate));
					}
					mrd.setApplicant(applicant);
					mrd.setCharge(charge);
					mrd.setInnerFlag(innerFlag);
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
				}				
			}

			if (receiveRequestDetailType.equals("3")) {
				if (queryResult2 == null || queryResult2.isEmpty()) {
//					receiveRequestDetailImpl.create(eventInfo, siteName,
//							receiveRequestName, receiveRequestDetailName,
//							pocategory, receiveRequestDetailType,
//							materialSpecName, description2, requestQuantity,
//							receivedQuantity, erpLocation, returnFlag,
//							freeFlag, forceCompletedFlag,
//							receiveRequestDetailState, holdState, iqcFlag,
//							planDate, applicant, charge, erpFactoryName);
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(siteName);
					mrdk.setReceiveRequestName(receiveRequestName);
					mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
					mrd.setKey(mrdk);					
					mrd.setPocategory(pocategory);
					mrd.setReceiveRequestDetailType(receiveRequestDetailType);
					mrd.setMaterialSpecName(materialSpecName);
					mrd.setDescription(description2);
					if(!receivedQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					if(!receivedQuantity.isEmpty())
						mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
					mrd.setErpLocation(erpLocation);
					mrd.setErpFactory(erpFactoryName);
					mrd.setReturnFlag(returnFlag);
					mrd.setFreeFlag(freeFlag);
					mrd.setForceCompletedFlag(forceCompletedFlag);
					mrd.setReceiveRequestDetailState(receiveRequestDetailState);
					mrd.setHoldState(holdState);
					mrd.setIqcFlag(iqcFlag);
					if(!(planDate ==null || planDate.isEmpty() || planDate.equals("0000-00-00")))
					{
						planDate+=" 00:00:00";
						mrd.setPlanDate(Timestamp.valueOf(planDate));
					}
					mrd.setApplicant(applicant);
					mrd.setCharge(charge);
					mrd.setInnerFlag(innerFlag);
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
				}

				if (queryResult3 != null && !queryResult3.isEmpty()) {
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(siteName);
					mrdk.setReceiveRequestName(receiveRequestName);
					mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
					mrd.setKey(mrdk);					
					mrd.setPocategory(pocategory);
					mrd.setReceiveRequestDetailType(receiveRequestDetailType);
					mrd.setMaterialSpecName(materialSpecName);
					mrd.setDescription(description2);
					if(!receivedQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					if(!receivedQuantity.isEmpty())
						mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
					mrd.setErpLocation(erpLocation);
					mrd.setErpFactory(erpFactoryName);
					mrd.setReturnFlag(returnFlag);
					mrd.setFreeFlag(freeFlag);
					mrd.setForceCompletedFlag(forceCompletedFlag);
					mrd.setReceiveRequestDetailState(receiveRequestDetailState);
					mrd.setHoldState(holdState);
					mrd.setIqcFlag(iqcFlag);
					if(!(planDate ==null || planDate.isEmpty() || planDate.equals("0000-00-00")))
					{
						planDate+=" 00:00:00";
						mrd.setPlanDate(Timestamp.valueOf(planDate));
					}
					mrd.setApplicant(applicant);
					mrd.setCharge(charge);
					mrd.setInnerFlag(innerFlag);
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
					
					MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
					MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
					key.setSiteName(siteName);
					key.setReceiveRequestName(receiveRequestName);
					key.setReceiveRequestDetailName(receiveRequestDetailName);
					key.setSubMaterialSpecName(subMaterialSpecName);
					dataInfo.setKey(key);
					dataInfo.setRequestQuantity(Double
							.parseDouble(requestQuantity2));
					dataInfo.setLastEventTimeKey(TimeStampUtil
							.getCurrentEventTimeKey());
					dataInfo.setLastEventName("Modify");
					dataInfo.setLastEventTime(TimeStampUtil
							.getCurrentTimestamp());
					dataInfo.setLastEventUser(eventInfo.getEventUser());
					dataInfo.setLastEventComment(eventInfo.getEventComment());
					shipRequestToOEMImpl.update(dataInfo);
				} else // throw new CustomException("INT-0006",
						// receiveRequestName, receiveRequestDetailName,
						// subMaterialSpecName);

				{
					MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
					MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
					key.setSiteName(siteName);
					key.setReceiveRequestName(receiveRequestName);
					key.setReceiveRequestDetailName(receiveRequestDetailName);
					key.setSubMaterialSpecName(subMaterialSpecName);
					dataInfo.setKey(key);
					dataInfo.setRequestQuantity(Double
							.parseDouble(requestQuantity2));
					dataInfo.setLastEventTimeKey(TimeStampUtil
							.getCurrentEventTimeKey());
					dataInfo.setLastEventName("Create");
					dataInfo.setLastEventTime(TimeStampUtil
							.getCurrentTimestamp());
					dataInfo.setLastEventUser(eventInfo.getEventUser());
					dataInfo.setLastEventComment(eventInfo.getEventComment());
					shipRequestToOEMImpl.insert(dataInfo);
				}
			}

			receiveRequestImpl.createSupplier(supplierNo, description, address,
					city, fax, tel, postCode, nationalNo);
		}

		// Remove
		else if (flag.equals("3")) {

			if (receiveRequestDetailType.equals("3")) {
				if (queryResult3 == null || queryResult3.isEmpty()) {
					// throw new CustomException("INT-0006", receiveRequestName,
					// receiveRequestDetailName);
				} else {

					if (queryResult3.get(0).get("ASSIGNEDQUANTITY").toString()
							.equals("0")) {
						MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
						key.setSiteName(siteName);
						key.setReceiveRequestName(receiveRequestName);
						key.setReceiveRequestDetailName(receiveRequestDetailName);
						key.setSubMaterialSpecName(subMaterialSpecName);
						shipRequestToOEMImpl.delete(key);
						String sql4 = "SELECT * FROM MATERIALSHIPREQUESTTOOEM "
								+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName";
						Map<String, String> bindMap4 = new HashMap<String, String>();
						bindMap4.put("siteName", siteName);
						bindMap4.put("receiveRequestName", receiveRequestName);
						bindMap4.put("receiveRequestDetailName",
								receiveRequestDetailName);
						List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sql4, bindMap4);
						if (queryResult4 == null || queryResult4.isEmpty()) {

							if (!(queryResult2 == null || queryResult2
									.isEmpty())) {
								receiveRequestDetailImpl.remove(eventInfo,
										siteName, receiveRequestName,
										receiveRequestDetailName); // add by mxh
																	// 20161115;
							}
						}

					} else {
						throw new CustomException("INT-0013",
								receiveRequestName, receiveRequestDetailName);
					}

				}
			} else {
				if (queryResult == null || queryResult.isEmpty()) {
					// throw new CustomException("INT-0010",
					// receiveRequestName);
				}
				if (queryResult2 == null || queryResult2.isEmpty()) {
					// throw new CustomException("INT-0011", receiveRequestName,
					// receiveRequestDetailName);
				} else {
					if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
							.equals("0")) {
						receiveRequestDetailImpl.remove(eventInfo, siteName,
								receiveRequestName, receiveRequestDetailName);
						// GET RECEIVEREQUEST
						String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
								+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";
						Map<String, String> bindMap4 = new HashMap<String, String>();
						bindMap4.put("siteName", siteName);
						bindMap4.put("receiveRequestName", receiveRequestName);
						List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sql4, bindMap4);
						if (queryResult4 == null || queryResult4.isEmpty()) {
							receiveRequestImpl.remove(eventInfo, siteName,
									receiveRequestName);
						}

					} else {
						throw new CustomException("INT-0014",
								receiveRequestName, receiveRequestDetailName);
					}
				}

			}
		}
		/*
		 * else{ throw new CustomException("INT-0008", flag); }
		 */
	}
	
	/** 
	 * 由ERPInterfaceServiceUtil INT_WMS09更改
	 * 2024.09.26
	 */
    public void INT_14074(String flag, EventInfo eventInfo,
            String erpFactoryName, String receiveRequestName,
            String receiveRequestDetailName, String purchaseOrderGroup,
            String receiveRequestState, String pocategory,
            String receiveRequestDetailType, String materialSpecName,
            String description2, String requestQuantity,
            String receivedQuantity, String erpLocation, String returnFlag,
            String freeFlag, String forceCompletedFlag,
            String receiveRequestDetailState, String holdState, String iqcFlag,
            String planDate, String applicant, String charge,
            String supplierNo, String address, String city, String fax,
            String tel, String postCode, String nationalNo, String description,
            String subMaterialSpecName, String requestQuantity2, String innerFlag, String passState, String innerOrder,
            String inCo1, String usTime, String bednr, String banfn, String orgName, String orgParentName, String ematn,
            String bwtar, String ps_Posid, String charg2, String bedat, String eindt, String kostl, String receiveRequestType, String erpFactory)
            throws CustomException, ParseException {
        MaterialReceiveRequestServiceImpl receiveRequestImpl = new MaterialReceiveRequestServiceImpl();
        MaterialReceiveRequestDetailServiceImpl receiveRequestDetailImpl = new MaterialReceiveRequestDetailServiceImpl();
        MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();
        String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
                .getSiteName(erpFactoryName);
        // B11区分F1材料和其余材料
        if (siteName.equals("B11")) {
            List<String> templist = new ArrayList<String>();
            String tempErpFactory = "";
            if (erpFactoryName.equals("2800")) {

                String[] array = { "107B", "107N", "110B", "110N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2811";
            } else if (erpFactoryName.equals("2809")) {

                String[] array = { "906B", "906N", "922B", "922N" };
                templist = Arrays.asList(array);
                tempErpFactory = "2812";
            }

            if (templist.contains(erpLocation)) {
                siteName = "BBF1";
                erpFactoryName = tempErpFactory;
            }
        }
        // GET RECEIVEREQUEST
        String sql = "SELECT * FROM MATERIALRECEIVEREQUEST "
                + "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";

        Map<String, String> bindMap = new HashMap<String, String>();
        bindMap.put("siteName", siteName);
        bindMap.put("receiveRequestName", receiveRequestName);

        List<Map<String, Object>> queryResult = IDMFrameServiceProxy
                .getSqlTemplate().queryForList(sql, bindMap);

        // GET RECEIVEREQUESTDETAIL
        String sql2 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
                + "WHERE SITENAME = :siteName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName and RECEIVEREQUESTNAME = :receiveRequestName";

        Map<String, String> bindMap2 = new HashMap<String, String>();
        bindMap2.put("siteName", siteName);
        bindMap2.put("receiveRequestDetailName", receiveRequestDetailName);
        bindMap2.put("receiveRequestName", receiveRequestName);

        List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql2, bindMap2);

        // GET OEM
        String sql3 = "SELECT * FROM MATERIALSHIPREQUESTTOOEM "
                + "WHERE SITENAME = :siteName  and RECEIVEREQUESTNAME = :receiveRequestName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName"
                + " and SUBMATERIALSPECNAME = :subMaterialSpecName";

        Map<String, String> bindMap3 = new HashMap<String, String>();
        bindMap3.put("siteName", siteName);
        bindMap3.put("receiveRequestName", receiveRequestName);
        bindMap3.put("receiveRequestDetailName", receiveRequestDetailName);
        bindMap3.put("subMaterialSpecName", subMaterialSpecName);

        List<Map<String, Object>> queryResult3 = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(sql3, bindMap3);

        // Create
        if (flag.equals("1")) {
            if (queryResult == null || queryResult.isEmpty()) {

                if (passState == null || passState.equals(""))
                    passState = "Created";
                if (passState.equals("XX"))
                    passState = "Completed";
                receiveRequestImpl.create(eventInfo, siteName,
                        receiveRequestName, purchaseOrderGroup,
                        receiveRequestState, supplierNo, "ERP", "", "", "", "", passState, bedat, receiveRequestType);
            } else {
                // if((queryResult.get(0).get("PASSSTATE")==null?"":queryResult.get(0).get("PASSSTATE").toString()).equals("Created"))
                // {
                receiveRequestImpl.modify(eventInfo, siteName, receiveRequestName, purchaseOrderGroup,
                        receiveRequestState, supplierNo, "ERP", "", "", "", "", bedat);
            }
            
            
            // Updateed By WH 2017/1/10 materialreceiverequestdetail表添加innerflag字段 原API不满足需求
            if (queryResult2 == null || queryResult2.isEmpty()) {
                // receiveRequestDetailImpl.create(eventInfo, siteName,
                // receiveRequestName, receiveRequestDetailName,
                // pocategory, receiveRequestDetailType, materialSpecName,
                // description2, requestQuantity, receivedQuantity,
                // erpLocation, returnFlag, freeFlag, forceCompletedFlag,
                // receiveRequestDetailState, holdState, iqcFlag,
                // planDate, applicant, charge, erpFactoryName);
                MaterialReceiveRequestDetail mrd = new MaterialReceiveRequestDetail();
                MaterialReceiveRequestDetailKey mrdk = new MaterialReceiveRequestDetailKey();
                mrdk.setSiteName(siteName);
                mrdk.setReceiveRequestName(receiveRequestName);
                mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
                mrd.setKey(mrdk);
                mrd.setPocategory(pocategory);
                mrd.setReceiveRequestDetailType(receiveRequestDetailType);
                mrd.setMaterialSpecName(materialSpecName);
                mrd.setDescription(description2);
                if (!receivedQuantity.isEmpty())
                    mrd.setRequestQuantity(Double.valueOf(requestQuantity));
                if (!receivedQuantity.isEmpty())
                    mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
                mrd.setErpLocation(erpLocation);
                mrd.setErpFactory(erpFactoryName);
                mrd.setReturnFlag(returnFlag);
                mrd.setFreeFlag(freeFlag);
                mrd.setForceCompletedFlag(forceCompletedFlag);
                mrd.setReceiveRequestDetailState(receiveRequestDetailState);
                mrd.setHoldState(holdState);
                mrd.setIqcFlag(iqcFlag);
                if (!(planDate == null || planDate.isEmpty() || planDate.equals("0000-00-00"))) {
                    planDate += " 00:00:00";
                    mrd.setPlanDate(Timestamp.valueOf(planDate));
                }
                mrd.setApplicant(applicant);
                mrd.setCharge(charge);
                mrd.setInnerFlag(innerFlag);
                mrd.setInnerOrder(innerOrder);// 内部订单号，EN确认生产计划
                ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
            }
            // else{
            if (receiveRequestDetailType.equals("3")) {
                if (queryResult3 == null || queryResult3.isEmpty()) {
                    MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
                    MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
                    key.setSiteName(siteName);
                    key.setReceiveRequestName(receiveRequestName);
                    key.setReceiveRequestDetailName(receiveRequestDetailName);
                    key.setSubMaterialSpecName(subMaterialSpecName);
                    dataInfo.setKey(key);
                    dataInfo.setRequestQuantity(Double
                            .parseDouble(requestQuantity2));
                    dataInfo.setLastEventTimeKey(TimeStampUtil
                            .getCurrentEventTimeKey());
                    dataInfo.setLastEventName("Create");
                    dataInfo.setLastEventTime(TimeStampUtil
                            .getCurrentTimestamp());
                    dataInfo.setLastEventUser(eventInfo.getEventUser());
                    dataInfo.setLastEventComment(eventInfo.getEventComment());
                    shipRequestToOEMImpl.insert(dataInfo);
                } // else throw new CustomException("INT-0012",
                  // receiveRequestName, receiveRequestDetailName,
                  // subMaterialSpecName);
            } // else throw new CustomException("INT-0009", receiveRequestName,
              // receiveRequestDetailName);
              // }

            receiveRequestImpl.createSupplier(supplierNo, description, address,
                    city, fax, tel, postCode, nationalNo);
        }

        // Modfiy
        else if (flag.equals("2")) {

            if (queryResult == null || queryResult.isEmpty()) {
                if (passState == null || passState.equals(""))
                    passState = "Create";
                if (passState.equals("XX"))
                    passState = "Completed";
                receiveRequestImpl.create(eventInfo, siteName,
                        receiveRequestName, purchaseOrderGroup,
                        receiveRequestState, supplierNo, "ERP", "", "", "", "", passState, bedat, receiveRequestType);
            } else {
                // if(queryResult.get(0).get("PASSSTATE").toString().equals("Created"))
                // {
                receiveRequestImpl.modify(eventInfo, siteName, receiveRequestName, purchaseOrderGroup,
                        receiveRequestState, supplierNo, "ERP", "", "", "", "", bedat);
                // }

            }

            if (!receiveRequestDetailType.equals("3")) {
                if (queryResult2 != null && !queryResult2.isEmpty()) {
                    MaterialReceiveRequestDetail mrd = new MaterialReceiveRequestDetail();
                    MaterialReceiveRequestDetailKey mrdk = new MaterialReceiveRequestDetailKey();
                    mrdk.setSiteName(siteName);
                    mrdk.setReceiveRequestName(receiveRequestName);
                    mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
                    mrd.setKey(mrdk);
                    mrd.setPocategory(pocategory);
                    mrd.setReceiveRequestDetailType(receiveRequestDetailType);
                    mrd.setMaterialSpecName(materialSpecName);
                    mrd.setDescription(description2);
                    if (!receivedQuantity.isEmpty())
                        mrd.setRequestQuantity(Double.valueOf(requestQuantity));
                    // po订单修改之后，对于已经收到的数量不变;
                    if (!receivedQuantity.isEmpty())
                        mrd.setReceivedQuantity(Double.valueOf(queryResult2.get(0).get("RECEIVEDQUANTITY").toString()));
                    mrd.setErpLocation(erpLocation);
                    mrd.setErpFactory(erpFactoryName);
                    mrd.setReturnFlag(returnFlag);
                    mrd.setFreeFlag(freeFlag);
                    mrd.setForceCompletedFlag(forceCompletedFlag);
                    mrd.setReceiveRequestDetailState(receiveRequestDetailState);
                    mrd.setHoldState(holdState);
                    mrd.setIqcFlag(iqcFlag);
                    if (!(planDate == null || planDate.isEmpty() || planDate.equals("0000-00-00"))) {
                        planDate += " 00:00:00";
                        mrd.setPlanDate(Timestamp.valueOf(planDate));
                    }
                    mrd.setApplicant(applicant);
                    mrd.setCharge(charge);
                    mrd.setInnerFlag(innerFlag);//
                    ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
                    // receiveRequestDetailImpl.modify(eventInfo, siteName,
                    // receiveRequestName, receiveRequestDetailName,
                    // pocategory, receiveRequestDetailType,
                    // materialSpecName, description2, requestQuantity,
                    // receivedQuantity, erpLocation, returnFlag,
                    // freeFlag, forceCompletedFlag,
                    // receiveRequestDetailState, holdState, iqcFlag,
                    // planDate, applicant, charge);
                } else // throw new CustomException("INT-0011",
                       // receiveRequestName, receiveRequestDetailName);

                {
                    MaterialReceiveRequestDetail mrd = new MaterialReceiveRequestDetail();
                    MaterialReceiveRequestDetailKey mrdk = new MaterialReceiveRequestDetailKey();
                    mrdk.setSiteName(siteName);
                    mrdk.setReceiveRequestName(receiveRequestName);
                    mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
                    mrd.setKey(mrdk);
                    mrd.setPocategory(pocategory);
                    mrd.setReceiveRequestDetailType(receiveRequestDetailType);
                    mrd.setMaterialSpecName(materialSpecName);
                    mrd.setDescription(description2);
                    if (!receivedQuantity.isEmpty())
                        mrd.setRequestQuantity(Double.valueOf(requestQuantity));
                    if (!receivedQuantity.isEmpty())
                        mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
                    mrd.setErpLocation(erpLocation);
                    mrd.setErpFactory(erpFactoryName);
                    mrd.setReturnFlag(returnFlag);
                    mrd.setFreeFlag(freeFlag);
                    mrd.setForceCompletedFlag(forceCompletedFlag);
                    mrd.setReceiveRequestDetailState(receiveRequestDetailState);
                    mrd.setHoldState(holdState);
                    mrd.setIqcFlag(iqcFlag);
                    if (!(planDate == null || planDate.isEmpty() || planDate.equals("0000-00-00"))) {
                        planDate += " 00:00:00";
                        mrd.setPlanDate(Timestamp.valueOf(planDate));
                    }
                    mrd.setApplicant(applicant);
                    mrd.setCharge(charge);
                    mrd.setInnerFlag(innerFlag);
                    ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
                }
            }

            if (receiveRequestDetailType.equals("3")) {
                if (queryResult2 == null || queryResult2.isEmpty()) {
                    // receiveRequestDetailImpl.create(eventInfo, siteName,
                    // receiveRequestName, receiveRequestDetailName,
                    // pocategory, receiveRequestDetailType,
                    // materialSpecName, description2, requestQuantity,
                    // receivedQuantity, erpLocation, returnFlag,
                    // freeFlag, forceCompletedFlag,
                    // receiveRequestDetailState, holdState, iqcFlag,
                    // planDate, applicant, charge, erpFactoryName);
                    MaterialReceiveRequestDetail mrd = new MaterialReceiveRequestDetail();
                    MaterialReceiveRequestDetailKey mrdk = new MaterialReceiveRequestDetailKey();
                    mrdk.setSiteName(siteName);
                    mrdk.setReceiveRequestName(receiveRequestName);
                    mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
                    mrd.setKey(mrdk);
                    mrd.setPocategory(pocategory);
                    mrd.setReceiveRequestDetailType(receiveRequestDetailType);
                    mrd.setMaterialSpecName(materialSpecName);
                    mrd.setDescription(description2);
                    if (!receivedQuantity.isEmpty())
                        mrd.setRequestQuantity(Double.valueOf(requestQuantity));
                    if (!receivedQuantity.isEmpty())
                        mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
                    mrd.setErpLocation(erpLocation);
                    mrd.setErpFactory(erpFactoryName);
                    mrd.setReturnFlag(returnFlag);
                    mrd.setFreeFlag(freeFlag);
                    mrd.setForceCompletedFlag(forceCompletedFlag);
                    mrd.setReceiveRequestDetailState(receiveRequestDetailState);
                    mrd.setHoldState(holdState);
                    mrd.setIqcFlag(iqcFlag);
				    if (!(planDate == null || planDate.isEmpty() || planDate.equals("0000-00-00"))) {
                        planDate += " 00:00:00";
                        mrd.setPlanDate(Timestamp.valueOf(planDate));
                    }
                    mrd.setApplicant(applicant);
                    mrd.setCharge(charge);
                    mrd.setInnerFlag(innerFlag);
                    ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
                }

                if (queryResult3 != null && !queryResult3.isEmpty()) {
                    MaterialReceiveRequestDetail mrd = new MaterialReceiveRequestDetail();
                    MaterialReceiveRequestDetailKey mrdk = new MaterialReceiveRequestDetailKey();
                    mrdk.setSiteName(siteName);
                    mrdk.setReceiveRequestName(receiveRequestName);
                    mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
                    mrd.setKey(mrdk);
                    mrd.setPocategory(pocategory);
                    mrd.setReceiveRequestDetailType(receiveRequestDetailType);
                    mrd.setMaterialSpecName(materialSpecName);
                    mrd.setDescription(description2);
                    if (!receivedQuantity.isEmpty())
                        mrd.setRequestQuantity(Double.valueOf(requestQuantity));
                    if (!receivedQuantity.isEmpty())
                        mrd.setReceivedQuantity(Double.valueOf(receivedQuantity));
                    mrd.setErpLocation(erpLocation);
                    mrd.setErpFactory(erpFactoryName);
                    mrd.setReturnFlag(returnFlag);
                    mrd.setFreeFlag(freeFlag);
                    mrd.setForceCompletedFlag(forceCompletedFlag);
                    mrd.setReceiveRequestDetailState(receiveRequestDetailState);
                    mrd.setHoldState(holdState);
                    mrd.setIqcFlag(iqcFlag);
                    if (!(planDate == null || planDate.isEmpty() || planDate.equals("0000-00-00"))) {
                        planDate += " 00:00:00";
                        mrd.setPlanDate(Timestamp.valueOf(planDate));
                    }
                    mrd.setApplicant(applicant);
                    mrd.setCharge(charge);
                    mrd.setInnerFlag(innerFlag);
                    ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);

                    MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
                    MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
                    key.setSiteName(siteName);
                    key.setReceiveRequestName(receiveRequestName);
                    key.setReceiveRequestDetailName(receiveRequestDetailName);
                    key.setSubMaterialSpecName(subMaterialSpecName);
                    dataInfo.setKey(key);
                    dataInfo.setRequestQuantity(Double
                            .parseDouble(requestQuantity2));
                    dataInfo.setLastEventTimeKey(TimeStampUtil
                            .getCurrentEventTimeKey());
                    dataInfo.setLastEventName("Modify");
                    dataInfo.setLastEventTime(TimeStampUtil
                            .getCurrentTimestamp());
                    dataInfo.setLastEventUser(eventInfo.getEventUser());
                    dataInfo.setLastEventComment(eventInfo.getEventComment());
                    shipRequestToOEMImpl.update(dataInfo);
                } else // throw new CustomException("INT-0006",
                       // receiveRequestName, receiveRequestDetailName,
                       // subMaterialSpecName);

                {
                    MaterialShipRequestToOEM dataInfo = new MaterialShipRequestToOEM();
                    MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
                    key.setSiteName(siteName);
                    key.setReceiveRequestName(receiveRequestName);
                    key.setReceiveRequestDetailName(receiveRequestDetailName);
                    key.setSubMaterialSpecName(subMaterialSpecName);
                    dataInfo.setKey(key);
                    dataInfo.setRequestQuantity(Double
                            .parseDouble(requestQuantity2));
                    dataInfo.setLastEventTimeKey(TimeStampUtil
                            .getCurrentEventTimeKey());
                    dataInfo.setLastEventName("Create");
                    dataInfo.setLastEventTime(TimeStampUtil
                            .getCurrentTimestamp());
                    dataInfo.setLastEventUser(eventInfo.getEventUser());
                    dataInfo.setLastEventComment(eventInfo.getEventComment());
                    shipRequestToOEMImpl.insert(dataInfo);
                }
            }

            receiveRequestImpl.createSupplier(supplierNo, description, address,
                    city, fax, tel, postCode, nationalNo);
        }

        // Remove
        else if (flag.equals("3")) {

            if (receiveRequestDetailType.equals("3")) {
                if (queryResult3 == null || queryResult3.isEmpty()) {
                    // throw new CustomException("INT-0006", receiveRequestName,
                    // receiveRequestDetailName);
                } else {

                    if (queryResult3.get(0).get("ASSIGNEDQUANTITY").toString()
                            .equals("0")) {
                        MaterialShipRequestToOEMKey key = new MaterialShipRequestToOEMKey();
                        key.setSiteName(siteName);
                        key.setReceiveRequestName(receiveRequestName);
                        key.setReceiveRequestDetailName(receiveRequestDetailName);
                        key.setSubMaterialSpecName(subMaterialSpecName);
                        shipRequestToOEMImpl.delete(key);
                        String sql4 = "SELECT * FROM MATERIALSHIPREQUESTTOOEM "
                                + "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName";
                        Map<String, String> bindMap4 = new HashMap<String, String>();
                        bindMap4.put("siteName", siteName);
                        bindMap4.put("receiveRequestName", receiveRequestName);
                        bindMap4.put("receiveRequestDetailName",
                                receiveRequestDetailName);
                        List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
                                .getSqlTemplate()
                                .queryForList(sql4, bindMap4);
                        if (queryResult4 == null || queryResult4.isEmpty()) {

                            if (!(queryResult2 == null || queryResult2
                                    .isEmpty())) {
                                receiveRequestDetailImpl.remove(eventInfo,
                                        siteName, receiveRequestName,
                                        receiveRequestDetailName); // add by mxh
                                                                   // 20161115;
                            }
                        }

                    } else {
                        throw new CustomException("INT-0013",
                                receiveRequestName, receiveRequestDetailName);
                    }

                }
            } else {
                if (queryResult == null || queryResult.isEmpty()) {
                    // throw new CustomException("INT-0010",
                    // receiveRequestName);
                }
                if (queryResult2 == null || queryResult2.isEmpty()) {
                    // throw new CustomException("INT-0011", receiveRequestName,
                    // receiveRequestDetailName);
                } else {
                    if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
                            .equals("0")) {
                        receiveRequestDetailImpl.remove(eventInfo, siteName,
                                receiveRequestName, receiveRequestDetailName);
                        // GET RECEIVEREQUEST
                        String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
                                + "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";
                        Map<String, String> bindMap4 = new HashMap<String, String>();
                        bindMap4.put("siteName", siteName);
                        bindMap4.put("receiveRequestName", receiveRequestName);
                        List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
                                .getSqlTemplate()
                                .queryForList(sql4, bindMap4);
                        if (queryResult4 == null || queryResult4.isEmpty()) {
                            receiveRequestImpl.remove(eventInfo, siteName,
                                    receiveRequestName);
                        }

                    } else {
                        throw new CustomException("INT-0014",
                                receiveRequestName, receiveRequestDetailName);
                    }
                }

            }
        }
    }

	
	public List<MaterialPackingStockInfo> createMaterialPackingList() throws Exception
	{
		try{
			List<MaterialPackingStockInfo> mpList=new ArrayList<MaterialPackingStockInfo>();
			return mpList;
		}catch(Exception e)
		{
			log.error(e.getMessage());
			throw e;
		}
		
	}
	
	
//	public List<MaterialPackingStockInfo> queryStockState(String erpFactory,String materialSpecName,String erpLocation,String charge,List<MaterialPackingStockInfo> mpList) throws Exception
//	{		
//		if(erpFactory!="" &&materialSpecName!="")
//		{
//			try
//			{
//				String querySql="SELECT M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE, "
//					+"SUM(CASE WHEN (PACKINGGRADE='OK' AND (OQARESULTSTATE IS NULL OR OQARESULTSTATE<>'PREOQA') ) THEN MATERIALQUANTITY ELSE NULL END) OKQUANTITY, "
//					+"SUM(CASE WHEN PACKINGGRADE='NG' THEN MATERIALQUANTITY ELSE NULL END) NGQUANTITY, "
//					+"SUM(CASE WHEN OQARESULTSTATE='PREOQA' THEN MATERIALQUANTITY ELSE NULL END ) PREOQAQUANTITY FROM MATERIALPACKING M "
//					+"WHERE M.ERPFACTORY=:ERPFACTORY "
//					+"AND M.MATERIALSPECNAME=:MATERIALSPECNAME "
//					+"AND (:CHARGE IS NULL OR M.CHARGE=:CHARGE) "
//					+"AND (:ERPLOCATION IS NULL OR M.ERPLOCATION=:ERPLOCATION) "
//					+"AND M.STOCKSTATE='Stocked' "	
//					+"AND M.MATERIALPACKINGTYPE='Box' "
//					+"GROUP BY M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE "
//					+ " union "
//					+ " SELECT M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE, "
//					+ " SUM(CASE WHEN OQARESULT='OK' THEN MATERIALQUANTITY ELSE NULL END ) OKQUANTITY, "
//					+ " SUM(CASE WHEN OQARESULT='NG' THEN MATERIALQUANTITY ELSE NULL END) NGQUANTITY, "
//					+ " SUM(CASE WHEN OQARESULTSTATE='PREOQA' THEN MATERIALQUANTITY ELSE NULL END ) PREOQAQUANTITY FROM MATERIALPACKINGSMT M "
//					+ " WHERE M.ERPFACTORY=:ERPFACTORY "
//					+ " AND M.MATERIALSPECNAME=:MATERIALSPECNAME "
//					+ " AND (:CHARGE IS NULL OR M.CHARGE=:CHARGE) "
//					+ " AND (:ERPLOCATION IS NULL OR M.ERPLOCATION=:ERPLOCATION) "
//					+ " AND M.STOCKSTATE='Stocked' 	"
//					+ " GROUP BY M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE ";
//				Map<String,Object> map=new HashMap<String, Object>();
//				map.put("MATERIALSPECNAME", materialSpecName);
//				map.put("ERPFACTORY", erpFactory);
//				map.put("CHARGE", charge);
//				map.put("ERPLOCATION", erpLocation);
//				List<Map<String, Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, map);
//				if(result!=null &&result.size()>0)
//				{
//					for(int i=0;i<result.size();i++)
//					{
//						MaterialPackingStockInfo mp=new MaterialPackingStockInfo();
//						mp.setMaterialSpecName(result.get(i).get("MATERIALSPECNAME").toString());
//						mp.setErpFactory(result.get(i).get("ERPFACTORY").toString());
//						mp.setErpLocation(result.get(i).get("ERPLOCATION")!=null?result.get(i).get("ERPLOCATION").toString():"");
//						mp.setCharge(result.get(i).get("CHARGE")!=null?result.get(i).get("CHARGE").toString():"");
//						mp.setOkQuantity(result.get(i).get("OKQUANTITY")!=null?result.get(i).get("OKQUANTITY").toString():"");
//						mp.setNgQuantity(result.get(i).get("NGQUANTITY")!=null?result.get(i).get("NGQUANTITY").toString():"");
//						mp.setPreOqaQuantity(result.get(i).get("PREOQAQUANTITY")!=null?result.get(i).get("PREOQAQUANTITY").toString():"");
//						mpList.add(mp);
//					}
//				}
//				return mpList;		
//			}catch(Exception e)
//			{
//			  log.error(e.getMessage());
//			  throw e;
//			}
//		}
//		else
//				throw new CustomException("E","物料号和ERP工厂不能为空！");
//	}	
	// （由ERPInterfaceServiceUtil queryStockState更改）
	public List<MaterialPackingStockInfo> queryStockState(String erpFactory, String materialSpecName,
            String erpLocation, String charge, List<MaterialPackingStockInfo> mpList) throws Exception {
        if (erpFactory != "" && materialSpecName != "") {
            try {

            	String querySql = "SELECT ERPFACTORY,MATERIALSPECNAME,ERPLOCATION,CHARGE,SPECIALFLAG,SUPPLIERNAME,SUM(OKQUANTITY) OKQUANTITY,SUM(NGQUANTITY) NGQUANTITY,SUM(PREOQAQUANTITY) PREOQAQUANTITY,POSID FROM( "
                        + "SELECT M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE, "
                        + "CASE WHEN M.SPECIALFLAG = 'K' AND M.POSID IS NULL THEN M.SPECIALFLAG ELSE ''END SPECIALFLAG , "
                        + "CASE WHEN M.SPECIALFLAG = 'K' THEN M.SUPPLIERNAME ELSE '' END SUPPLIERNAME, "
                        + "SUM(CASE WHEN (PACKINGGRADE='OK' AND (OQARESULTSTATE IS NULL OR OQARESULTSTATE<>'PREOQA') ) THEN MATERIALQUANTITY ELSE NULL END) OKQUANTITY, "
                        + "SUM(CASE WHEN PACKINGGRADE='NG' THEN MATERIALQUANTITY ELSE NULL END) NGQUANTITY, "
                        + "SUM(CASE WHEN OQARESULTSTATE='PREOQA' THEN MATERIALQUANTITY ELSE NULL END ) PREOQAQUANTITY,M.POSID FROM MATERIALPACKING M "
                        + "WHERE M.ERPFACTORY=:ERPFACTORY "
                        + "AND M.MATERIALSPECNAME=:MATERIALSPECNAME "
                        + "AND (:CHARGE IS NULL OR M.CHARGE=:CHARGE) "
                        + "AND (:ERPLOCATION IS NULL OR M.ERPLOCATION=:ERPLOCATION) "
                        + "AND M.STOCKSTATE='Stocked' "
                        + "AND M.MATERIALPACKINGTYPE='Box' "
                        + "GROUP BY M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE,M.SPECIALFLAG,M.SUPPLIERNAME,M.POSID "
                        + ") GROUP BY ERPFACTORY,MATERIALSPECNAME,ERPLOCATION,CHARGE,SPECIALFLAG,SUPPLIERNAME,POSID"
                        + " union "
                        + " SELECT M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE,'' SPECIALFLAG,'' SUPPLIERNAME, "
                        + " SUM(CASE WHEN OQARESULT='OK' THEN MATERIALQUANTITY ELSE NULL END ) OKQUANTITY, "
                        + " SUM(CASE WHEN OQARESULT='NG' THEN MATERIALQUANTITY ELSE NULL END) NGQUANTITY, "
                        + " SUM(CASE WHEN OQARESULTSTATE='PREOQA' THEN MATERIALQUANTITY ELSE NULL END ) PREOQAQUANTITY,'' AS POSID FROM MATERIALPACKINGSMT M "
                        + " WHERE M.ERPFACTORY=:ERPFACTORY "
                        + " AND M.MATERIALSPECNAME=:MATERIALSPECNAME "
                        + " AND (:CHARGE IS NULL OR M.CHARGE=:CHARGE) "
                        + " AND (:ERPLOCATION IS NULL OR M.ERPLOCATION=:ERPLOCATION) "
                        + " AND M.STOCKSTATE='Stocked' 	"
                        + " GROUP BY M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE";
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("MATERIALSPECNAME", materialSpecName);
                map.put("ERPFACTORY", erpFactory);
                map.put("CHARGE", charge);
                map.put("ERPLOCATION", erpLocation);
                // TODO 此处报错
                List<Map<String, Object>> result = IDMFrameServiceProxy.getSqlTemplate()
                        .queryForList(querySql, map);
                if (result != null && result.size() > 0) {
                    for (int i = 0; i < result.size(); i++) {
                        MaterialPackingStockInfo mp = new MaterialPackingStockInfo();
                        mp.setMaterialSpecName(result.get(i).get("MATERIALSPECNAME").toString());
                        mp.setErpFactory(result.get(i).get("ERPFACTORY").toString());
                        mp.setErpLocation(
                                result.get(i).get("ERPLOCATION") != null ? result.get(i).get("ERPLOCATION").toString()
                                        : "");
                        mp.setCharge(result.get(i).get("CHARGE") != null ? result.get(i).get("CHARGE").toString() : "");
                        mp.setOkQuantity(
                                result.get(i).get("OKQUANTITY") != null ? result.get(i).get("OKQUANTITY").toString()
                                        : "");
                        mp.setNgQuantity(
                                result.get(i).get("NGQUANTITY") != null ? result.get(i).get("NGQUANTITY").toString()
                                        : "");
                        mp.setPreOqaQuantity(result.get(i).get("PREOQAQUANTITY") != null
                                ? result.get(i).get("PREOQAQUANTITY").toString()
                                : "");
                        mp.setSpecialFlag(
                                result.get(i).get("SPECIALFLAG") != null ? result.get(i).get("SPECIALFLAG").toString()
                                        : "");
                        mp.setSupplierName(
                                result.get(i).get("SUPPLIERNAME") != null ? result.get(i).get("SUPPLIERNAME").toString()
                                        : "");
                        mp.setPosID(result.get(i).get("POSID") != null ? result.get(i).get("POSID").toString() : "");
                        mpList.add(mp);
                    }
                }
                return mpList;
            } catch (Exception e) {
                log.error(e.getMessage());
                throw e;
            }
        } else
            throw new CustomException("E", "物料号和ERP工厂不能为空！");
    }
	
	
	/**
	 * 内向交货单
	 */
	public void INT_PI045(String innerRequestName,
			String innerRequestDetailName, String receiveRequestName,
			String receiveRequestDetailName, String deliveryType,
			String erpTime, String deliveryTime, String supplierNO,
			String erpFactory, String materialSpecName, String unit,
			String charge, String materialQuantity, String erpLocation,
			String flag, String seq, String receivedQuantity)
			throws CustomException {
		String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
				.getSiteName(erpFactory);

		// InnerRequest innerRequest = new InnerRequest();
		// InnerRequestDetail innerRequestDetail = new InnerRequestDetail();
		String queryRequest = "SELECT * FROM INNERREQUEST WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
		Map<String, String> innerMap = new HashMap<String, String>();
		innerMap.put("SITENAME", siteName);
		innerMap.put("INNERREQUESTNAME", innerRequestName);
		List<Map<String, Object>> innerList = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(queryRequest, innerMap);

		String queryDetail = "SELECT * FROM INNERREQUESTDETAIL WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
		Map<String, String> detailMap = new HashMap<String, String>();
		detailMap.put("SITENAME", siteName);
		detailMap.put("INNERREQUESTNAME", innerRequestName);
		detailMap.put("INNERREQUESTDETAILNAME", innerRequestDetailName);
		List<Map<String, Object>> detailList = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(queryDetail, detailMap);
		// flag等于1，执行插入操作
		if (flag.equals("1")) {
			// 数据库中不存在当前内向交货单号
			if (innerList == null || innerList.isEmpty()) {
				Map<String, String> innerRequest = new HashMap<String, String>();
				innerRequest.put("SITENAME", siteName);
				innerRequest.put("INNERREQUESTNAME", innerRequestName);
				innerRequest.put("DELIVERYTYPE", deliveryType);
				if (deliveryTime != null) {
					innerRequest.put("DELIVERYTIME", deliveryTime);
				}
				if (erpTime != null) {
					innerRequest.put("ERPTIME", erpTime);
				}
				innerRequest.put("SUPPLIERNO", supplierNO);
				innerRequest.put("LASTEVENTNAME", "Create");
				innerRequest.put("LASTEVENTTIMEKEY",
						TimeStampUtil.getCurrentEventTimeKey());
				innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
						"yyyy-MM-dd").format(new Date()));
				innerRequest.put("LASTEVENTUSER", "ERP");
				innerRequest.put("LASTEVENTCOMMENT", "Create");
				String insertInner = "INSERT INTO  INNERREQUEST(SITENAME,INNERREQUESTNAME,DELIVERYTYPE,ERPTIME,DELIVERYTIME,SUPPLIERNO,LASTEVENTNAME,LASTEVENTTIMEKEY,LASTEVENTTIME,LASTEVENTUSER,LASTEVENTCOMMENT) "
						+ "VALUES(:SITENAME,:INNERREQUESTNAME,:DELIVERYTYPE,TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),:SUPPLIERNO,:LASTEVENTNAME,:LASTEVENTTIMEKEY,TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),:LASTEVENTUSER,:LASTEVENTCOMMENT)";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertInner, innerRequest);

			}
			// 数据库中不存在当前内向交货单行项目号
			if (detailList == null || detailList.isEmpty()) {
				Map<String, String> innerDetail = new HashMap<String, String>();
				innerDetail.put("SITENAME", siteName);
				innerDetail.put("INNERREQUESTNAME", innerRequestName);
				innerDetail.put("INNERREQUESTDETAILNAME",
						innerRequestDetailName);
				innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
				innerDetail.put("RECEIVEREQUESTDETAILNAME",
						receiveRequestDetailName);
				innerDetail.put("MATERIALSPECNAME", materialSpecName);
				innerDetail.put("CHARGE", charge);
				innerDetail.put("MATERIALQUANTITY", materialQuantity);
				innerDetail.put("RECEIVEDQUANTITY", receivedQuantity);
				innerDetail.put("UNIT", unit);
				innerDetail.put("ERPLOCATION", erpLocation);
				innerDetail.put("ERPFACTORY", erpFactory);
				String insertDetail = "INSERT INTO  INNERREQUESTDETAIL(SITENAME,INNERREQUESTNAME,INNERREQUESTDETAILNAME,RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME,CHARGE,MATERIALQUANTITY,UNIT,ERPLOCATION,ERPFACTORY,RECEIVEDQUANTITY) "
						+ "VALUES(:SITENAME,:INNERREQUESTNAME,:INNERREQUESTDETAILNAME,:RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:MATERIALSPECNAME,:CHARGE,:MATERIALQUANTITY,:UNIT,:ERPLOCATION,:ERPFACTORY,:RECEIVEDQUANTITY)";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertDetail, innerDetail);
			}
		}
		// flag等于2，执行修改操作
		else if (flag.equals("2")) {
			// 数据库中不存在当前内向交货单号
			if (innerList == null || innerList.isEmpty()) {
				Map<String, String> innerRequest = new HashMap<String, String>();
				innerRequest.put("SITENAME", siteName);
				innerRequest.put("INNERREQUESTNAME", innerRequestName);
				innerRequest.put("DELIVERYTYPE", deliveryType);
				if (deliveryTime != null) {
					innerRequest.put("DELIVERYTIME", deliveryTime);
				}
				if (erpTime != null) {
					innerRequest.put("ERPTIME", erpTime);
				}
				innerRequest.put("SUPPLIERNO", supplierNO);
				innerRequest.put("LASTEVENTNAME", "Create");
				innerRequest.put("LASTEVENTTIMEKEY",
						TimeStampUtil.getCurrentEventTimeKey());
				innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
						"yyyy-MM-dd").format(new Date()));
				innerRequest.put("LASTEVENTUSER", "ERP");
				innerRequest.put("LASTEVENTCOMMENT", "Create");
				String insertInner = "INSERT INTO  INNERREQUEST(SITENAME,INNERREQUESTNAME,DELIVERYTYPE,ERPTIME,DELIVERYTIME,SUPPLIERNO,LASTEVENTNAME,LASTEVENTTIMEKEY,LASTEVENTTIME,LASTEVENTUSER,LASTEVENTCOMMENT) "
						+ "VALUES(:SITENAME,:INNERREQUESTNAME,:DELIVERYTYPE,TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),:SUPPLIERNO,:LASTEVENTNAME,:LASTEVENTTIMEKEY,TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),:LASTEVENTUSER,:LASTEVENTCOMMENT)";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertInner, innerRequest);
			} else {
				Map<String, String> innerRequest = new HashMap<String, String>();
				innerRequest.put("SITENAME", siteName);
				innerRequest.put("INNERREQUESTNAME", innerRequestName);
				innerRequest.put("DELIVERYTYPE", deliveryType);
				if (deliveryTime != null) {
					innerRequest.put("DELIVERYTIME", deliveryTime);
				}
				if (erpTime != null) {
					innerRequest.put("ERPTIME", erpTime);
				}
				innerRequest.put("SUPPLIERNO", supplierNO);
				innerRequest.put("LASTEVENTNAME", "Update");
				innerRequest.put("LASTEVENTTIMEKEY",
						TimeStampUtil.getCurrentEventTimeKey());
				innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
						"yyyy-MM-dd").format(new Date()));
				innerRequest.put("LASTEVENTUSER", "ERP");
				innerRequest.put("LASTEVENTCOMMENT", "Update");
				String insertInner = "UPDATE INNERREQUEST SET DELIVERYTYPE=:DELIVERYTYPE,ERPTIME=TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),DELIVERYTIME=TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),SUPPLIERNO=:SUPPLIERNO,LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
						+ "WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertInner, innerRequest);
			}
			if (detailList == null || detailList.isEmpty()) {
				Map<String, String> innerDetail = new HashMap<String, String>();
				innerDetail.put("SITENAME", siteName);
				innerDetail.put("INNERREQUESTNAME", innerRequestName);
				innerDetail.put("INNERREQUESTDETAILNAME",
						innerRequestDetailName);
				innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
				innerDetail.put("RECEIVEREQUESTDETAILNAME",
						receiveRequestDetailName);
				innerDetail.put("MATERIALSPECNAME", materialSpecName);
				innerDetail.put("CHARGE", charge);
				innerDetail.put("MATERIALQUANTITY", materialQuantity);
				innerDetail.put("UNIT", unit);
				innerDetail.put("ERPLOCATION", erpLocation);
				innerDetail.put("ERPFACTORY", erpFactory);
				String insertDetail = "INSERT INTO  INNERREQUESTDETAIL(SITENAME,INNERREQUESTNAME,INNERREQUESTDETAILNAME,RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME,CHARGE,MATERIALQUANTITY,UNIT,ERPLOCATION,ERPFACTORY) "
						+ "VALUES(:SITENAME,:INNERREQUESTNAME,:INNERREQUESTDETAILNAME,:RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:MATERIALSPECNAME,:CHARGE,:MATERIALQUANTITY,:UNIT,:ERPLOCATION,:ERPFACTORY)";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertDetail, innerDetail);
			} else {
				Map<String, String> innerDetail = new HashMap<String, String>();
				innerDetail.put("SITENAME", siteName);
				innerDetail.put("INNERREQUESTNAME", innerRequestName);
				innerDetail.put("INNERREQUESTDETAILNAME",
						innerRequestDetailName);
				innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
				innerDetail.put("RECEIVEREQUESTDETAILNAME",
						receiveRequestDetailName);
				innerDetail.put("MATERIALSPECNAME", materialSpecName);
				innerDetail.put("CHARGE", charge);
				innerDetail.put("MATERIALQUANTITY", materialQuantity);
				innerDetail.put("UNIT", unit);
				innerDetail.put("ERPLOCATION", erpLocation);
				innerDetail.put("ERPFACTORY", erpFactory);
				innerDetail.put("RECEIVEDQUANTITY", receivedQuantity);
				String insertDetail = "UPDATE INNERREQUESTDETAIL SET RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME=:RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME=:MATERIALSPECNAME,CHARGE=:CHARGE,MATERIALQUANTITY=:MATERIALQUANTITY,UNIT=:UNIT,ERPLOCATION=:ERPLOCATION,ERPFACTORY=:ERPFACTORY,RECEIVEDQUANTITY=:RECEIVEDQUANTITY "
						+ "WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertDetail, innerDetail);
			}

		}
		// flag等于3，执行删除操作
		else if (flag.equals("3")) {
			if (innerList != null || !innerList.isEmpty()) {
				Map<String, String> innerRequest = new HashMap<String, String>();
				innerRequest.put("SITENAME", siteName);
				innerRequest.put("INNERREQUESTNAME", innerRequestName);
				String deleteInner = "DELETE FROM INNERREQUEST WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(deleteInner, innerRequest);
			}
			if (detailList != null || !detailList.isEmpty()) {
				Map<String, String> innerDetail = new HashMap<String, String>();
				innerDetail.put("SITENAME", siteName);
				innerDetail.put("INNERREQUESTNAME", innerRequestName);
				innerDetail.put("INNERREQUESTDETAILNAME",
						innerRequestDetailName);
				String deleteDetail = "DELETE FROM INNERREQUESTDETAIL WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
				IDMFrameServiceProxy.getSqlTemplate()
						.update(deleteDetail, innerDetail);
			}
		}
	}
	
	

	/**
	 * （由ERPInterfaceServiceUtil INT_PI045更改）
	 */
    public void INT_14075(String innerRequestName,
            String innerRequestDetailName, String receiveRequestName,
            String receiveRequestDetailName, String deliveryType,
            String erpTime, String deliveryTime, String supplierNO,
            String erpFactory, String materialSpecName, String unit,
            String charge, String materialQuantity, String erpLocation,
            String flag, String seq, String receivedQuantity, String name1, String wadat_Ist, String maktx,
            String vrkme, String loekz, String umren, String umrez, String lgmng, String lifex, String beg03)
            throws CustomException {
        String siteName = new com.cim.idm.mwmsextend.generic.util.CommonValidation()
                .getSiteName(erpFactory);

        // InnerRequest innerRequest = new InnerRequest();
        // InnerRequestDetail innerRequestDetail = new InnerRequestDetail();
        String queryRequest = "SELECT * FROM INNERREQUEST WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
        Map<String, String> innerMap = new HashMap<String, String>();
        innerMap.put("SITENAME", siteName);
        innerMap.put("INNERREQUESTNAME", innerRequestName);
        List<Map<String, Object>> innerList = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(queryRequest, innerMap);

        String queryDetail = "SELECT * FROM INNERREQUESTDETAIL WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
        Map<String, String> detailMap = new HashMap<String, String>();
        detailMap.put("SITENAME", siteName);
        detailMap.put("INNERREQUESTNAME", innerRequestName);
        detailMap.put("INNERREQUESTDETAILNAME", innerRequestDetailName);
        List<Map<String, Object>> detailList = IDMFrameServiceProxy
                .getSqlTemplate()
                .queryForList(queryDetail, detailMap);
        // flag等于1，执行插入操作
        if (flag.equals("1")) {
            // 数据库中不存在当前内向交货单号
            if (innerList == null || innerList.isEmpty()) {
                Map<String, String> innerRequest = new HashMap<String, String>();
                innerRequest.put("SITENAME", siteName);
                innerRequest.put("INNERREQUESTNAME", innerRequestName);
                innerRequest.put("DELIVERYTYPE", deliveryType);
                if (deliveryTime != null) {
                    innerRequest.put("DELIVERYTIME", deliveryTime);
                }
                if (erpTime != null) {
                    innerRequest.put("ERPTIME", erpTime);
                }
                innerRequest.put("SUPPLIERNO", supplierNO);
                innerRequest.put("LASTEVENTNAME", "Create");
                innerRequest.put("LASTEVENTTIMEKEY",
                        TimeStampUtil.getCurrentEventTimeKey());
                innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
                        "yyyy-MM-dd").format(new Date()));
                innerRequest.put("LASTEVENTUSER", "ERP");
                innerRequest.put("LASTEVENTCOMMENT", "Create");
                String insertInner = "INSERT INTO  INNERREQUEST(SITENAME,INNERREQUESTNAME,DELIVERYTYPE,ERPTIME,DELIVERYTIME,SUPPLIERNO,LASTEVENTNAME,LASTEVENTTIMEKEY,LASTEVENTTIME,LASTEVENTUSER,LASTEVENTCOMMENT) "
                        + "VALUES(:SITENAME,:INNERREQUESTNAME,:DELIVERYTYPE,TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),:SUPPLIERNO,:LASTEVENTNAME,:LASTEVENTTIMEKEY,TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),:LASTEVENTUSER,:LASTEVENTCOMMENT)";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertInner, innerRequest);

            }
            // 数据库中不存在当前内向交货单行项目号
            if (detailList == null || detailList.isEmpty()) {
                Map<String, String> innerDetail = new HashMap<String, String>();
                innerDetail.put("SITENAME", siteName);
                innerDetail.put("INNERREQUESTNAME", innerRequestName);
                innerDetail.put("INNERREQUESTDETAILNAME",
                        innerRequestDetailName);
                innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
                innerDetail.put("RECEIVEREQUESTDETAILNAME",
                        receiveRequestDetailName);
                innerDetail.put("MATERIALSPECNAME", materialSpecName);
                innerDetail.put("CHARGE", charge);
                innerDetail.put("MATERIALQUANTITY", materialQuantity);
                innerDetail.put("RECEIVEDQUANTITY", receivedQuantity);
                innerDetail.put("UNIT", unit);
                innerDetail.put("ERPLOCATION", erpLocation);
                innerDetail.put("ERPFACTORY", erpFactory);
                innerDetail.put("NAME1", name1);
                innerDetail.put("WADAT_IST", wadat_Ist);
                innerDetail.put("MAKTX", maktx);
                innerDetail.put("VRKME", vrkme);
                innerDetail.put("LOEKZ", loekz);
                innerDetail.put("UMREN", umren);
                innerDetail.put("UMREZ", umrez);
                innerDetail.put("LGMNG", lgmng);
                innerDetail.put("LIFEX", lifex);
                innerDetail.put("BEG03", beg03);
                innerDetail.put("SEQ", seq);
                String insertDetail = "INSERT INTO  INNERREQUESTDETAIL(SITENAME,INNERREQUESTNAME,INNERREQUESTDETAILNAME,RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME,CHARGE,MATERIALQUANTITY,UNIT,ERPLOCATION,ERPFACTORY,RECEIVEDQUANTITY,NAME1,WADAT_IST,MAKTX,VRKME,LOEKZ,UMREN,UMREZ,LGMNG,LIFEX,BEG03,SEQ)"
                        + " VALUES(:SITENAME,:INNERREQUESTNAME,:INNERREQUESTDETAILNAME,:RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:MATERIALSPECNAME,:CHARGE,:MATERIALQUANTITY,:UNIT,:ERPLOCATION,:ERPFACTORY,:RECEIVEDQUANTITY,:NAME1,:WADAT_IST,:MAKTX,:VRKME,:LOEKZ,:UMREN,:UMREZ,:LGMNG,:LIFEX,:BEG03,:SEQ)";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertDetail, innerDetail);
            }
        }
        // flag等于2，执行修改操作
        else if (flag.equals("2")) {
            // 数据库中不存在当前内向交货单号
            if (innerList == null || innerList.isEmpty()) {
                Map<String, String> innerRequest = new HashMap<String, String>();
                innerRequest.put("SITENAME", siteName);
                innerRequest.put("INNERREQUESTNAME", innerRequestName);
                innerRequest.put("DELIVERYTYPE", deliveryType);
                if (deliveryTime != null) {
                    innerRequest.put("DELIVERYTIME", deliveryTime);
                }
                if (erpTime != null) {
                    innerRequest.put("ERPTIME", erpTime);
                }
                innerRequest.put("SUPPLIERNO", supplierNO);
                innerRequest.put("LASTEVENTNAME", "Create");
                innerRequest.put("LASTEVENTTIMEKEY",
                        TimeStampUtil.getCurrentEventTimeKey());
                innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
                        "yyyy-MM-dd").format(new Date()));
                innerRequest.put("LASTEVENTUSER", "ERP");
                innerRequest.put("LASTEVENTCOMMENT", "Create");
                String insertInner = "INSERT INTO  INNERREQUEST(SITENAME,INNERREQUESTNAME,DELIVERYTYPE,ERPTIME,DELIVERYTIME,SUPPLIERNO,LASTEVENTNAME,LASTEVENTTIMEKEY,LASTEVENTTIME,LASTEVENTUSER,LASTEVENTCOMMENT) "
                        + "VALUES(:SITENAME,:INNERREQUESTNAME,:DELIVERYTYPE,TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),:SUPPLIERNO,:LASTEVENTNAME,:LASTEVENTTIMEKEY,TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),:LASTEVENTUSER,:LASTEVENTCOMMENT)";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertInner, innerRequest);
            } else {
                Map<String, String> innerRequest = new HashMap<String, String>();
                innerRequest.put("SITENAME", siteName);
                innerRequest.put("INNERREQUESTNAME", innerRequestName);
                innerRequest.put("DELIVERYTYPE", deliveryType);
                if (deliveryTime != null) {
                    innerRequest.put("DELIVERYTIME", deliveryTime);
                }
                if (erpTime != null) {
                    innerRequest.put("ERPTIME", erpTime);
                }
                innerRequest.put("SUPPLIERNO", supplierNO);
                innerRequest.put("LASTEVENTNAME", "Update");
                innerRequest.put("LASTEVENTTIMEKEY",
                        TimeStampUtil.getCurrentEventTimeKey());
                innerRequest.put("LASTEVENTTIME", new SimpleDateFormat(
                        "yyyy-MM-dd").format(new Date()));
                innerRequest.put("LASTEVENTUSER", "ERP");
                innerRequest.put("LASTEVENTCOMMENT", "Update");
                String insertInner = "UPDATE INNERREQUEST SET DELIVERYTYPE=:DELIVERYTYPE,ERPTIME=TO_DATE(:ERPTIME,'yyyy-mm-dd,hh24:mi:ss'),DELIVERYTIME=TO_DATE(:DELIVERYTIME,'yyyy-mm-dd,hh24:mi:ss'),SUPPLIERNO=:SUPPLIERNO,LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=TO_DATE(:LASTEVENTTIME,'yyyy-mm-dd,hh24:mi:ss'),LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
                        + "WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertInner, innerRequest);
            }
            if (detailList == null || detailList.isEmpty()) {
                Map<String, String> innerDetail = new HashMap<String, String>();
                innerDetail.put("SITENAME", siteName);
                innerDetail.put("INNERREQUESTNAME", innerRequestName);
                innerDetail.put("INNERREQUESTDETAILNAME",
                        innerRequestDetailName);
                innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
                innerDetail.put("RECEIVEREQUESTDETAILNAME",
                        receiveRequestDetailName);
                innerDetail.put("MATERIALSPECNAME", materialSpecName);
                innerDetail.put("CHARGE", charge);
                innerDetail.put("MATERIALQUANTITY", materialQuantity);
                innerDetail.put("UNIT", unit);
                innerDetail.put("ERPLOCATION", erpLocation);
                innerDetail.put("ERPFACTORY", erpFactory);
                innerDetail.put("NAME1", name1);
                innerDetail.put("WADAT_IST", wadat_Ist);
                innerDetail.put("MAKTX", maktx);
                innerDetail.put("VRKME", vrkme);
                innerDetail.put("LOEKZ", loekz);
                innerDetail.put("UMREN", umren);
                innerDetail.put("UMREZ", umrez);
                innerDetail.put("LGMNG", lgmng);
                innerDetail.put("LIFEX", lifex);
                innerDetail.put("BEG03", beg03);
                innerDetail.put("SEQ", seq);
                String insertDetail = "INSERT INTO  INNERREQUESTDETAIL(SITENAME,INNERREQUESTNAME,INNERREQUESTDETAILNAME,RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME,CHARGE,MATERIALQUANTITY,UNIT,ERPLOCATION,ERPFACTORY,NAME1,WADAT_IST,MAKTX,VRKME,LOEKZ,UMREN,UMREZ,LGMNG,LIFEX,BEG03,SEQ) "
                        + " VALUES(:SITENAME,:INNERREQUESTNAME,:INNERREQUESTDETAILNAME,:RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:MATERIALSPECNAME,:CHARGE,:MATERIALQUANTITY,:UNIT,:ERPLOCATION,:ERPFACTORY,:NAME1,:WADAT_IST,:MAKTX,:VRKME,:LOEKZ,:UMREN,:UMREZ,:LGMNG,:LIFEX,:BEG03,:SEQ)";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertDetail, innerDetail);
            } else {
                Map<String, String> innerDetail = new HashMap<String, String>();
                innerDetail.put("SITENAME", siteName);
                innerDetail.put("INNERREQUESTNAME", innerRequestName);
                innerDetail.put("INNERREQUESTDETAILNAME",
                        innerRequestDetailName);
                innerDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
                innerDetail.put("RECEIVEREQUESTDETAILNAME",
                        receiveRequestDetailName);
                innerDetail.put("MATERIALSPECNAME", materialSpecName);
                innerDetail.put("CHARGE", charge);
                innerDetail.put("MATERIALQUANTITY", materialQuantity);
                innerDetail.put("UNIT", unit);
                innerDetail.put("ERPLOCATION", erpLocation);
                innerDetail.put("ERPFACTORY", erpFactory);
                innerDetail.put("RECEIVEDQUANTITY", receivedQuantity);
                innerDetail.put("NAME1", name1);
                innerDetail.put("WADAT_IST", wadat_Ist);
                innerDetail.put("MAKTX", maktx);
                innerDetail.put("VRKME", vrkme);
                innerDetail.put("LOEKZ", loekz);
                innerDetail.put("UMREN", umren);
                innerDetail.put("UMREZ", umrez);
                innerDetail.put("LGMNG", lgmng);
                innerDetail.put("LIFEX", lifex);
                innerDetail.put("BEG03", beg03);
                innerDetail.put("SEQ", seq);
                String insertDetail = "UPDATE INNERREQUESTDETAIL SET RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME=:RECEIVEREQUESTDETAILNAME,MATERIALSPECNAME=:MATERIALSPECNAME,CHARGE=:CHARGE,MATERIALQUANTITY=:MATERIALQUANTITY,UNIT=:UNIT,ERPLOCATION=:ERPLOCATION,ERPFACTORY=:ERPFACTORY,RECEIVEDQUANTITY=:RECEIVEDQUANTITY,"
                        + "NAME1=:NAME1,WADAT_IST=:WADAT_IST,MAKTX=:MAKTX,VRKME=:VRKME,LOEKZ=:LOEKZ,UMREN=:UMREN,UMREZ=:UMREZ,LGMNG=:LGMNG,LIFEX=:LIFEX,BEG03=:BEG03,SEQ=:SEQ  "
                        + "WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(insertDetail, innerDetail);
            }

        }
        // flag等于3，执行删除操作
        else if (flag.equals("3")) {
            if (innerList != null || !innerList.isEmpty()) {
                Map<String, String> innerRequest = new HashMap<String, String>();
                innerRequest.put("SITENAME", siteName);
                innerRequest.put("INNERREQUESTNAME", innerRequestName);
                String deleteInner = "DELETE FROM INNERREQUEST WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(deleteInner, innerRequest);
            }
            if (detailList != null || !detailList.isEmpty()) {
                Map<String, String> innerDetail = new HashMap<String, String>();
                innerDetail.put("SITENAME", siteName);
                innerDetail.put("INNERREQUESTNAME", innerRequestName);
                innerDetail.put("INNERREQUESTDETAILNAME",
                        innerRequestDetailName);
                String deleteDetail = "DELETE FROM INNERREQUESTDETAIL WHERE SITENAME=:SITENAME AND INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME";
                IDMFrameServiceProxy.getSqlTemplate()
                        .update(deleteDetail, innerDetail);
            }
        }

    }

	
	
	public void INT_GetBMDTOEMPOInfo(String flag, EventInfo eventInfo,
			String receiveRequestName,String erpFactoryName,
			String receiveRequestDetailName, 
			String receiveRequestState, 
			String materialSpecName,
			String description2, String requestQuantity, 
			String supplierNo,String supplierName,String sitename,String erpLocation,String receiveRequestDetailType)
			throws CustomException, ParseException {
		MaterialReceiveRequestServiceImpl receiveRequestImpl = new MaterialReceiveRequestServiceImpl();
		MaterialReceiveRequestDetailServiceImpl receiveRequestDetailImpl = new MaterialReceiveRequestDetailServiceImpl();
		MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();
		String siteName = sitename;
		// GET RECEIVEREQUEST
		String sql = "SELECT * FROM MATERIALRECEIVEREQUEST "
				+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("receiveRequestName", receiveRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET RECEIVEREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName and RECEIVEREQUESTNAME = :receiveRequestName";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("receiveRequestDetailName", receiveRequestDetailName);
		bindMap2.put("receiveRequestName", receiveRequestName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);



		// Create
		if (flag.equals("1")) {
			if (queryResult == null || queryResult.isEmpty()) {								
				receiveRequestImpl.createOemPO(eventInfo, siteName,
						receiveRequestName, "",
						receiveRequestState, supplierNo, "ERPOEMPO", "", "", "", "","",erpFactoryName);
			}
			
			if (queryResult2 == null || queryResult2.isEmpty()) {
				receiveRequestDetailImpl.create(eventInfo, siteName,
						receiveRequestName, receiveRequestDetailName,
						"",receiveRequestDetailType , materialSpecName,
						description2, requestQuantity, "0",
						erpLocation, "", "", "",
						"Created", "", "",
						"", "", "", erpFactoryName);
			}else{
				if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
						.equals("0")) {
					receiveRequestDetailImpl.remove(eventInfo, siteName,
							receiveRequestName, receiveRequestDetailName);
					
					
					receiveRequestDetailImpl.create(eventInfo, siteName,
							receiveRequestName, receiveRequestDetailName,
							"", receiveRequestDetailType, materialSpecName,
							description2, requestQuantity, "0",
							erpLocation, "", "", "",
							"Created", "", "",
							"", "", "", erpFactoryName);
				}else{

					receiveRequestDetailImpl.modify(eventInfo, siteName,
							receiveRequestName, receiveRequestDetailName,
							"", receiveRequestDetailType,
							materialSpecName, description2, requestQuantity,
							"0", "", "",
							"", "",
							"Created", "", "",
							"", "", "");
					
				}
		
			}

			receiveRequestImpl.createSupplier(supplierNo, supplierName, "",
					"", "", "", "", "");
		}else if(flag.equals("3")){
			if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
					.equals("0")) {
				receiveRequestDetailImpl.remove(eventInfo, siteName,
						receiveRequestName, receiveRequestDetailName);
				// GET RECEIVEREQUEST
				String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
						+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";
				Map<String, String> bindMap4 = new HashMap<String, String>();
				bindMap4.put("siteName", siteName);
				bindMap4.put("receiveRequestName", receiveRequestName);
				List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql4, bindMap4);
				if (queryResult4 == null || queryResult4.isEmpty()) {
					receiveRequestImpl.remove(eventInfo, siteName,
							receiveRequestName);
				}
			}
		}

	}
	
	//获取ERPOEMReserve 2017.4.5
	public void INT_GetBMDTOEMReserveInfo(String flag, EventInfo eventInfo,
			String shipRequestName,String erpFactoryName,
			String shipRequestDetailName, 
			String shipRequestState, 
			String shipRequestDetailType,
			String materialSpecName,
			String requestQuantity,
			String erpLocation,
			String erpReceiveLocation,
			String siteName,
			String oemErpFactoryName
			)
			throws Exception {
		MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();		
		MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
		MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();
		//String siteName = "BMDT";
		// GET RECEIVEREQUEST
		String sql = "SELECT * FROM MATERIALSHIPREQUEST "
				+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET RECEIVEREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName and SHIPREQUESTDETAILNAME = :shipRequestDetailName and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("shipRequestDetailName", shipRequestDetailName);
		bindMap2.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);
		
		// Create 
		if (flag.equals("1")) {
			//获取代工厂的sitename
			//存进materialshiprequest表中的customerno字段
			String oemSiteName = new CommonValidation().getSiteName(oemErpFactoryName);
			if (queryResult == null || queryResult.isEmpty()) {								
				shipRequestImpl.create(eventInfo, siteName, shipRequestName, shipRequestState, "",
						shipRequestDetailType, oemSiteName, "Reserve", "", "", "", "", "", "", "", "ERPOEMPO", erpFactoryName,"","","");
				}
			if (queryResult2 == null || queryResult2.isEmpty()) {
				shipRequestDetailImpl.create(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,materialSpecName,
						"", "",
						 requestQuantity, "0", "",erpLocation,
						 erpFactoryName, erpReceiveLocation,"","");
			}else{
				
					if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
							.equals("0")) {
						shipRequestDetailImpl.remove(eventInfo, siteName,
								shipRequestName, shipRequestDetailName);
						
							shipRequestDetailImpl.create(eventInfo, siteName,
							shipRequestName, shipRequestDetailName,materialSpecName,
							"", "",
							 requestQuantity, "0", "",erpLocation,
							 erpFactoryName, erpReceiveLocation,"","");
					}else{
						
						shipRequestDetailImpl.modify(eventInfo, siteName,
								shipRequestName, shipRequestDetailName,materialSpecName,
								"", "",
								requestQuantity,
								queryResult2.get(0).get("ASSIGNEDQUANTITY").toString());					
					}		
				}
				
					
		}else if(flag.equals("3")){
			if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
					.equals("0")) {
				shipRequestDetailImpl.remove(eventInfo, siteName,
						shipRequestName, shipRequestDetailName);
				// GET RECEIVEREQUEST
				String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
						+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";
				Map<String, String> bindMap4 = new HashMap<String, String>();
				bindMap4.put("siteName", siteName);
				bindMap4.put("receiveRequestName", shipRequestName);
				List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql4, bindMap4);
				if (queryResult4 == null || queryResult4.isEmpty()) {
					shipRequestImpl.remove(eventInfo, siteName,
							shipRequestName);
				}
			}
		}
		

	}
		
		public void INT_GetOEMPOInfo(String flag, EventInfo eventInfo,
				String receiveRequestName,String erpFactoryName,
				String receiveRequestDetailName, 
				String receiveRequestState, 
				String materialSpecName,
				String description2, String requestQuantity, 
				String supplierNo,List<MaterialReceiveRequestDetail> detailList)
				throws CustomException, ParseException {
			MaterialReceiveRequestServiceImpl receiveRequestImpl = new MaterialReceiveRequestServiceImpl();
			MaterialReceiveRequestDetailServiceImpl receiveRequestDetailImpl = new MaterialReceiveRequestDetailServiceImpl();
			MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();		
			// GET RECEIVEREQUEST
			String sql = "SELECT * FROM MATERIALRECEIVEREQUEST "
					+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";

			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("siteName", detailList.get(0).getKey().getSiteName());
			bindMap.put("receiveRequestName", receiveRequestName);

			List<Map<String, Object>> queryResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);

			// GET RECEIVEREQUESTDETAIL
			String sql2 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
					+ "WHERE SITENAME = :siteName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName and RECEIVEREQUESTNAME = :receiveRequestName";

			Map<String, String> bindMap2 = new HashMap<String, String>();
			bindMap2.put("siteName", detailList.get(0).getKey().getSiteName());
			bindMap2.put("receiveRequestDetailName", receiveRequestDetailName);
			bindMap2.put("receiveRequestName", receiveRequestName);

			List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql2, bindMap2);



			// Create
			if (flag.equals("1")) {
				if (queryResult == null || queryResult.isEmpty()) {								
//					receiveRequestImpl.BMDTcreate(eventInfo, siteName,
//							receiveRequestName, "",
//							receiveRequestState, supplierNo, "ERPOEMPO", "", "", "", "",erpFactoryName);
//					receiveRequestImpl.create(eventInfo, detailList.get(0).getKey().getSiteName(),
//							receiveRequestName, "", receiveRequestState, 
//							supplierNo, "ERPOEMPO", "", "", "", "","Completed");
					receiveRequestImpl.createOemPO(eventInfo, detailList.get(0).getKey().getSiteName(),
							receiveRequestName, "", receiveRequestState, 
							supplierNo, "ERPOEMPO", "", "", "", "","Completed",erpFactoryName);
				}
				
				if (queryResult2 == null || queryResult2.isEmpty()) {
					receiveRequestDetailImpl.create(eventInfo, detailList.get(0).getKey().getSiteName(),
							receiveRequestName, receiveRequestDetailName,
							"", "0", materialSpecName,
							description2, requestQuantity, "0",
							"", "", "", "",
							"Created", "", "",
							"", "", "", erpFactoryName);
				}else{
					if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
							.equals("0")) {
						//删除当前行项目信息，然后新建
						receiveRequestDetailImpl.remove(eventInfo, detailList.get(0).getKey().getSiteName(),
								receiveRequestName, receiveRequestDetailName);
//						String deleteSql=" DELETE FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME = :siteName and RECEIVEREQUESTDETAILNAME = :receiveRequestDetailName and RECEIVEREQUESTNAME = :receiveRequestName"; 
//						IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, bindMap2);
						receiveRequestDetailImpl.create(eventInfo, detailList.get(0).getKey().getSiteName(),
								receiveRequestName, receiveRequestDetailName,
								"", "0", materialSpecName,
								description2, requestQuantity, "0",
								"", "", "", "",
								"Created", "", "",
								"", "", "",erpFactoryName);	
					}else{
						
						receiveRequestDetailImpl.modify(eventInfo, detailList.get(0).getKey().getSiteName(),
								receiveRequestName, receiveRequestDetailName,
								"", "0",
								materialSpecName, description2, requestQuantity,
								"0", "", "",
								"", "",
								"Created", "", "",
								"", "", "");
						
					}
			
				}
			}else if(flag.equals("3")){
				if (queryResult2.get(0).get("RECEIVEDQUANTITY").toString()
						.equals("0")) {
					receiveRequestDetailImpl.remove(eventInfo, detailList.get(0).getKey().getSiteName(),
							receiveRequestName, receiveRequestDetailName);
					// GET RECEIVEREQUEST
					String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
							+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";
					Map<String, String> bindMap4 = new HashMap<String, String>();
					bindMap4.put("siteName", detailList.get(0).getKey().getSiteName());
					bindMap4.put("receiveRequestName", receiveRequestName);
					List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql4, bindMap4);
					if (queryResult4 == null || queryResult4.isEmpty()) {
						receiveRequestImpl.remove(eventInfo, detailList.get(0).getKey().getSiteName(),
								receiveRequestName);
					}
				}
			}

		}
	public void INT_GetERPOEMShipInfo(String flag, EventInfo eventInfo,
			String shipRequestName,String erpFactoryName,
			String shipRequestDetailName, 
			String shipRequestState, 
			String shipRequestDetailType,
			String materialSpecName,
			String requestQuantity,
			String erpLocation,
			String erpReceiveLocation,List<MaterialShipRequestDetail> detailList
			)
			throws Exception {
		MaterialShipRequestServiceImpl shipRequestImpl = new MaterialShipRequestServiceImpl();		
		MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
		MaterialShipRequestToOEMServiceImpl shipRequestToOEMImpl = new MaterialShipRequestToOEMServiceImpl();
		String siteName = detailList.get(0).getKey().getSiteName();
		// GET RECEIVEREQUEST
		String sql = "SELECT * FROM MATERIALSHIPREQUEST "
				+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		// GET RECEIVEREQUESTDETAIL
		String sql2 = "SELECT * FROM MATERIALSHIPREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName and SHIPREQUESTDETAILNAME = :shipRequestDetailName and SHIPREQUESTNAME = :shipRequestName";

		Map<String, String> bindMap2 = new HashMap<String, String>();
		bindMap2.put("siteName", siteName);
		bindMap2.put("shipRequestDetailName", shipRequestDetailName);
		bindMap2.put("shipRequestName", shipRequestName);

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap2);		
		// Create 
		if (flag.equals("1")) {
			//获取代工厂的sitename
			//存进materialshiprequest表中的customerno字段
			String oemSiteName = new CommonValidation().getSiteName(erpFactoryName);
			if (queryResult == null || queryResult.isEmpty()) {								
				shipRequestImpl.create(eventInfo, siteName, shipRequestName, shipRequestState, "", shipRequestDetailType, oemSiteName, "Reserve", "", "", "", "", "", "", "", "ERPOEMSHIP", erpFactoryName, "", "", "");
				}
			if (queryResult2 == null || queryResult2.isEmpty()) {
				shipRequestDetailImpl.create(eventInfo, siteName,
						shipRequestName, shipRequestDetailName,materialSpecName,
						"", "",
						 requestQuantity, "0", "",erpLocation,
						 erpFactoryName, erpReceiveLocation,"","");
			}else{
					if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
							.equals("0")) {
						shipRequestDetailImpl.remove(eventInfo, siteName,
								shipRequestName, shipRequestDetailName);
						
							shipRequestDetailImpl.create(eventInfo, siteName,
							shipRequestName, shipRequestDetailName,materialSpecName,
							"", "",
							 requestQuantity, "0", "",erpLocation,
							 erpFactoryName, erpReceiveLocation,"","");
					}else{
						
						shipRequestDetailImpl.modify(eventInfo, siteName,
								shipRequestName, shipRequestDetailName,materialSpecName,
								"", "",
								requestQuantity,
								queryResult2.get(0).get("ASSIGNEDQUANTITY").toString());					
					}		
				}
				
		}else if(flag.equals("3")){
			if (queryResult2.get(0).get("ASSIGNEDQUANTITY").toString()
					.equals("0")) {
				shipRequestDetailImpl.remove(eventInfo, siteName,
						shipRequestName, shipRequestDetailName);
				// GET RECEIVEREQUEST
				String sql4 = "SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
						+ "WHERE SITENAME = :siteName and SHIPREQUESTNAME = :shipRequestName";
				Map<String, String> bindMap4 = new HashMap<String, String>();
				bindMap4.put("siteName", siteName);
				bindMap4.put("receiveRequestName", shipRequestName);
				List<Map<String, Object>> queryResult4 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql4, bindMap4);
				if (queryResult4 == null || queryResult4.isEmpty()) {
					shipRequestImpl.remove(eventInfo, siteName,
							shipRequestName);
				}
			}
		}
		

	}

	public void saveRTShipRequest(String rtShipRequestName,String rtShipRequestDetailName,String erpFactory,String erpLocation,EventInfo eventInfo,String reasonCodeType,String reasonCode,
			String workOrder,String materialSpecName,String  materialQuantity,String charge,String receiveLocation,String receiver,String shipTime,
		    String	workOrderType,String returnType,String returnTypeDes,String Line,String reMark,String supplierNO) throws CustomException
	{
		try
		{
			CommonValidation cv=new CommonValidation();
			String siteName=cv.getSiteName(erpFactory);
			String queryShip="SELECT SHIPREQUESTNAME FROM MATERIALSHIPREQUEST WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME AND SYSTEMTYPE='MESSHIP' ";
			Map<String,String> mapShip=new HashMap<String, String>();
			mapShip.put("SITENAME", siteName);
			mapShip.put("SHIPREQUESTNAME", rtShipRequestName);
			List<Map<String,Object>> shipRequest=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShip, mapShip);
			//退货单信息
			CreateMaterialShipRequestInfo msInfo=new CreateMaterialShipRequestInfo();
			msInfo.setSiteName(siteName);
			msInfo.setShipRequestName(rtShipRequestName);
			msInfo.setShipRequestState("Created");
			msInfo.setShipRequestType("Refund");
			msInfo.setShipRequestDetailType(reasonCodeType);
			msInfo.setDeliveryType("Reserve");			
			msInfo.setSystemType("MESSHIP");		
			Map<String,Object> userColumn=new HashMap<String, Object>();
			userColumn.put("mesReceiveFlag", "N");
			userColumn.put("receiver", receiver);
			userColumn.put("shipPlanDate",Timestamp.valueOf(shipTime));
			msInfo.setUserColumns(userColumn);
			//退库单只发一次
			if(shipRequest.size()==0)
			{				
				MaterialShipRequestServiceProxy.getMaterialShipRequestService().create(eventInfo, msInfo);								
			}
			String queryDetail="SELECT SHIPREQUESTNAME FROM MATERIALSHIPREQUESTDETAIL WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME";
			mapShip.put("SHIPREQUESTDETAILNAME", rtShipRequestDetailName);			
			List<Map<String,Object>> shipDetail=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryDetail, mapShip);
			//新增退库单行项目
			if(shipDetail.size()==0)
			{
				CreateMaterialShipRequestDetailInfo mdInfo=new CreateMaterialShipRequestDetailInfo();
				mdInfo.setSiteName(siteName);
				mdInfo.setShipRequestName(rtShipRequestName);
				mdInfo.setShipRequestDetailName(rtShipRequestDetailName);
				mdInfo.setMaterialSpecName(materialSpecName);
				mdInfo.setRequestQuantity(Double.parseDouble(materialQuantity));
				mdInfo.setAssignedQuantity(0);			
				
				Map<String,Object> detailMap=new HashMap<String, Object>();
				detailMap.put("erpLocation",receiveLocation);//发出库位erpLocation 改成接收库位
				detailMap.put("erpFactoryName", erpFactory);
				detailMap.put("charge", charge);
				detailMap.put("erpReceiveLocation", erpLocation);//目前是接收库位receiveLocation改成线边仓库位
				detailMap.put("workOrder", workOrder);
				detailMap.put("workOrderType", workOrderType);
				detailMap.put("line", Line);
				detailMap.put("supplierNO", supplierNO);
				detailMap.put("returnType", returnType);
				detailMap.put("reasonCode", reasonCode);
				detailMap.put("reasonCodeType", reasonCodeType);
				detailMap.put("returnTypeDesc", returnTypeDes);
				detailMap.put("remark", reMark);			
				mdInfo.setUserColumns(detailMap);				
				MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().create(mdInfo);
			}
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new CustomException("MESRT-001", rtShipRequestName);
		}
	}
	
	// MES单据删除航项目发送到wms删除
	public void deleteRTShipRequest(String rtShipRequestName,String rtShipRequestDetailName,String sitename,EventInfo eventInfo	) throws CustomException
	{
		try
		{
			CommonValidation cv=new CommonValidation();
			String queryShip="SELECT SHIPREQUESTNAME FROM MATERIALSHIPREQUESTDETAIL WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME "
					+ "AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME ";
			Map<String,String> mapShip=new HashMap<String, String>();
			mapShip.put("SITENAME", sitename);
			mapShip.put("SHIPREQUESTNAME", rtShipRequestName);
			mapShip.put("SHIPREQUESTDETAILNAME", rtShipRequestDetailName);
			List<Map<String,Object>> shipRequest=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShip, mapShip);
			//退货单信息
			if(shipRequest.size()>0)
			{
			MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
			shipRequestDetailImpl.remove(eventInfo, sitename,
					rtShipRequestName, rtShipRequestDetailName);
			}
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new CustomException("MESRT-001", rtShipRequestName);
		}
	}
	//MES单据修改航项目枯萎发送到wms修改
	public void ModifyRTShipRequest(String rtShipRequestName,String erpReceiveLocation,String sitename,EventInfo eventInfo	) throws CustomException
	{
		try
		{
			String queryShip="SELECT SHIPREQUESTNAME,SHIPREQUESTDETAILNAME  FROM MATERIALSHIPREQUESTDETAIL WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME  ";
			Map<String,String> mapShip=new HashMap<String, String>();
			mapShip.put("SITENAME", sitename);
			mapShip.put("SHIPREQUESTNAME", rtShipRequestName);		
			List<Map<String,Object>> shipRequest=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShip, mapShip);
			//退货单信息
			if(shipRequest.size()>0)
			{
				for(int i=0;i<shipRequest.size();i++)
				{
			   MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
			   shipRequestDetailImpl.TM1modify(eventInfo, sitename, rtShipRequestName, shipRequest.get(i).get("SHIPREQUESTDETAILNAME").toString(),erpReceiveLocation);
				}

			}
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new CustomException("MESRT-001", rtShipRequestName);
		}
	}
	//B5新增 by WJ
	public void deleteUnAssignedRTShipRequestdetail(String rtShipRequestName,EventInfo eventInfo) throws CustomException
	{
		try
		{
			CommonValidation cv=new CommonValidation();
			String queryShip="SELECT SHIPREQUESTDETAILNAME,SITENAME FROM MATERIALSHIPREQUESTDETAIL WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME "
					+ "AND ASSIGNEDQUANTITY='0' ";
			Map<String,String> mapShip=new HashMap<String, String>();
			mapShip.put("SHIPREQUESTNAME", rtShipRequestName);
			List<Map<String,Object>> shipRequest=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShip, mapShip);
			//退货单信息
			if(shipRequest.size()>0)
			{
				for(int i=0;i<shipRequest.size();i++)
				{
					MaterialShipRequestDetailServiceImpl shipRequestDetailImpl = new MaterialShipRequestDetailServiceImpl();
					shipRequestDetailImpl.remove(eventInfo, shipRequest.get(i).get("SITENAME").toString(),
							rtShipRequestName, shipRequest.get(i).get("SHIPREQUESTDETAILNAME").toString());
				}
			}
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new CustomException("MESRT-001", rtShipRequestName);
		}
	}
	//B3增加Bom接口
	public static void insertCT_PLMINF_PI143(String productSpecName, Document message)
		    throws Exception
		  {
		    Element body = message.getRootElement().getChild("Body");

		    String ITEM_ID = "";
		    String OBJECT_DESC = "";
		    String BL_QUANTITY = "";
		    String ITEM_REVISION_ID = "";
		    String BOE_BL_ALT_GROUP = "";
		    String T4_PRIORITY = "";
		    String BOE_BL_ALT_PERCENT = "";
		    String BOE_BL_ALT_POLICY = "";
		    String UP_ITEM_ID = "";
		    String UP_BL_QUANTITY = "";
		    String UOM = "";
		    String BL_UOM = "";
		    try
		    {
		      for (Iterator iterator = body.getChildren().iterator(); iterator.hasNext(); )
		      {
		        Element itemsE = (Element)iterator.next();

		        StringBuilder sql = new StringBuilder();
		        sql.append("INSERT INTO BSPLMINF_PI143(                                                                                              ");
		        sql.append("   PRODUCTSPECNAME, ITEM_ID, OBJECT_DESC, BL_QUANTITY,                                               ");
		        sql.append("   ITEM_REVISION_ID, BOE_BL_ALT_GROUP, T4_PRIORITY, BOE_BL_ALT_PERCENT,                    ");
		        sql.append("   BOE_BL_ALT_POLICY, UP_ITEM_ID, UP_BL_QUANTITY, UOM,                                                  ");
		        sql.append("   BL_UOM, CREATETIME)                                                                                                       ");
		        sql.append(" VALUES (                                                                                                                             ");
		        sql.append("   :PRODUCTSPECNAME, :ITEM_ID, :OBJECT_DESC, :BL_QUANTITY,                                          ");
		        sql.append("   :ITEM_REVISION_ID, :BOE_BL_ALT_GROUP, :T4_PRIORITY, :BOE_BL_ALT_PERCENT,               ");
		        sql.append("   :BOE_BL_ALT_POLICY, :UP_ITEM_ID, :UP_BL_QUANTITY, :UOM,                                             ");
		        sql.append("   :BL_UOM, SYSDATE)                                                                                                           ");

		        ITEM_ID = itemsE.getChildText("ITEM_ID");
		        OBJECT_DESC = itemsE.getChildText("OBJECT_DESC");
		        BL_QUANTITY = itemsE.getChildText("BL_QUANTITY");
		        ITEM_REVISION_ID = itemsE.getChildText("ITEM_REVISION_ID");
		        BOE_BL_ALT_GROUP = itemsE.getChildText("BOE_BL_ALT_GROUP");
		        T4_PRIORITY = itemsE.getChildText("T4_PRIORITY");
		        BOE_BL_ALT_PERCENT = itemsE.getChildText("BOE_BL_ALT_PERCENT");
		        BOE_BL_ALT_POLICY = itemsE.getChildText("BOE_BL_ALT_POLICY");
		        UP_ITEM_ID = itemsE.getChildText("UP_ITEM_ID");
		        UP_BL_QUANTITY = itemsE.getChildText("UP_BL_QUANTITY");
		        UOM = itemsE.getChildText("UOM");
		        BL_UOM = itemsE.getChildText("BL_UOM");

		        Map bindMap = new HashMap();
		        bindMap.put("PRODUCTSPECNAME", productSpecName);
		        bindMap.put("ITEM_ID", ITEM_ID);
		        bindMap.put("OBJECT_DESC", OBJECT_DESC);
		        bindMap.put("BL_QUANTITY", BL_QUANTITY);
		        bindMap.put("ITEM_REVISION_ID", ITEM_REVISION_ID);
		        bindMap.put("BOE_BL_ALT_GROUP", BOE_BL_ALT_GROUP);
		        bindMap.put("T4_PRIORITY", T4_PRIORITY);
		        bindMap.put("BOE_BL_ALT_PERCENT", BOE_BL_ALT_PERCENT);
		        bindMap.put("BOE_BL_ALT_POLICY", BOE_BL_ALT_POLICY);
		        bindMap.put("UP_ITEM_ID", UP_ITEM_ID);
		        bindMap.put("UP_BL_QUANTITY", UP_BL_QUANTITY);
		        bindMap.put("UOM", UOM);
		        bindMap.put("BL_UOM", BL_UOM);

		        IDMFrameServiceProxy.getSqlTemplate().update(sql.toString(), bindMap);
		        log.info("Insert BSERPINF_PI107 Success: " + productSpecName + " " + OBJECT_DESC);
		      }
		    }
		    catch (Exception e)
		    {
		      log.error("Insert BSERPINF_PI107 Error: " + productSpecName + " " + OBJECT_DESC);
		      log.error(e.getMessage());
		    }
		  }
	
}
