package com.cim.idm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.data.TransportCommand;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.service.WCSService;
import com.cim.idm.util.WCSHttpUtil;
import com.cim.idm.wmsextend.generic.util.ConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description TODO
 * @Author li
 * @Date 2024/4/25 15:32
 */
@Service
@Slf4j
public class WCSServiceImpl implements WCSService {

    @Autowired
	WCSHttpUtil wCSHttpUtil;

    //dev
    //private static String baseUrl = "http://127.0.0.1:8017";
    
    //prod
   private static String baseUrl = "http://172.22.21.200:8017";
    /**
     * 搬送指令下发
     * @param TRANSPORTCOMMANDID
     * @return
     */
    @Override
    public String transportCommandRequest(String TRANSPORTCOMMANDID,String userId) {
//    	if (1 == 1) return "{\"RETURNCODE\":1,\"RETURNMESSAGE\":\"货位调整成功！\",\"vbillcode\":\"WT2408000004\"}";
    	StringBuffer stringBuffer = new StringBuffer();
    	String Querysql="SELECT  PACKINGNAME,DURABLENAME FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID =:TRANSPORTCOMMANDID";
    	Map<String, Object> QueryMap = new HashMap<String, Object>();
    	QueryMap.put("TRANSPORTCOMMANDID",TRANSPORTCOMMANDID );
    	List<Map<String,Object>> list =IDMFrameServiceProxy.getSqlTemplate().queryForList(Querysql, QueryMap);
    	
    	String Querysql2 ="SELECT  DISTINCT DURABLENAME FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID =:TRANSPORTCOMMANDID";
    	List<Map<String,Object>> list2 =IDMFrameServiceProxy.getSqlTemplate().queryForList(Querysql2, QueryMap);
    	 String doExchange = "";
    	//根据托盘号去循环发消息
    	for (Map<String, Object> map : list2) {
    		stringBuffer = new StringBuffer();
    		String trayName = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
    	   	if(list.get(0).get("PACKINGNAME").equals("TP"))
        	{
        		stringBuffer.append(" ");
            	stringBuffer.append(" SELECT T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE,");
            	stringBuffer.append(" T.TRANSPORTCOMMANDID          TRANSPORTCOMMANDID,");
            	stringBuffer.append("   T.INDESTINATION,");  
            	stringBuffer.append(" T.OUTDESTINATION,");   
            	stringBuffer.append(" D.MATERIALSPECNAME   PRODUCTSPECNAME,        ");  
            	stringBuffer.append(" S.ENCODE                      SDK_DESC,");
            	stringBuffer.append(" MO.PHASE,");
            	stringBuffer.append(" MO.MATERIALPACKINGNAME        ,");
            	stringBuffer.append(" T.DURABLENAME                 TRAYNAME,");
            	stringBuffer.append(" T2.STATE TRANSPORTSTATE,");
            	stringBuffer.append(" T.ISAGV,");  
            	stringBuffer.append(" T.WIDTH,");
            	stringBuffer.append(" T.DIAMETER,");
            	stringBuffer.append(" T.DIAMETER,");
            	stringBuffer.append(" T.DEVIATION,");
            	stringBuffer.append("  T.WEIGHT,");
            	stringBuffer.append(" T.PRODUCTLINE,T.INITILATION , T.ENDING, T.AB ,MO.MATERIALPACKINGNAME PALLETNAME");
            	stringBuffer.append(" FROM TRANSPORTCOMMANDDETAIL T ");
            	stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 on T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID ");
            	stringBuffer.append(" left join MATERIALPACKING MO on T.PACKINGNAME = MO.MATERIALPACKINGNAME ");
            	stringBuffer.append(" LEFT JOIN SDK_SPEC S ON MO.SDK_ID = S.SDK_ID ");
            	stringBuffer.append(" LEFT JOIN DURABLE D ON D.DURABLENAME = T.DURABLENAME ");
            	stringBuffer.append(" WHERE T.TRANSPORTCOMMANDID =  ? AND T.DURABLENAME = ?");
        	} else if ("".equals(trayName)) {
        		stringBuffer.append(" ");
        		stringBuffer.append(" SELECT ");
        		stringBuffer.append(" T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE, ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID TRANSPORTCOMMANDID, ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
        		stringBuffer.append(" LISTAGG(MO.MATERIALSPECNAME, ';')  WITHIN GROUP (ORDER BY MO.MATERIALSPECNAME) AS  PRODUCTSPECNAME, ");
        		stringBuffer.append(" LISTAGG(S.ENCODE, ';')  WITHIN GROUP (ORDER BY S.ENCODE) AS  SDK_DESC, ");
        		stringBuffer.append(" LISTAGG(MO.PHASE, ';')  WITHIN GROUP (ORDER BY MO.PHASE) AS  PHASE, ");
        		stringBuffer.append(" T.DURABLENAME  TRAYNAME, ");
//        		stringBuffer.append(" LISTAGG(T.DURABLENAME , ';')  WITHIN GROUP (ORDER BY T.DURABLENAME) AS TRAYNAME, ");
        		stringBuffer.append(" T2.STATE TRANSPORTSTATE, ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS,");
        		stringBuffer.append(" LISTAGG(MO.MATERIALPACKINGNAME, ';')  WITHIN GROUP (ORDER BY MO.MATERIALPACKINGNAME) AS PALLETNAME ");
//        		stringBuffer.append(" MO.MATERIALPACKINGNAME AS PALLETNAME ");
        		stringBuffer.append(" FROM ");
        		stringBuffer.append(" TRANSPORTCOMMANDDETAIL T ");
        		stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 ON ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID ");
        		stringBuffer.append(" LEFT JOIN MATERIALPACKING MO ON ");
        		stringBuffer.append(" T.PACKINGNAME = MO.MATERIALPACKINGNAME ");
        		stringBuffer.append(" LEFT JOIN SDK_SPEC S ON ");
        		stringBuffer.append(" MO.SDK_ID = S.SDK_ID ");
        		stringBuffer.append(" WHERE ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID = ? AND  (T.DURABLENAME = '' OR T.DURABLENAME IS NULL ) ");
        		stringBuffer.append(" GROUP BY T2.TRANSPORTCOMMANDDETAILTYPE , ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID , ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
//        		stringBuffer.append(" MO.MATERIALSPECNAME , ");
//        		stringBuffer.append(" S.ENCODE , ");
//        		stringBuffer.append(" MO.PHASE, ");
//        		stringBuffer.append(" MO.MATERIALPACKINGNAME , ");
        		stringBuffer.append(" T2.STATE , ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS ,T.DURABLENAME ");
        	} else {
        		stringBuffer.append(" ");
        		stringBuffer.append(" SELECT ");
        		stringBuffer.append(" T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE, ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID TRANSPORTCOMMANDID, ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
        		stringBuffer.append(" LISTAGG(MO.MATERIALSPECNAME, ';')  WITHIN GROUP (ORDER BY MO.MATERIALSPECNAME) AS  PRODUCTSPECNAME, ");
        		stringBuffer.append(" LISTAGG(S.ENCODE, ';')  WITHIN GROUP (ORDER BY S.ENCODE) AS  SDK_DESC, ");
        		stringBuffer.append(" LISTAGG(MO.PHASE, ';')  WITHIN GROUP (ORDER BY MO.PHASE) AS  PHASE, ");
        		stringBuffer.append(" T.DURABLENAME  TRAYNAME, ");
//        		stringBuffer.append(" LISTAGG(T.DURABLENAME , ';')  WITHIN GROUP (ORDER BY T.DURABLENAME) AS TRAYNAME, ");
        		stringBuffer.append(" T2.STATE TRANSPORTSTATE, ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS,");
        		stringBuffer.append(" LISTAGG(MO.MATERIALPACKINGNAME, ';')  WITHIN GROUP (ORDER BY MO.MATERIALPACKINGNAME) AS PALLETNAME ");
//        		stringBuffer.append(" MO.MATERIALPACKINGNAME AS PALLETNAME ");
        		stringBuffer.append(" FROM ");
        		stringBuffer.append(" TRANSPORTCOMMANDDETAIL T ");
        		stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 ON ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID ");
        		stringBuffer.append(" LEFT JOIN MATERIALPACKING MO ON ");
        		stringBuffer.append(" T.PACKINGNAME = MO.MATERIALPACKINGNAME ");
        		stringBuffer.append(" LEFT JOIN SDK_SPEC S ON ");
        		stringBuffer.append(" MO.SDK_ID = S.SDK_ID ");
        		stringBuffer.append(" WHERE ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID = ? AND  T.DURABLENAME = ? ");
        		stringBuffer.append(" GROUP BY T2.TRANSPORTCOMMANDDETAILTYPE , ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID , ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
//        		stringBuffer.append(" MO.MATERIALSPECNAME , ");
//        		stringBuffer.append(" S.ENCODE , ");
//        		stringBuffer.append(" MO.PHASE, ");
//        		stringBuffer.append(" MO.MATERIALPACKINGNAME , ");
        		stringBuffer.append(" T2.STATE , ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS ,T.DURABLENAME ");
        	}
        	List<TransportCommand> transportInfo = new ArrayList<TransportCommand> ();
        	if ("".equals(trayName)) {
        		Object[] bindSet = {TRANSPORTCOMMANDID};
        		 transportInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
            			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        	} else {
        		Object[] bindSet = {TRANSPORTCOMMANDID,trayName};
        		 transportInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
            			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        	}
        	
        	
            for (int i = 0; i < transportInfo.size(); i++) {
            	JSONObject transportCommandRequest = createTransportCommandRequest(transportInfo.get(i),userId);
            	doExchange = wCSHttpUtil.httpPost(baseUrl + "/api/WCS/TransportCommandRequest", transportCommandRequest, null);
                org.json.JSONObject jsonObject = new org.json.JSONObject(doExchange);
        		Thread t = new Thread(new Runnable(){  
        			public void run(){  
        				// run方法具体重写
        				UUID uuid = UUID.randomUUID();
        				ErpMessageLog erplog = new ErpMessageLog();
        				erplog.setEventUser("transportCommandRequest");
        				erplog.setServerName("WmsToWcs");
        				erplog.setEventName("transportCommandRequest");
        				erplog.setId(uuid.toString());
        				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
        				erplog.setMessageId(TRANSPORTCOMMANDID);
        				erplog.setSendMsg2(transportCommandRequest.toJSONString());
        				erplog.setReturnMsg2(jsonObject.toString());
        				erplog.setResultCode(jsonObject.get("RETURNCODE").toString());
        				saveMessageLog(erplog);  
        			}});  
        	        t.start();
    			
    		}
		}
        return doExchange;
    }
    
    
    /**
     * 只打印标签的立库入库搬送
     */
    public String bqTransportCommandRequest(String TRANSPORTCOMMANDID,String userId) {
    	StringBuffer stringBuffer = new StringBuffer();
    	String Querysql="SELECT  PACKINGNAME,DURABLENAME FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID =:TRANSPORTCOMMANDID";
    	Map<String, Object> QueryMap = new HashMap<String, Object>();
    	QueryMap.put("TRANSPORTCOMMANDID",TRANSPORTCOMMANDID );
    	List<Map<String,Object>> list =IDMFrameServiceProxy.getSqlTemplate().queryForList(Querysql, QueryMap);
    	
    	String Querysql2 ="SELECT  DISTINCT DURABLENAME FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID =:TRANSPORTCOMMANDID";
    	List<Map<String,Object>> list2 =IDMFrameServiceProxy.getSqlTemplate().queryForList(Querysql2, QueryMap);
    	 String doExchange = "";
    	//根据托盘号去循环发消息
    	for (Map<String, Object> map : list2) {
    		stringBuffer = new StringBuffer();
    		String trayName = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
    	   	if(list.get(0).get("PACKINGNAME").equals("TP"))
        	{
        		stringBuffer.append(" ");
        		stringBuffer.append(" SELECT T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE, ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID          TRANSPORTCOMMANDID, ");
        		stringBuffer.append(" T.INDESTINATION,   ");
        		stringBuffer.append(" T.OUTDESTINATION,    ");
        		stringBuffer.append(" D.MATERIALSPECNAME   PRODUCTSPECNAME,  ");         
        		stringBuffer.append(" S.SPECNAME                      SDK_DESC, ");
        		stringBuffer.append(" MO.PHASE, ");
        		stringBuffer.append(" MO.LOTNAME MATERIALPACKINGNAME        , ");
        		stringBuffer.append(" T.DURABLENAME                 TRAYNAME, ");
        		stringBuffer.append(" T2.STATE TRANSPORTSTATE, ");
        		stringBuffer.append(" T.ISAGV,   ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE,T.INITILATION , T.ENDING, T.AB ,MO.LOTNAME PALLETNAME ");
        		stringBuffer.append(" FROM TRANSPORTCOMMANDDETAIL T  ");
        		stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 on T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID  ");
        		stringBuffer.append(" left join BS_MES_SHIPPED MO on T.PACKINGNAME = MO.LOTNAME  ");
        		stringBuffer.append(" LEFT JOIN SDK_SPEC S ON MO.SDK_ID = S.SDK_ID  ");
        		stringBuffer.append(" LEFT JOIN DURABLE D ON D.DURABLENAME = T.DURABLENAME  ");
        		stringBuffer.append(" WHERE T.TRANSPORTCOMMANDID =  ? AND T.DURABLENAME = ? ");
        	} else if ("".equals(trayName)) {
        		stringBuffer.append(" ");
        		stringBuffer.append(" SELECT  ");
        		stringBuffer.append("  T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE,  ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID TRANSPORTCOMMANDID,  ");
        		stringBuffer.append(" T.INDESTINATION,  ");
        		stringBuffer.append(" T.OUTDESTINATION,  ");
        		stringBuffer.append(" LISTAGG(MO.PRODUCTSPECNAME, ';')  WITHIN GROUP (ORDER BY MO.PRODUCTSPECNAME) AS  PRODUCTSPECNAME,  ");
        		stringBuffer.append("  LISTAGG(S.ENCODE, ';')  WITHIN GROUP (ORDER BY S.ENCODE) AS  SDK_DESC,  ");
        		stringBuffer.append(" LISTAGG(MO.PHASE, ';')  WITHIN GROUP (ORDER BY MO.PHASE) AS  PHASE,  ");
        		stringBuffer.append(" T.DURABLENAME  TRAYNAME,  ");
        		stringBuffer.append("  T2.STATE TRANSPORTSTATE,  ");
        		stringBuffer.append("  T.ISAGV,  ");
        		stringBuffer.append("  T.WIDTH,  ");
        		stringBuffer.append("  T.DIAMETER,  ");
        		stringBuffer.append("  T.DIAMETER,  ");
        		stringBuffer.append("  T.DEVIATION,  ");
        		stringBuffer.append("  T.WEIGHT,  ");
        		stringBuffer.append("  T.PRODUCTLINE,  ");
        		stringBuffer.append("  T.INITILATION ,  ");
        		stringBuffer.append("  T.ENDING,  ");
        		stringBuffer.append("  T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS, ");
        		stringBuffer.append("  LISTAGG(MO.LOTNAME , ';')  WITHIN GROUP (ORDER BY MO.LOTNAME) AS PALLETNAME  ");
        		stringBuffer.append("  FROM  ");
        		stringBuffer.append("  TRANSPORTCOMMANDDETAIL T  ");
        		stringBuffer.append("  LEFT JOIN TRANSPORTCOMMAND T2 ON  ");
        		stringBuffer.append("  T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID  ");
        		stringBuffer.append(" LEFT JOIN BS_MES_SHIPPED MO ON  ");
        		stringBuffer.append(" T.PACKINGNAME = MO.LOTNAME  ");
        		stringBuffer.append(" LEFT JOIN SDK_SPEC S ON  ");
        		stringBuffer.append(" MO.SDK_ID = S.SDK_ID  ");
        		stringBuffer.append("  WHERE  1 = 1 ");
        		stringBuffer.append(" AND T.TRANSPORTCOMMANDID = ? AND  (T.DURABLENAME = '' OR T.DURABLENAME IS NULL )  ");
        		stringBuffer.append(" GROUP BY T2.TRANSPORTCOMMANDDETAILTYPE ,  ");
        		stringBuffer.append("  T.TRANSPORTCOMMANDID ,  ");
        		stringBuffer.append("  T.INDESTINATION,  ");
        		stringBuffer.append("  T.OUTDESTINATION,  ");
        		stringBuffer.append("  T2.STATE ,  ");
        		stringBuffer.append(" T.ISAGV,  ");
        		stringBuffer.append(" T.WIDTH,  ");
        		stringBuffer.append(" T.DIAMETER,  ");
        		stringBuffer.append(" T.DIAMETER,  ");
        		stringBuffer.append("  T.DEVIATION,  ");
        		stringBuffer.append("  T.WEIGHT,  ");
        		stringBuffer.append(" T.PRODUCTLINE,  ");
        		stringBuffer.append(" T.INITILATION ,  ");
        		stringBuffer.append(" T.ENDING,  ");
        		stringBuffer.append("  T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS ,T.DURABLENAME ");
        	} else {
        		stringBuffer.append(" ");
        		stringBuffer.append(" SELECT ");
        		stringBuffer.append(" T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE, ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID TRANSPORTCOMMANDID, ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
        		stringBuffer.append(" LISTAGG(MO.PRODUCTSPECNAME , ';')  WITHIN GROUP (ORDER BY MO.PRODUCTSPECNAME) AS  PRODUCTSPECNAME, ");
        		stringBuffer.append(" LISTAGG(S.ENCODE, ';')  WITHIN GROUP (ORDER BY S.ENCODE) AS  SDK_DESC, ");
        		stringBuffer.append(" LISTAGG(MO.PHASE, ';')  WITHIN GROUP (ORDER BY MO.PHASE) AS  PHASE, ");
        		stringBuffer.append(" T.DURABLENAME  TRAYNAME, ");
        		stringBuffer.append(" T2.STATE TRANSPORTSTATE, ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append("  T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS, ");
        		stringBuffer.append(" LISTAGG(MO.LOTNAME, ';')  WITHIN GROUP (ORDER BY MO.LOTNAME) AS PALLETNAME ");
        		stringBuffer.append(" FROM ");
        		stringBuffer.append(" TRANSPORTCOMMANDDETAIL T ");
        		stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 ON ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID ");
        		stringBuffer.append(" LEFT JOIN BS_MES_SHIPPED MO ON ");
        		stringBuffer.append(" T.PACKINGNAME = MO.LOTNAME  ");
        		stringBuffer.append(" LEFT JOIN SDK_SPEC S ON ");
        		stringBuffer.append(" MO.SDK_ID = S.SDK_ID ");
        		stringBuffer.append(" WHERE 1 = 1 ");
        		stringBuffer.append(" AND  T.TRANSPORTCOMMANDID = ? AND  T.DURABLENAME = ? ");
        		stringBuffer.append(" GROUP BY T2.TRANSPORTCOMMANDDETAILTYPE , ");
        		stringBuffer.append(" T.TRANSPORTCOMMANDID , ");
        		stringBuffer.append(" T.INDESTINATION, ");
        		stringBuffer.append(" T.OUTDESTINATION, ");
        		stringBuffer.append(" T2.STATE , ");
        		stringBuffer.append(" T.ISAGV, ");
        		stringBuffer.append(" T.WIDTH, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DIAMETER, ");
        		stringBuffer.append(" T.DEVIATION, ");
        		stringBuffer.append(" T.WEIGHT, ");
        		stringBuffer.append(" T.PRODUCTLINE, ");
        		stringBuffer.append(" T.INITILATION , ");
        		stringBuffer.append(" T.ENDING, ");
        		stringBuffer.append(" T.AB , T.PORT,T.TEMPERATURE,T.BAKINGDAYS ,T.DURABLENAME ");
        	}
        	List<TransportCommand> transportInfo = new ArrayList<TransportCommand> ();
        	if ("".equals(trayName)) {
        		Object[] bindSet = {TRANSPORTCOMMANDID};
        		 transportInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
            			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        	} else {
        		Object[] bindSet = {TRANSPORTCOMMANDID,trayName};
        		 transportInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
            			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        	}
        	
        	
            for (int i = 0; i < transportInfo.size(); i++) {
            	JSONObject transportCommandRequest = createTransportCommandRequest(transportInfo.get(i),userId);
            	doExchange = wCSHttpUtil.httpPost(baseUrl + "/api/WCS/TransportCommandRequest", transportCommandRequest, null);
                org.json.JSONObject jsonObject = new org.json.JSONObject(doExchange);
        		Thread t = new Thread(new Runnable(){  
        			public void run(){  
        				// run方法具体重写
        				UUID uuid = UUID.randomUUID();
        				ErpMessageLog erplog = new ErpMessageLog();
        				erplog.setEventUser("transportCommandRequest");
        				erplog.setServerName("WmsToWcs");
        				erplog.setEventName("transportCommandRequest");
        				erplog.setId(uuid.toString());
        				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
        				erplog.setMessageId(TRANSPORTCOMMANDID);
        				erplog.setSendMsg2(transportCommandRequest.toJSONString());
        				erplog.setReturnMsg2(jsonObject.toString());
        				erplog.setResultCode(jsonObject.get("RETURNCODE").toString());
        				saveMessageLog(erplog);  
        			}});  
        	        t.start();
    			
    		}
		}
        return doExchange;
    }
    

    /**
     * 搬送任务更新
     *
     * @param TRANSPORTCOMMANDID
     * @return
     */
    @Override
    public String TransportCommandChange(String TRANSPORTCOMMANDID) {
    	StringBuffer stringBuffer = new StringBuffer();
    	stringBuffer.append(" ");
    	stringBuffer.append(" SELECT T2.TRANSPORTCOMMANDDETAILTYPE TRANSPORTCOMMANDTYPE,");
    	stringBuffer.append(" T.TRANSPORTCOMMANDID          TRANSPORTCOMMANDID,");
    	stringBuffer.append(" T.INDESTINATION,");
    	stringBuffer.append(" T.OUTDESTINATION,");
    	stringBuffer.append(" MO.MATERIALSPECNAME   ,        ");
    	stringBuffer.append(" S.ENCODE                      SDK_DESC,");
    	stringBuffer.append(" MO.PHASE,");
    	stringBuffer.append(" MO.MATERIALPACKINGNAME        PALLETNAME,");
    	stringBuffer.append(" T.DURABLENAME                 TRAYNAME,");
    	stringBuffer.append(" T2.STATE TRANSPORTSTATE,");
    	stringBuffer.append(" T.ISAGV,");
    	stringBuffer.append(" T.WIDTH,");
    	stringBuffer.append(" T.DIAMETER,");
    	stringBuffer.append(" T.DIAMETER,");
    	stringBuffer.append(" T.DEVIATION,");
    	stringBuffer.append("  T.WEIGHT,");
    	stringBuffer.append(" T.PRODUCTLINE,M2.STATE TRANSPORTSTATE ");
    	stringBuffer.append(" FROM TRANSPORTCOMMANDDETAIL T ");
    	stringBuffer.append(" LEFT JOIN TRANSPORTCOMMAND T2 on T.TRANSPORTCOMMANDID = T2.TRANSPORTCOMMANDID ");
    	stringBuffer.append(" left join MATERIALPACKING MO on T.PACKINGNAME = MO.MATERIALPACKINGNAME ");
    	stringBuffer.append(" LEFT JOIN SDK_SPEC S ON MO.SDK_ID = S.SDK_ID ");
    	stringBuffer.append(" WHERE T.TRANSPORTCOMMANDID =  ? ");
    	Object[] bindSet = {TRANSPORTCOMMANDID};
   	 List<TransportCommand> transportInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
   			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        JSONObject transportCommandChange = createTransportCommandChange(transportInfo.get(0));
        String doExchange = wCSHttpUtil.httpPost(baseUrl + "/api/WCS/TransportCommandChange", transportCommandChange, null);
        org.json.JSONObject jsonObject = new org.json.JSONObject(doExchange);
		Thread t = new Thread(new Runnable(){  
			public void run(){  
				// run方法具体重写
				UUID uuid = UUID.randomUUID();
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("TransportCommandChange");
				erplog.setServerName("WmsToWcs");
				erplog.setEventName("TransportCommandChange");
				erplog.setId(uuid.toString());
				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
				erplog.setMessageId(TRANSPORTCOMMANDID);
				erplog.setSendMsg2(transportCommandChange.toJSONString());
				erplog.setReturnMsg2(doExchange);
				erplog.setResultCode(jsonObject.get("RETURNCODE").toString());
				saveMessageLog(erplog);  
			}});  
	        t.start();
        return doExchange;
    }

    /**
     * 货位使用状态更新
     *
     * @param SHELFNAME
     * @return
     */
    @Override
    public String ShelfInfoRequest(String SHELFNAME) {
    	StringBuffer stringBuffer = new StringBuffer();
    	stringBuffer.append(" ");
    	stringBuffer.append(" SELECT T.STORAGENAME SHELFNAME,T.RESOURCESTATE AVAILABLESTATE FROM STORAGE T WHERE T.STORAGENAME = ? ");
    	Object[] bindSet = {SHELFNAME};
      	 List<TransportCommand> shelfInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
      			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
        JSONObject shelfInfoRequest = createShelfInfoRequest(shelfInfo.get(0));
        String doExchange = wCSHttpUtil.httpPost(baseUrl + "/api/WCS/ShelfInfoRequest", shelfInfoRequest, null);
        org.json.JSONObject jsonObject = new org.json.JSONObject(doExchange);
        Thread t = new Thread(new Runnable(){  
			public void run(){  
				// run方法具体重写
				UUID uuid = UUID.randomUUID();
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("shelfInfoRequest");
				erplog.setServerName("WmsToWcs");
				erplog.setEventName("shelfInfoRequest");
				erplog.setId(uuid.toString());
				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
				erplog.setMessageId(SHELFNAME);
				erplog.setSendMsg2(shelfInfoRequest.toJSONString());
				erplog.setReturnMsg2(doExchange);
				erplog.setResultCode(jsonObject.get("RETURNCODE").toString());
				saveMessageLog(erplog);  
			}});  
	        t.start();
        return doExchange;
    }

    /**
     * 库存更新
     *
     * @param SHELFNAME
     * @return
     */
    @Override
    public String StockInfoChange(String SHELFNAME,String PALLETNAME){
    	StringBuffer stringBuffer = new StringBuffer();
    	stringBuffer.append(" ");
    	stringBuffer.append(" SELECT T.MATERIALPACKINGNAME PALLETNAME, T.LOCATIONNAME SHELNAME,T.MATERIALQUANTITY PRODUCTQUANTITY FROM MATERIALPACKING T ");
    	stringBuffer.append(" WHERE 1= 1 ");
    	if ( PALLETNAME != null && !"".equals(PALLETNAME)) {
    		stringBuffer.append(" AND  T.MATERIALPACKINGNAME = ? ");
    	}
    	if (SHELFNAME != null && !"".equals(SHELFNAME)) {
    		stringBuffer.append("  AND T.LOCATIONNAME = ? ");
    	}
    	Object[] bindSet = {PALLETNAME,SHELFNAME};
      	List<TransportCommand> stockInfo = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().
      			 query(stringBuffer.toString(), bindSet,new BeanPropertyRowMapper<TransportCommand>(TransportCommand.class));
      	JSONObject stockInfoChange = createStockInfoChange(stockInfo.get(0));
        String doExchange = wCSHttpUtil.httpPost(baseUrl + "/api/WCS/StockInfoChange", stockInfoChange, null);
        org.json.JSONObject jsonObject = new org.json.JSONObject(doExchange);
        Thread t = new Thread(new Runnable(){  
			public void run(){  
				// run方法具体重写
				UUID uuid = UUID.randomUUID();
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("StockInfoChange");
				erplog.setServerName("WmsToWcs");
				erplog.setEventName("StockInfoChange");
				erplog.setId(uuid.toString());
				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
				erplog.setMessageId(SHELFNAME);
				erplog.setSendMsg2(stockInfoChange.toJSONString());
				erplog.setReturnMsg2(doExchange);
				erplog.setResultCode(jsonObject.get("RETURNCODE").toString());
				saveMessageLog(erplog);  
			}});  
	        t.start();
        return doExchange;

    }

    /**
     * 搬送任务下发消息组装
     * @return
     */
    private JSONObject createTransportCommandRequest(TransportCommand transportCommand,String userId) {
//        TRANSPORTCOMMANDTYPE	是	String	搬送类型  [IN|OUT|MOVE]
//        TRANSPORTCOMMANDID	是	String	搬送指令ID
//        INDESTINATION	否	String	搬入库位
//        OUTDESTINATION	否	String	搬出库位
//        PRODUCTSPECNAME	是	String	成品料号
//        SDK_DESC	否	String	SDK规格
//        PHASE	否	String	阶段
//        PALLETNAME	是	String	成品批号/标签
//        TRAYNAME	是	String	轴心RFID/托盘ID
//        ISAGV	是	String	是否AGV搬送
//        WIDTH	否	String	宽幅(AGV使用)
//                DIAMETER	否	String	直径(AGV使用)
//        DEVIATION	否	String	偏移(AGV使用)
//                WEIGHT	否	String	重量(AGV使用)
//        PRODUCTLINE	否	String	生产线(AGV使用)
        JSONObject all = new JSONObject(true);
        JSONObject body = new JSONObject(true);
        body.put("TRANSPORTCOMMANDTYPE",transportCommand.getTRANSPORTCOMMANDTYPE());
        body.put("TRANSPORTCOMMANDID",transportCommand.getTRANSPORTCOMMANDID());
        body.put("INDESTINATION",transportCommand.getINDESTINATION());
        body.put("OUTDESTINATION",transportCommand.getOUTDESTINATION());
        body.put("PRODUCTSPECNAME",transportCommand.getPRODUCTSPECNAME());
        body.put("SDK_DESC",transportCommand.getSDK_DESC());
        body.put("PHASE",transportCommand.getPHASE());
        body.put("PALLETNAME",transportCommand.getPALLETNAME());
        body.put("TRAYNAME",transportCommand.getTRAYNAME());
        body.put("EVENTUSERNAME",userId);
        if("TRUE".equals(transportCommand.getISAGV().toUpperCase()))
        {
        	body.put("ISAGV",true);
        }else {
        	body.put("ISAGV",false);
        }
       // body.put("ISAGV",transportCommand.getISAGV());
        body.put("WIDTH",transportCommand.getWIDTH());
        body.put("DIAMETER",transportCommand.getDIAMETER());
        body.put("DEVIATION",transportCommand.getDEVIATION());
        body.put("WEIGHT",transportCommand.getWEIGHT());
        body.put("PRODUCTLINE",transportCommand.getPRODUCTLINE());
        body.put("INITILATION",transportCommand.getINITILATION());
        body.put("ENDING",transportCommand.getENDING());
        body.put("AB",transportCommand.getAB());
        body.put("PORT",transportCommand.getPORT());
        body.put("PORT",transportCommand.getPORT());
        body.put("TEMPERATURE",transportCommand.getTEMPERATURE());
        body.put("BAKINGDAYS",transportCommand.getBAKINGDAYS());
        all.put("DATA",body);
        return all;
    }

    /**
     * 搬送状态信息更新
     * @param transportCommand
     * @return
     */
    private JSONObject createTransportCommandChange(TransportCommand transportCommand) {
//        TRANSPORTCOMMANDTYPE	是	String	搬送类型  [IN|OUT|MOVE]
//        TRANSPORTCOMMANDID	是	String	搬送指令ID
//        TRANSPORTSTATE	是	String	搬送状态更新类型
//        Normal-正常
//        Prior-优先
//        Cancel-取消
//        Pause-暂停
        JSONObject all = new JSONObject(true);
        JSONObject body = new JSONObject(true);
        body.put("TRANSPORTCOMMANDTYPE",transportCommand.getTRANSPORTCOMMANDTYPE());
        body.put("TRANSPORTCOMMANDID",transportCommand.getTRANSPORTCOMMANDID());
        body.put("TRANSPORTSTATE",transportCommand.getTRANSPORTSTATE());
        all.put("DATA",body);
        return all;
    }

    /**
     * 库位状态信息更新
     * @param transportCommand
     * @return
     */
    private JSONObject createShelfInfoRequest(TransportCommand transportCommand) {
//        SHELFNAME	是	String	货位名称
//        AVAILABLESTATE	是	String	货位是否可用
//        Normal-正常
//        Close-封闭
//        Problem-问题
//        ForbidIn-禁入
//        ForbidOut-禁出
        JSONObject all = new JSONObject(true);
        JSONObject body = new JSONObject(true);
        body.put("SHELFNAME",transportCommand.getSHELFNAME());
        body.put("AVAILABLESTATE",transportCommand.getAVAILABLESTATE());
        all.put("DATA",body);
        return all;
    }

    /**
     * 库存信息变更消息组装
     * @param transportCommand
     * @return
     */
    private JSONObject createStockInfoChange(TransportCommand transportCommand) {
//        SHELFNAME	是	String	货位名称
//        PALLETNAME	是	String	成品批号/标签(多个条码用;隔开)
//        PRODUCTQUANTITY	否	String	数量
        JSONObject all = new JSONObject(true);
        JSONObject body = new JSONObject(true);
        body.put("SHELFNAME",transportCommand.getSHELFNAME());
        body.put("PALLETNAME",transportCommand.getPALLETNAME());
        body.put("PRODUCTQUANTITY",transportCommand.getPRODUCTQUANTITY());
        all.put("DATA",body);
        return all;
    }
    
    /**
     * 日志保存
     * @param log
     */
	public static void saveMessageLog(ErpMessageLog log) {

		String sql = "INSERT INTO BS_ERPMESSAGELOG(INTERFACETIME,SERVERNAME, EVENTNAME, EVENTTIMEKEY, EVENTUSER, MESSAGELOG,RESULTCODE,MESSAGEID,RESULTMESSAGE,MESSAGELOG2,RESULTMESSAGE2)\r\n"
				+ "VALUES(TO_DATE(:INTERFACETIME,'yyyy-mm-dd hh24:mi:ss'),:SERVERNAME, :EVENTNAME, :EVENTTIMEKEY, :EVENTUSER, :MESSAGELOG,:RESULTCODE,:MESSAGEID,:RESULTMESSAGE,:MESSAGELOG2,:RESULTMESSAGE2)";
 		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("SERVERNAME", log.getServerName());
		bindMap.put("EVENTNAME", log.getEventName());
		bindMap.put("EVENTTIMEKEY", log.getId());
		bindMap.put("EVENTUSER", log.getEventUser());
		bindMap.put("MESSAGEID", log.getMessageId());
		bindMap.put("INTERFACETIME", log.getInterfaceTime());
		bindMap.put("RESULTCODE", log.getResultCode());
		bindMap.put("MESSAGELOG", log.getSendMsg());// 推送ERP的json
		bindMap.put("RESULTMESSAGE", log.getReturnMsg());// 返回结果的json
		bindMap.put("MESSAGELOG2", log.getSendMsg2());// 推送ERP的json
		bindMap.put("RESULTMESSAGE2", log.getReturnMsg2());// 返回结果的json
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
	}
}