package com.cim.idm.yard.service;

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.wmspackage.name.NameServiceProxy;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

import java.util.*;

public class YardDeviceServiceImpl {

	private static Log logger = LogFactory.getLog("YardDeviceServiceImpl");

	/**
	 * B20堆场设备待入库导入数据
	 */
	public void devicePreStock(EventInfo eventInfo, String siteName, String receiveRequestName, String PONO,
			String invoiceNO, String container, String charge, String device, String deviceName, String caseNO,
			String length, String width, String height, String cross, String net, String department) throws Exception {

		logger.info("堆场设备待入库导入数据   => " + receiveRequestName + "|" + PONO + "|" + invoiceNO + "|" + container + "|"
				+ device);
//		查询是否存在主表，不存在就新增
		String querySqlString = "SELECT CONTAINER,DEVICE  FROM YARD_DEVICE WHERE CONTAINER = :CONTAINER AND DEVICE = :DEVICE";
		Map<String, String> queryMap = new HashMap<String, String>();
		queryMap.put("CONTAINER", container);
		queryMap.put("DEVICE", device);
		List<Map<String, Object>> returnListStorge = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySqlString,
				queryMap);
		if (returnListStorge != null && returnListStorge.size() > 0) {
			throw new CustomException(String.valueOf(1), "该设备：" + container + " + " + device + " 已经在库，请确认");

		} else {
			Map<String, Object> insertMap = new HashMap<String, Object>();
			String insertSql = " INSERT INTO YARD_DEVICE (SITENAME, CONTAINER, DEVICE, DEVICENAME, RECEIVEUSER, RECEIVETIME, RECEIVEREQUESTNAME"
					+ ", STOCKUSER, STOCKTIME, STOCKSTATE, SHIPREQUESTNAME, SHIPUSER, SHIPTIME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER, LASTEVENTCOMMENT"
					+ ", PONO, INVOICENO, CHARGE, CASENO, \"LENGTH\", WIDTH, HEIGHT, \"CROSS\", NET, DEPARTMENT, UNPACKING, LOCATIONNAME"
					+ ", \"EXCEPTION\", DESCRIPTION, INVENTORYRESULTS, INVENTORYDESCRIPTION, CARINFO)"
					+ " VALUES(:SITENAME, :CONTAINER, :DEVICE, :DEVICENAME, :RECEIVEUSER, :RECEIVETIME, :RECEIVEREQUESTNAME"
					+ ", NULL, NULL, :STOCKSTATE, NULL, NULL, NULL, :LASTEVENTNAME, :LASTEVENTTIMEKEY, :LASTEVENTTIME, :LASTEVENTUSER, :LASTEVENTCOMMENT"
					+ ", :PONO, :INVOICENO, :CHARGE, :CASENO, :LENGTH, :WIDTH, :HEIGHT, :CROSS, :NET, :DEPARTMENT, :UNPACKING, :LOCATIONNAME"
					+ ", :EXCEPTION, :DESCRIPTION, :INVENTORYRESULTS, NULL, NULL) ";
			insertMap.put("SITENAME", siteName);
			insertMap.put("CONTAINER", container);
			insertMap.put("DEVICE", device);
			insertMap.put("DEVICENAME", deviceName);
			insertMap.put("RECEIVEUSER", eventInfo.getEventUser());
			insertMap.put("RECEIVETIME", eventInfo.getEventTime());
			insertMap.put("RECEIVEREQUESTNAME", receiveRequestName);
			insertMap.put("STOCKSTATE", "Created");

			insertMap.put("LASTEVENTNAME", "PreStock");
			insertMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			insertMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			insertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			insertMap.put("LASTEVENTCOMMENT", "PreStock");

			insertMap.put("PONO", PONO);
			insertMap.put("INVOICENO", invoiceNO);
			insertMap.put("CHARGE", charge);
			insertMap.put("CASENO", caseNO);
			insertMap.put("LENGTH", length);
			insertMap.put("WIDTH", width);
			insertMap.put("HEIGHT", height);
			insertMap.put("CROSS", cross);
			insertMap.put("NET", net);
			insertMap.put("DEPARTMENT", department);
			insertMap.put("UNPACKING", "");
			insertMap.put("LOCATIONNAME", PONO);
			insertMap.put("EXCEPTION", "");
			insertMap.put("DESCRIPTION", "");
			insertMap.put("INVENTORYRESULTS", "正确");

			IDMFrameServiceProxy.getSqlTemplate().update(insertSql, insertMap);

			insertSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CONTAINER = :CONTAINER AND yd.DEVICE = :DEVICE";
			insertMap = new HashMap<String, Object>();
			insertMap.put("SITENAME", siteName);
			insertMap.put("CONTAINER", container);
			insertMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(insertSql, insertMap);

		}

	}

	/**
	 * B20堆场设备待入库导入数据生成入库单
	 * 
	 * @throws Exception
	 */
	public void makeReceiveRequst(EventInfo eventInfo, String siteName, String receiveRequestName, String quantity)
			throws Exception {

		logger.info("堆场设备待入库导入数据生成入库单   => " + receiveRequestName + "|" + quantity);
//		查询是否存在主表，不存在就新增
		String querySqlString = "SELECT SITENAME,DEVICERECEIVEREQUEST FROM YARD_DEVICERECEIVEREQUEST WHERE SITENAME = :SITENAME AND DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST";
		Map<String, String> queryMap = new HashMap<String, String>();
		queryMap.put("SITENAME", siteName);
		queryMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
		List<Map<String, Object>> returnListStorge = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySqlString,
				queryMap);
		if (returnListStorge != null && returnListStorge.size() > 0) {
			throw new CustomException(String.valueOf(1), "入库单：" + receiveRequestName + " 已经生成，不用重复操作");
		} else {
			Map<String, Object> insertMap = new HashMap<String, Object>();
			String insertSql = " INSERT INTO YARD_DEVICERECEIVEREQUEST (SITENAME, DEVICERECEIVEREQUEST, RECEIVEDQUANTITY, SHIPQUANTITY, CREATUSER, CREATTIME"
					+ ", DESCRIPTION, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER, LASTEVENTCOMMENT, QUANTITY, RECEIVEQUESTSTATE,STOCKTIME)"
					+ " VALUES (:SITENAME, :DEVICERECEIVEREQUEST, :RECEIVEDQUANTITY, NULL, :CREATUSER, :CREATTIME"
					+ ", NULL, :LASTEVENTNAME, :LASTEVENTTIMEKEY, :LASTEVENTTIME, :LASTEVENTUSER, :LASTEVENTCOMMENT, :QUANTITY, :RECEIVEQUESTSTATE,SYSDATE) ";

			insertMap.put("SITENAME", siteName);
			insertMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
			insertMap.put("RECEIVEDQUANTITY", quantity);
			insertMap.put("SHIPQUANTITY", 0);
			insertMap.put("CREATUSER", eventInfo.getEventUser());
			insertMap.put("CREATTIME", eventInfo.getEventTime());

			insertMap.put("LASTEVENTNAME", "Completed");
			insertMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			insertMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			insertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			insertMap.put("LASTEVENTCOMMENT", "Completed");

			insertMap.put("QUANTITY", quantity);
			insertMap.put("RECEIVEQUESTSTATE", "Completed");

			IDMFrameServiceProxy.getSqlTemplate().update(insertSql, insertMap);
		}

	}

	/**
	 * B20堆场待入库数据删除
	 * 
	 * @throws Exception
	 */
	public void removeYardPreStock(EventInfo eventInfo, Document message) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element deviceListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		String receiveRequestName = "";
		String pono = "";
		String siteName = "";
		int sum = 0;

		for (Iterator<?> iterator = deviceListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			siteName = deviceElement.getChild("SITENAME").getText();
			pono = deviceElement.getChild("PONO").getText();
			receiveRequestName = deviceElement.getChild("RECEIVEREQUESTNAME").getText();
			String container = deviceElement.getChild("CONTAINER").getText();
			String device = deviceElement.getChild("DEVICE").getText();

			logger.info("B20堆场待入库数据删除   => " + pono + "|" + container + "|" + device);

//				String querySql = "SELECT * FROM YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CONTAINER = :CONTAINER AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Created' ";
//				List<Map<String, Object>> queryResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, bindMap);

			String delSql = " DELETE FROM YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CONTAINER = :CONTAINER AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Created' ";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("CONTAINER", container);
			bindMap.put("DEVICE", device);
			int rows = IDMFrameServiceProxy.getSqlTemplate().update(delSql, bindMap);
			logger.info("B20堆场待入库数据删除delete " + rows + " rows");
			if (rows <= 0) {
				throw new CustomException(String.valueOf(1), "集装箱号：" + container + "，设备编号：" + device + " 不存在或已入库，请确认");
			}
			sum++;
		}

//		更新入库单信息，如果待入库的全部删除了，更新单据状态为 Completed
		Map<String, Object> updateMap = new HashMap<String, Object>();
		String updateSql = " UPDATE YARD_DEVICERECEIVEREQUEST yd SET yd.RECEIVEDQUANTITY = yd.RECEIVEDQUANTITY - :SUM"
				+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT"
				+ " WHERE yd.SITENAME = :SITENAME AND yd.DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST ";
		updateMap.put("SUM", sum);

		updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
		updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
		updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
		updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

		updateMap.put("SITENAME", siteName);
		updateMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
		IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);

		updateSql = " SELECT yd.RECEIVEDQUANTITY - yd.QUANTITY FROM YARD_DEVICERECEIVEREQUEST yd WHERE yd.SITENAME = ? AND yd.DEVICERECEIVEREQUEST = ? ";
		Long qPanelQty = IDMFrameServiceProxy.getSqlTemplate().queryForObject(updateSql, Long.class, siteName,
				receiveRequestName);

		if (qPanelQty <= 0) {
			updateSql = " UPDATE YARD_DEVICERECEIVEREQUEST yd SET yd.RECEIVEQUESTSTATE = 'Completed' WHERE yd.SITENAME = :SITENAME AND yd.DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST ";
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
		}

	}

	/**
	 * B20堆场入库
	 * 
	 * @throws Exception
	 */
	public void yardStockIn(EventInfo eventInfo, Document message) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element deviceListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		//String receiveRequestName = "";
		String pono = "";
		String siteName = "";
		int sum = 0;

		//生成入库单单号
		String generateMaterialReceiveRequestName = GenerateMaterialReceiveRequestName(siteName);
		for (Iterator<?> iterator = deviceListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			siteName = deviceElement.getChild("SITENAME").getText();
			pono = deviceElement.getChild("PONO").getText();
			//receiveRequestName = deviceElement.getChild("RECEIVEREQUESTNAME").getText();
			String container = deviceElement.getChild("CONTAINER").getText();
			String device = deviceElement.getChild("DEVICE").getText();
			String unpacking = deviceElement.getChild("UNPACKING").getText();
			String locationName = deviceElement.getChild("LOCATIONNAME").getText();
			String exception = deviceElement.getChild("EXCEPTION").getText();
			String description = deviceElement.getChild("DESCRIPTION").getText();
			String carinfo = deviceElement.getChild("CARINFO").getText();
			String THROUGH_STORAGE_YARD = deviceElement.getChild("THROUGH_STORAGE_YARD").getText();
			String CASENO = deviceElement.getChild("CASENO").getText();
			
			
			// 判断该库位是否存在
			String judgeLocationSql = "SELECT yl.LOCATIONNAME FROM YARD_LOCATION yl WHERE "
					+ "yl.LOCATIONNAME = :LOCATIONNAME AND yl.X = :X AND yl.Y = :Y";
			if (locationName.length() > 0) {
				String[] arr = locationName.split("-");
				Map<String, Object> locationMap = new HashMap<String,Object> ();
				locationMap.put("LOCATIONNAME", arr[0]);
				locationMap.put("X", arr[2]);
				locationMap.put("Y", arr[1]);
				List<Map<String, Object>> returnListLocation = 
						IDMFrameServiceProxy.getSqlTemplate().queryForList(judgeLocationSql,
						locationMap);
				if (returnListLocation.size() <= 0) {
					throw new CustomException(String.valueOf(1), "该存放位置：" + locationName + " 不存在，请确认是否已维护！");
				}
			}

			logger.info("B20堆场入库   => " + pono + "|" + CASENO + "|" + device);
			
			
			String sql = "INSERT INTO YARD_DEVICE\r\n" + 
					"  (SITENAME,\r\n" + 
					"   PONO,\r\n" + 
					"   DEVICE,\r\n" + 
					"   CASENO,\r\n" + 
					"   DEVICENAME,\r\n" + 
					"   LENGTH,\r\n" + 
					"   WIDTH,\r\n" + 
					"   HEIGHT,\r\n" + 
					"   CROSS,\r\n" + 
					"   NET,\r\n" + 
					"   VOLUME,\r\n" + 
					"   DEPARTMENT,\r\n" + 
					"   THROUGH_STORAGE_YARD,\r\n" + 
					"   MOVEDATE,MOVEENTRANCE,\r\n" + 
					"   RECEIVEREQUESTNAME,\r\n" + 
					"   STOCKSTATE)\r\n" + 
					"  SELECT :FSITENAME, --工厂\r\n" + 
					"         PO_NO, --PO\r\n" + 
					"         DEV_NO, --设备编号\r\n" + 
					"         CARTION_NO, --包装箱编号\r\n" + 
					"         MCNAME_THREE_CN, --设备名称\r\n" + 
					"         PACKING_DEPTH, --Length(包装尺寸cm)\r\n" + 
					"         PACKING_WIDTH, --Width(包装尺寸cm)\r\n" + 
					"         PACKING_HIGHT, -- Height(包装尺寸cm)\r\n" + 
					"         UNPACKING_WEIGHT, --Cross  (净重kg)\r\n" + 
					"         PACKING_WEIGHT, --Net(毛重kg)\r\n" + 
					"         PACKING_VOLUME, --体积\r\n" + 
					"         FAB_FACTORY, --使用部门\r\n" + 
					"         THROUGH_STORAGE_YARD, --是否过堆场\r\n" + 
					"         TO_DATE(MOVE_IN_DATE_PLAN,'YYYY/MM/DD'), MOVE_IN_ENTRANCE_NO,\r\n" + 
					"         :RECEIVEREQUESTNAME,\r\n" + 
					"         'Created'\r\n" + 
					"    FROM PACKING_LIST T WHERE T.DEV_NO = :DEV_NO AND T.CARTION_NO = :CARTION_NO AND (T.WMSRECEIVE_FLAG IS  NULL OR T.WMSRECEIVE_FLAG <> 'Y')";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("FSITENAME", siteName);
			hashMap.put("RECEIVEREQUESTNAME", generateMaterialReceiveRequestName);
			hashMap.put("DEV_NO", device);
			hashMap.put("CARTION_NO", CASENO);
			int update = IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap);
			if (update >= 1) {//更新接收标识
				String receiveSql = " UPDATE PACKING_LIST T\r\n" + 
						"       SET T.WMSRECEIVE_FLAG = 'Y', T.WMSRECEIVE_TIME = SYSDATE\r\n" + 
						"     WHERE T.DEV_NO = :DEV_NO\r\n" + 
						"       AND T.CARTION_NO = :CARTION_NO";
				IDMFrameServiceProxy.getSqlTemplate().update(receiveSql, hashMap);
				
				// 更新帆软数据库
				String updateSql = "UPDATE PACKING_LIST@yardToFR pl SET pl.WMS_FLAG = 'Y' "
						+ "WHERE pl.DEV_NO = :DEV_NO  AND  pl.CARTION_NO = :CARTION_NO";
//				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);
			}
			
			/*
			 * <SITENAME>B20</SITENAME> <CONTAINER />
			 * <DEVICE>KAMMM0210086CCCCCCCCCCC</DEVICE>
			 * <RECEIVEREQUESTNAME>1700774432.999999999999999999999999999997</
			 * RECEIVEREQUESTNAME> <PONO>TEST-123</PONO> <CASENO>510</CASENO>
			 * <UNPACKING>True</UNPACKING> <LOCATIONNAME>12</LOCATIONNAME>
			 * <EXCEPTION>12</EXCEPTION> <DESCRIPTION>12</DESCRIPTION> <CARINFO>12</CARINFO>
			 * <THROUGH_STORAGE_YARD>是</THROUGH_STORAGE_YARD>
			 */
//			logger.info("堆场设备待入库导入数据生成入库单   => " + siteName + "|" + device+"|"+CASENO);
//
//			
//			if(receiveRequestName == null || receiveRequestName =="") {
//				Map<String, Object> insertMap = new HashMap<String, Object>();
//				String insertSql = " INSERT INTO YARD_DEVICERECEIVEREQUEST (SITENAME, DEVICERECEIVEREQUEST, RECEIVEDQUANTITY, SHIPQUANTITY, CREATUSER, CREATTIME"
//						+ ", DESCRIPTION, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER, LASTEVENTCOMMENT, QUANTITY, RECEIVEQUESTSTATE)"
//						+ " VALUES (:SITENAME,:DEVICERECEIVEREQUEST, :RECEIVEDQUANTITY, NULL, :CREATUSER, :CREATTIME"
//						+ ", NULL, :LASTEVENTNAME, :LASTEVENTTIMEKEY, :LASTEVENTTIME, :LASTEVENTUSER, :LASTEVENTCOMMENT, :QUANTITY, :RECEIVEQUESTSTATE) ";
//				
//				receiveRequestName=TimeStampUtil.getCurrentEventTimeKey();
//				insertMap.put("SITENAME", siteName);
//				insertMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
//				insertMap.put("RECEIVEDQUANTITY", 0);
//				insertMap.put("SHIPQUANTITY", 0);
//				insertMap.put("CREATUSER", eventInfo.getEventUser());
//				insertMap.put("CREATTIME", eventInfo.getEventTime());
//
//				insertMap.put("LASTEVENTNAME", "Created");
//				insertMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
//				insertMap.put("LASTEVENTTIME", eventInfo.getEventTime());
//				insertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
//				insertMap.put("LASTEVENTCOMMENT", "Created");
//				
//				insertMap.put("QUANTITY", 0);
//				insertMap.put("RECEIVEQUESTSTATE", "Created");
//				
//				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, insertMap);
//			}else {
//				String UPDDEVICERECEIVEREQUEST="UPDATE YARD_DEVICERECEIVEREQUEST SET RECEIVEDQUANTITY=RECEIVEDQUANTITY+1 WHERE SITENAME = :SITENAME AND DEVICE = :DEVICE AND CASENO=:CASENO";
//				Map<String, String> updMap = new HashMap<String, String>();
//				updMap.put("SITENAME", siteName); 
//				updMap.put("DEVICE", device); 
//				updMap.put("CASENO", CASENO); 
//				IDMFrameServiceProxy.getSqlTemplate().update(UPDDEVICERECEIVEREQUEST, updMap);
//			}

			String updateSql = " UPDATE YARD_DEVICE yd SET yd.STOCKSTATE = 'Stocked', yd.STOCKINTYPE = '正常入库', yd.UNPACKING = :UNPACKING,yd.LOCATIONNAME = :LOCATIONNAME,yd.\"EXCEPTION\" = :EXCEPTION,yd.DESCRIPTION = :DESCRIPTION, yd.CARINFO = :CARINFO"
					+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT,YD.STOCKTIME = SYSDATE,YD.STOCKUSER = :LASTEVENTUSER"
					+ " WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Created' ";
			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("UNPACKING", unpacking);
			updateMap.put("LOCATIONNAME", locationName);
			updateMap.put("EXCEPTION", exception);
			updateMap.put("DESCRIPTION", description);
			updateMap.put("CARINFO", carinfo);

			updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
			updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CASENO);
			updateMap.put("DEVICE", device);
			int rows = IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			if (rows <= 0) {
				throw new CustomException(String.valueOf(1),"CASENO：" + CASENO + "，设备编号：" + device + " 不存在或已入库，请确认");
			}
			sum++;

			updateSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE";
			updateMap = new HashMap<String, Object>();
			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CASENO);
			updateMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			
			// 更新库位使用状态
			
			String[] arr = locationName.split("-");
			String updateLocationSql = "UPDATE YARD_LOCATION yl SET yl.USESTATE = 'Y' WHERE yl.SITENAME = :SITENAME AND yl.LOCATIONNAME = :LOCATIONNAME AND yl.X = :X AND yl.Y = :Y";
			Map<String, Object> updateLocationMap = new HashMap<String, Object>();
			updateLocationMap.put("SITENAME", siteName);
			updateLocationMap.put("LOCATIONNAME", arr[0]);
			updateLocationMap.put("X", arr[1]);
			updateLocationMap.put("Y", arr[2]);
			IDMFrameServiceProxy.getSqlTemplate().update(updateLocationSql, updateLocationMap);
		}
		//receiveRequestName = TimeStampUtil.getCurrentEventTimeKey();
		makeReceiveRequst(eventInfo, siteName, generateMaterialReceiveRequestName, Integer.toString(sum));

//		更新入库单信息，如果待入库的全部入库了，更新单据状态为 Completed
//		Map<String, Object> updateMap = new HashMap<String, Object>();
//		String updateSql = " UPDATE YARD_DEVICERECEIVEREQUEST yd SET yd.QUANTITY = yd.QUANTITY + :SUM"
//				+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT"
//				+ " WHERE yd.SITENAME = :SITENAME AND yd.DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST ";
//		updateMap.put("SUM", sum);
//		updateMap.put("STOCKUSER", eventInfo.getEventUser());
//		updateMap.put("STOCKTIME", eventInfo.getEventTime());
//
//		updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
//		updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
//		updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
//		updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
//		updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
//
//		updateMap.put("SITENAME", siteName);
//		updateMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
//		IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
//
//		updateSql = " SELECT yd.RECEIVEDQUANTITY - yd.QUANTITY FROM YARD_DEVICERECEIVEREQUEST yd WHERE yd.SITENAME = ? AND yd.DEVICERECEIVEREQUEST = ? ";
//		Long qPanelQty = IDMFrameServiceProxy.getSqlTemplate().queryForObject(updateSql, Long.class, siteName,
//				receiveRequestName);
//
//		if (qPanelQty <= 0) {
//			updateSql = " UPDATE YARD_DEVICERECEIVEREQUEST yd SET yd.RECEIVEQUESTSTATE = 'Completed' WHERE yd.SITENAME = :SITENAME AND yd.DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST ";
//			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
//		}

	}

	public String yardDirectStockInShip() {
		return "ZB-" + System.currentTimeMillis();
	}
	
	/**
	 * 直搬入库
	 * @param eventInfo
	 * @param message
	 * @throws Exception
	 */
	public void yardDirectStockIn(EventInfo eventInfo, Document message,String shipRequestName) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element deviceListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		//String receiveRequestName = "";
		String pono = "";
		String siteName = "";
		int sum = 0;

		//生成入库单单号
		String generateMaterialReceiveRequestName = GenerateMaterialReceiveRequestName(siteName);
		
		long currentTimeMillis = System.currentTimeMillis();
		for (Iterator<?> iterator = deviceListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			siteName = deviceElement.getChild("SITENAME").getText();
			String device = deviceElement.getChild("DEVICE").getText();
			String CASENO = deviceElement.getChild("CASENO").getText();

			logger.info("B20堆场入库   => " + pono + "|" + CASENO + "|" + device);
			
			String sql = "INSERT INTO YARD_DEVICE\r\n" + 
					"  (SITENAME,\r\n" + 
					"   PONO,\r\n" + 
					"   DEVICE,\r\n" + 
					"   CASENO,\r\n" + 
					"   DEVICENAME,\r\n" + 
					"   LENGTH,\r\n" + 
					"   WIDTH,\r\n" + 
					"   HEIGHT,\r\n" + 
					"   CROSS,\r\n" + 
					"   NET,\r\n" + 
					"   VOLUME,\r\n" +
					"   DEPARTMENT,\r\n" + 
					"   THROUGH_STORAGE_YARD,\r\n" + 
					"   MOVEDATE,\r\n" + 
					"   RECEIVEREQUESTNAME,\r\n" + 
					"   STOCKSTATE,MOVEENTRANCE)\r\n" + 
					"  SELECT :FSITENAME, --工厂\r\n" + 
					"         PO_NO, --PO\r\n" + 
					"         DEV_NO, --设备编号\r\n" + 
					"         CARTION_NO, --包装箱编号\r\n" + 
					"         MCNAME_THREE_CN, --设备名称\r\n" + 
					"         PACKING_DEPTH, --Length(包装尺寸cm)\r\n" + 
					"         PACKING_WIDTH, --Width(包装尺寸cm)\r\n" + 
					"         PACKING_HIGHT, -- Height(包装尺寸cm)\r\n" + 
					"         UNPACKING_WEIGHT, --Cross  (净重kg)\r\n" + 
					"         PACKING_WEIGHT, --Net(毛重kg)\r\n" + 
					"         PACKING_VOLUME, --体积\r\n" + 
					"         FAB_FACTORY, --使用部门\r\n" + 
					"         THROUGH_STORAGE_YARD, --是否过堆场\r\n" + 
					"         TO_DATE(MOVE_IN_DATE_PLAN,'YYYY/MM/DD'),\r\n" + 
					"         :RECEIVEREQUESTNAME,\r\n" + 
					"         'Created',MOVE_IN_ENTRANCE_NO\r\n" + 
					"    FROM PACKING_LIST T WHERE T.DEV_NO = :DEV_NO AND T.CARTION_NO = :CARTION_NO AND (T.WMSRECEIVE_FLAG IS  NULL OR T.WMSRECEIVE_FLAG <> 'Y')";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("FSITENAME", siteName);
			hashMap.put("RECEIVEREQUESTNAME", generateMaterialReceiveRequestName);
			hashMap.put("DEV_NO", device);
			hashMap.put("CARTION_NO", CASENO);
			int update = IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap);
			if (update >= 1) {//更新接收标识
				String receiveSql = " UPDATE PACKING_LIST T\r\n" + 
						"       SET T.WMSRECEIVE_FLAG = 'Y', T.WMSRECEIVE_TIME = SYSDATE\r\n" + 
						"     WHERE T.DEV_NO = :DEV_NO\r\n" + 
						"       AND T.CARTION_NO = :CARTION_NO";
				IDMFrameServiceProxy.getSqlTemplate().update(receiveSql, hashMap);
				
				// 更新帆软数据库
//				String updateSql = "UPDATE PACKING_LIST@yardToFR pl SET pl.WMS_FLAG = 'Y' "
//						+ "WHERE pl.DEV_NO = :DEV_NO AND pl.CARTION_NO = :CARTION_NO";
//				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);
			}
			// 入库状态更新
			String updateCreatedSql = " UPDATE YARD_DEVICE yd SET yd.STOCKSTATE = 'Stocked',yd.UNPACKING = :UNPACKING,yd.LOCATIONNAME = :LOCATIONNAME,yd.\"EXCEPTION\" = :EXCEPTION,yd.DESCRIPTION = :DESCRIPTION, yd.CARINFO = :CARINFO, yd.STOCKINTYPE = '直搬入库'"
					+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT,YD.STOCKTIME = SYSDATE,YD.STOCKUSER = :LASTEVENTUSER"
					+ " WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Created' ";
			Map<String, Object> updateCreatedMap = new HashMap<String, Object>();
			updateCreatedMap.put("UNPACKING", "");
			updateCreatedMap.put("LOCATIONNAME", "");
			updateCreatedMap.put("EXCEPTION", "");
			updateCreatedMap.put("DESCRIPTION", "");
			updateCreatedMap.put("CARINFO", "");
			updateCreatedMap.put("LASTEVENTNAME", eventInfo.getEventName());
			updateCreatedMap.put("LASTEVENTTIMEKEY", currentTimeMillis);
			updateCreatedMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateCreatedMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateCreatedMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			updateCreatedMap.put("SITENAME", siteName);
			updateCreatedMap.put("CASENO", CASENO);
			updateCreatedMap.put("DEVICE", device);
			int createdrows = IDMFrameServiceProxy.getSqlTemplate().update(updateCreatedSql, updateCreatedMap);
			if (createdrows <= 0) {
				throw new CustomException(String.valueOf(1),"CASENO：" + CASENO + "，设备编号：" + device + " 不存在或已入库，请确认");
			}
			
			// 直搬插入历史
			String updateDirSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE";
			Map<String, Object> updateDirMap = new HashMap<String, Object>();
			updateDirMap.put("SITENAME", siteName);
			updateDirMap.put("CASENO", CASENO);
			updateDirMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(updateDirSql, updateDirMap);
			
			// 出库更新状态
			String updateSql = " UPDATE YARD_DEVICE yd SET yd.STOCKSTATE = 'StockOut',SHIPREQUESTNAME = :SHIPREQUESTNAME,yd.UNPACKING = :UNPACKING,yd.LOCATIONNAME = :LOCATIONNAME,yd.\"EXCEPTION\" = :EXCEPTION,yd.DESCRIPTION = :DESCRIPTION, yd.CARINFO = :CARINFO"
					+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT,SHIPTIME = sysdate ,YD.STOCKUSER = :LASTEVENTUSER"
					+ " WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Stocked' ";
			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("UNPACKING", "");
			updateMap.put("LOCATIONNAME", "");
			updateMap.put("EXCEPTION", "");
			updateMap.put("DESCRIPTION", "");
			updateMap.put("CARINFO", "");
			updateMap.put("SHIPREQUESTNAME", shipRequestName);
			updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
			updateMap.put("LASTEVENTTIMEKEY", currentTimeMillis);
			updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CASENO);
			updateMap.put("DEVICE", device);
			int rows = IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			if (rows <= 0) {
				throw new CustomException(String.valueOf(1),"CASENO：" + CASENO + "，设备编号：" + device + " 不存在或已入库，请确认");
			}
			sum++;

			updateSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE";
			updateMap = new HashMap<String, Object>();
			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CASENO);
			updateMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);

		}
		makeReceiveRequst(eventInfo, siteName, generateMaterialReceiveRequestName, Integer.toString(sum));
		
		
		//直搬出库单
		String Insertsql="INSERT INTO YARD_DEVICESHIPREQUEST(SITENAME,DEVICESHIREQUEST,SHIPQUANTITY,CREATUSER,CREATTIME,LASTEVENTNAME,LASTEVENTTIMEKEY,LASTEVENTTIME,LASTEVENTUSER,LASTEVENTCOMMENT,SHIPSTATE)"+
				"VALUES(:SITENAME,:DEVICESHIREQUEST,:SHIPQUANTITY,:CREATUSER,:CREATTIME,:LASTEVENTNAME,:LASTEVENTTIMEKEY,:LASTEVENTTIME,:LASTEVENTUSER,:LASTEVENTCOMMENT,'Completed')";
				Map<String, Object> InsertMap = new HashMap<String, Object>();
				InsertMap.put("SITENAME", siteName);
				InsertMap.put("DEVICESHIREQUEST", shipRequestName);
				InsertMap.put("SHIPQUANTITY", sum);
				InsertMap.put("CREATUSER", eventInfo.getEventUser());
				InsertMap.put("CREATTIME",eventInfo.getEventTime());
				InsertMap.put("LASTEVENTNAME", "Completed");
				InsertMap.put("LASTEVENTTIMEKEY", currentTimeMillis);
				InsertMap.put("LASTEVENTTIME", new Date());
				InsertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
				InsertMap.put("LASTEVENTCOMMENT","Completed");
				IDMFrameServiceProxy.getSqlTemplate().update(Insertsql, InsertMap);	
		
	}
	
	/**
	 * B20堆场更新PO和ERP关系看板
	 * 
	 * @throws Exception
	 */
	public void yardUpdatePOAndERP(EventInfo eventInfo, Document message) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element poListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		for (Iterator<?> iterator = poListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			String siteName = deviceElement.getChild("SITENAME").getText();
			String pono = deviceElement.getChild("PONO").getText();
			String preReceiveQty = deviceElement.getChild("PRERECEIVEQTY").getText();		
			String orderQty = deviceElement.getChild("ORDERQTY").getText();
			String isOrPass = deviceElement.getChild("ISORPASS").getText();
			// 判断PONO是否存在  插入 | 更新
			String judgeSql = "SELECT ype.PONO FROM YARD_PO_ERP ype WHERE ype.PONO = :PONO";
			Map<String, Object> judgeMap = new HashMap<String, Object>();
			judgeMap.put("PONO", pono);
			
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(judgeSql, judgeMap);
			
			String updateSql = "";
			
			
			if (sqlResult.size() == 0) {
				updateSql = "INSERT INTO YARD_PO_ERP(PONO,PRERECEIVEQTY,ORDERQTY,ISORPASS) VALUES(:PONO, :PRERECEIVEQTY, :ORDERQTY, :ISORPASS)";
			}else {
				updateSql = "UPDATE YARD_PO_ERP SET PRERECEIVEQTY = :PRERECEIVEQTY, ORDERQTY = :ORDERQTY, ISORPASS = :ISORPASS WHERE PONO = :PONO";
			}
			
			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("PONO", pono);
			updateMap.put("PRERECEIVEQTY", preReceiveQty);
			updateMap.put("ORDERQTY", orderQty);
			updateMap.put("ISORPASS", isOrPass);

			//updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
			//updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			//updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			//updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			//updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);

		}
	}


	/**
	 * B20堆场库位移动
	 * 
	 * @throws Exception
	 */
	public void yardChangeLocation(EventInfo eventInfo, Document message, String toLocationName) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element deviceListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		String receiveRequestName = "";
		String pono = "";
		String siteName = "";

		for (Iterator<?> iterator = deviceListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			siteName = deviceElement.getChild("SITENAME").getText();
			pono = deviceElement.getChild("PONO").getText();
			receiveRequestName = deviceElement.getChild("RECEIVEREQUESTNAME").getText();
			String container = deviceElement.getChild("CONTAINER").getText();
			String device = deviceElement.getChild("DEVICE").getText();
			String toLocation = deviceElement.getChild("TOLOCATIONNAME").getText();
			String CaseNo = deviceElement.getChild("CASENO").getText();

			logger.info("B20堆场库位移动   => " + pono + "|" + CaseNo + "|" + device);

			String updateSql = " UPDATE YARD_DEVICE yd SET yd.LOCATIONNAME = :TOLOCATIONNAME"
					+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT"
					+ " WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE AND yd.STOCKSTATE = 'Stocked' ";
			Map<String, Object> updateMap = new HashMap<String, Object>();

			if (StringUtils.isEmpty(toLocationName)) {
				if (StringUtils.isEmpty(toLocation)) {
					throw new CustomException(String.valueOf(1), "集装箱号：" + container + "，设备编号：" + device + " 未填写要移动至的库位");
				} else {
					updateMap.put("TOLOCATIONNAME", toLocation);
				}
			} else {
				updateMap.put("TOLOCATIONNAME", toLocationName);
			}

			updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
			updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CaseNo);
			updateMap.put("DEVICE", device);
			int rows = IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			if (rows <= 0) {
				throw new CustomException(String.valueOf(1), "集装箱号：" + container + "，设备编号：" + device + " 不在库，请确认");
			}

			updateSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE";
			updateMap = new HashMap<String, Object>();
			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CaseNo);
			updateMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);

		}
	}

	/**
	 * B20堆场在库管理
	 * 
	 * @throws Exception
	 */
	public void yardStockInChange(EventInfo eventInfo, Document message) throws Exception {
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element deviceListElement = bodyElement.getChild("ORIGINALDEVICELIST");

		String pono = "";
		String siteName = "";

		for (Iterator<?> iterator = deviceListElement.getChildren().iterator(); iterator.hasNext();) {

			Element deviceElement = (Element) iterator.next();
			siteName = deviceElement.getChild("SITENAME").getText();
			pono = deviceElement.getChild("PONO").getText();
			String container = deviceElement.getChild("CONTAINER").getText();
			String device = deviceElement.getChild("DEVICE").getText();
			String unpacking = deviceElement.getChild("UNPACKING").getText();
			String locationName = deviceElement.getChild("LOCATIONNAME").getText();
			String exception = deviceElement.getChild("EXCEPTION").getText();
			String description = deviceElement.getChild("DESCRIPTION").getText();
			String CaseNo = deviceElement.getChild("CASENO").getText();
			String CARINFO = deviceElement.getChild("CARINFO").getText();
			logger.info("B20堆场在库管理   => " + pono + "|" + CaseNo + "|" + device);

			String updateSql = " UPDATE YARD_DEVICE yd SET yd.UNPACKING = :UNPACKING,yd.LOCATIONNAME = :LOCATIONNAME,yd.\"EXCEPTION\" = :EXCEPTION,yd.DESCRIPTION = :DESCRIPTION,CARINFO = :CARINFO"
					+ ",yd.LASTEVENTNAME = :LASTEVENTNAME,yd.LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,yd.LASTEVENTTIME = :LASTEVENTTIME,yd.LASTEVENTUSER = :LASTEVENTUSER,yd.LASTEVENTCOMMENT = :LASTEVENTCOMMENT"
					+ " WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE ";
			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("UNPACKING", unpacking);
			updateMap.put("LOCATIONNAME", locationName);
			updateMap.put("EXCEPTION", exception);
			updateMap.put("DESCRIPTION", description);
			updateMap.put("CARINFO", CARINFO);

			updateMap.put("LASTEVENTNAME", eventInfo.getEventName());
			updateMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
			updateMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());

			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CaseNo);
			updateMap.put("DEVICE", device);
			int rows = IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			if (rows <= 0) {
				throw new CustomException(String.valueOf(1), "CASENO：" + CaseNo + "，设备编号：" + device + " 不存在，请确认");
			}

			updateSql = "insert into YARD_DEVICEHISTORY select * from YARD_DEVICE yd WHERE yd.SITENAME = :SITENAME AND yd.CASENO = :CASENO AND yd.DEVICE = :DEVICE";
			updateMap = new HashMap<String, Object>();
			updateMap.put("SITENAME", siteName);
			updateMap.put("CASENO", CaseNo);
			updateMap.put("DEVICE", device);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);

		}

	}

	/**
	 * B20堆场出库冲销
	 * 
	 * @throws Exception
	 */
	public void RemoveForYardUn(EventInfo eventInfo, String sitename, String pono, String ShipRequestName,
			String Invoiceno, String Caseno) throws Exception {

		logger.info(" 先判断是否能出库冲销");
		String selectShipQuerySql = "SELECT SHIPQUANTITY FROM YARD_DEVICESHIPREQUEST WHERE DEVICESHIREQUEST=:DEVICESHIREQUEST AND SHIPSTATE = 'Completed' ";
		Map<String, Object> selectMap = new HashMap<>();
		selectMap.put("DEVICESHIREQUEST", ShipRequestName);
		List<Map<String, Object>> returnListStorge = IDMFrameServiceProxy.getSqlTemplate()
				.queryForList(selectShipQuerySql, selectMap);
		if (returnListStorge == null || returnListStorge .size() <= 0) {
			throw new CustomException(String.valueOf(2),"单据不存在，或者不为已出库");
		}
		Map<String, Object> firstMap = returnListStorge.get(0);
		int shipQuantityNumber = Integer.parseInt(firstMap.get("SHIPQUANTITY").toString());

		String selectShipQuerySql2 = "SELECT RECEIVEDQUANTITY,SHIPQUANTITY,QUANTITY FROM YARD_DEVICERECEIVEREQUEST WHERE DEVICERECEIVEREQUEST=:DEVICERECEIVEREQUEST";
		Map<String, Object> selectMap2 = new HashMap<>();
		selectMap2.put("DEVICERECEIVEREQUEST", pono);
		List<Map<String, Object>> returnListStorge2 = IDMFrameServiceProxy.getSqlTemplate()
				.queryForList(selectShipQuerySql2, selectMap2);
		if  (returnListStorge2 != null && returnListStorge2.size() > 0) {
			Map<String, Object> firstMap2 = returnListStorge2.get(0);
			Object shipQuantity = firstMap2.get("SHIPQUANTITY");
			if (shipQuantity == null) {
				shipQuantity = "0";
			}
			int shipQuantityNumber2 = Integer.parseInt(shipQuantity.toString());
			if (shipQuantityNumber2 - shipQuantityNumber < 0) {
				throw new CustomException(String.valueOf(1), "出库冲销数量大于出库数量   " + "|");
			}
			String UpdateYARDDEVICERECEIVEREQUEST = "UPDATE YARD_DEVICERECEIVEREQUEST SET SHIPQUANTITY=:SHIPQUANTITY,LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT WHERE DEVICERECEIVEREQUEST=:DEVICERECEIVEREQUEST";
			Map<String, Object> UpdateYARDDEVICERECEIVEREQUESTMap = new HashMap<String, Object>();
			UpdateYARDDEVICERECEIVEREQUESTMap.put("SHIPQUANTITY", shipQuantityNumber2 - shipQuantityNumber);
			UpdateYARDDEVICERECEIVEREQUESTMap.put("LASTEVENTNAME", "RemoveYardUn");
			UpdateYARDDEVICERECEIVEREQUESTMap.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
			UpdateYARDDEVICERECEIVEREQUESTMap.put("LASTEVENTTIME", new Date());
			UpdateYARDDEVICERECEIVEREQUESTMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			UpdateYARDDEVICERECEIVEREQUESTMap.put("LASTEVENTCOMMENT", "RemoveYardUn");
			UpdateYARDDEVICERECEIVEREQUESTMap.put("DEVICERECEIVEREQUEST", pono);
			IDMFrameServiceProxy.getSqlTemplate().update(UpdateYARDDEVICERECEIVEREQUEST, UpdateYARDDEVICERECEIVEREQUESTMap);
		}
		
		//判断是否存在冲销区库区
		String sql = "SELECT 1 FROM YARD_LOCATION T WHERE T.LOCATIONNAME = '冲销区'";
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, firstMap);
		if (queryForList == null || queryForList.size() <= 0) {
			throw new CustomException(String.valueOf(1),"请维护  冲销区  库区");
		}
		
		// 判断是直搬还是堆场
		/*
		 * String Selectsql =
		 * "SELECT yd.THROUGH_STORAGE_YARD FROM YARD_DEVICE yd WHERE yd.SHIPREQUESTNAME = :SHIPREQUESTNAME"
		 * ; Map<String, Object> InsertMap2 = new HashMap<String, Object>();
		 * InsertMap2.put("SHIPREQUESTNAME", ShipRequestName); List<Map<String, Object>>
		 * returnList =
		 * IDMFrameServiceProxy.getSqlTemplate().queryForList(Selectsql,InsertMap2);
		 * 
		 * Map<String, Object> map = returnList.get(0); String type =
		 * map.get("THROUGH_STORAGE_YARD").toString();
		 * 
		 * if (type.equals("直入")) {
		 * 
		 * }
		 */

		logger.info(" 堆场设备出库 冲销");
		String UpdateShipState = "UPDATE YARD_DEVICE SET STOCKSTATE=:STOCKSTATE, STOCKINTYPE=:STOCKINTYPE, SHIPUSER=null,SHIPTIME=null,LOCATIONNAME = '冲销区', STOCKTIME = :STOCKTIME, "
				+ " LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME";
		Map<String, Object> InsertMap = new HashMap<String, Object>();
		InsertMap.put("STOCKSTATE", "Stocked");
		InsertMap.put("LASTEVENTNAME", "RemoveYardUn");
		InsertMap.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
		InsertMap.put("LASTEVENTTIME", new Date());
		InsertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		InsertMap.put("LASTEVENTCOMMENT", "RemoveYardUn");
		InsertMap.put("SHIPREQUESTNAME", ShipRequestName);
		//InsertMap.put("CASENO", Caseno);
		InsertMap.put("STOCKINTYPE", "冲销入库");
		InsertMap.put("STOCKTIME", new Date());
		IDMFrameServiceProxy.getSqlTemplate().update(UpdateShipState, InsertMap);

		/*
		 * String Selectsql =
		 * "SELECT SITENAME,CONTAINER,DEVICE,PONO,INVOICENO ,CASENO FROM YARD_DEVICE WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME "
		 * ; Map<String, Object> InsertMap2 = new HashMap<String, Object>();
		 * InsertMap2.put("SHIPREQUESTNAME", ShipRequestName); List<Map<String, Object>>
		 * returnList = IDMFrameServiceProxy.getSqlTemplate().queryForList(Selectsql,
		 * InsertMap2); Map<String, Object> map = returnList.get(0); String SITENAME =
		 * (String) map.get("SITENAME"); String CASENO = (String) map.get("CASENO");
		 * String DEVICE = (String) map.get("DEVICE");
		 */
		
		//logger.info(" 堆场设备变更Device表历史记录 " + SITENAME + "," + CASENO + "," + DEVICE);
		String Insertsql = "insert into " + " YARD_DEVICEHISTORY "
				+ "select * from YARD_DEVICE t where t.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		Map<String, Object> insertMap2 = new HashMap<String, Object>();
		//insertMap2.put("SITENAME", SITENAME);
		insertMap2.put("SHIPREQUESTNAME", ShipRequestName);
		//insertMap2.put("DEVICE", DEVICE);
		IDMFrameServiceProxy.getSqlTemplate().update(Insertsql, insertMap2);

		String UpdateShipSql = "UPDATE YARD_DEVICESHIPREQUEST SET LASTEVENTNAME=:LASTEVENTNAME,SHIPSTATE = 'Reserve', LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT WHERE DEVICESHIREQUEST=:DEVICESHIREQUEST";
		Map<String, Object> UpdateMap = new HashMap<String, Object>();
		UpdateMap.put("LASTEVENTNAME", "RemoveYardUn");
		UpdateMap.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
		UpdateMap.put("LASTEVENTTIME", new Date());
		UpdateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		UpdateMap.put("LASTEVENTCOMMENT", "RemoveYardUn");
		UpdateMap.put("DEVICESHIREQUEST", ShipRequestName);
		IDMFrameServiceProxy.getSqlTemplate().update(UpdateShipSql, UpdateMap);

	}
	
	/**
	 * B20堆场出库退库
	 * 
	 * @throws Exception
	 */
	public void ReturnForYardStock(EventInfo eventInfo, String sitename, String receiveRequestName) throws Exception {

		logger.info(" 先判断是否能出库退库");
		String selectShipQuerySql = "SELECT RECEIVEDQUANTITY FROM YARD_DEVICERECEIVEREQUEST yd WHERE yd.SITENAME = :SITENAME AND yd.DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST";
		Map<String, Object> selectMap = new HashMap<>();
		selectMap.put("SITENAME", sitename);
		selectMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
		List<Map<String, Object>> returnListStorge = IDMFrameServiceProxy.getSqlTemplate()
				.queryForList(selectShipQuerySql, selectMap);
		if (returnListStorge == null || returnListStorge .size() <= 0) {
			throw new CustomException(String.valueOf(2),"单据不存在");
		}

		logger.info(" 堆场设备出库 退库，退库至虚拟库位T1");
		String UpdateShipState = "UPDATE YARD_DEVICE SET STOCKSTATE=:STOCKSTATE, STOCKINTYPE=:STOCKINTYPE, STOCKTIME = :STOCKTIME, LOCATIONNAME = 'T1',"
				+ " LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME";
		Map<String, Object> InsertMap = new HashMap<String, Object>();
		InsertMap.put("STOCKSTATE", "Stocked");
		InsertMap.put("LASTEVENTNAME", "ReturnYardStock");
		InsertMap.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
		InsertMap.put("LASTEVENTTIME", new Date());
		InsertMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		InsertMap.put("LASTEVENTCOMMENT", "ReturnYardStock");
		InsertMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		
		InsertMap.put("STOCKINTYPE", "退库入库");
		InsertMap.put("STOCKTIME", new Date());
		IDMFrameServiceProxy.getSqlTemplate().update(UpdateShipState, InsertMap);

		
		String Insertsql = "insert into " + " YARD_DEVICEHISTORY "
				+ "select * from YARD_DEVICE t where t.SITENAME =:SITENAME AND t.RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME";
		Map<String, Object> insertMap2 = new HashMap<String, Object>();
		insertMap2.put("SITENAME", sitename);
		insertMap2.put("RECEIVEREQUESTNAME", receiveRequestName);
				IDMFrameServiceProxy.getSqlTemplate().update(Insertsql, insertMap2);

		String UpdateShipSql = "UPDATE YARD_DEVICERECEIVEREQUEST SET LASTEVENTNAME=:LASTEVENTNAME,RECEIVEQUESTSTATE = 'Completed', LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER,LASTEVENTCOMMENT=:LASTEVENTCOMMENT WHERE SITENAME = :SITENAME AND DEVICERECEIVEREQUEST = :DEVICERECEIVEREQUEST";
		Map<String, Object> UpdateMap = new HashMap<String, Object>();
		UpdateMap.put("SITENAME", sitename);
		UpdateMap.put("LASTEVENTNAME", "ReturnYardStock");
		UpdateMap.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
		UpdateMap.put("LASTEVENTTIME", new Date());
		UpdateMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		UpdateMap.put("LASTEVENTCOMMENT", "ReturnYardStock");
		UpdateMap.put("DEVICERECEIVEREQUEST", receiveRequestName);
		IDMFrameServiceProxy.getSqlTemplate().update(UpdateShipSql, UpdateMap);

	}

	/**
	 * B20堆场盘点
	 * 
	 * @throws Exception
	 */
	public void SaveForYardInventory(EventInfo eventInfo, Document doc) {

		Element root = doc.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		// 获取单据明细行
		List<Element> detail = root.getChild("Body").getChild("DETAILS").getChildren();
		
		String siteName = bodyElement.getChildText("SITENAME");
		// 单据号
		String checkNo = bodyElement.getChildText("CHECKNO");

		for (Element element : detail) {
			
			 String caseNo = element.getChildText("CASENO");
			 String device = element.getChildText("DEVICE");
			 String checkResult = element.getChildText("INVENTORYRESULTS");
			 String checkRemark = element.getChildText("INVENTORYDESCRIPTION");
			 String checker = element.getChildText("CHECKER");
			
			 // 更新设备表
//			 String InsertSql = "  UPDATE YARD_DEVICE SET INVENTORYRESULTS= :INVENTORYRESULTS, INVENTORYDESCRIPTION = :INVENTORYDESCRIPTION , LASTEVENTNAME = :LASTEVENTNAME, LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY,LASTEVENTTIME = :LASTEVENTTIME, LASTEVENTUSER = :LASTEVENTUSER, LASTEVENTCOMMENT = :LASTEVENTCOMMENT "
//					 + " WHERE SITENAME = :SITENAME AND CASENO = :CASENO AND DEVICE= :DEVICE";
//			 Map<String, Object> insertMap2 = new HashMap<String, Object>();
//			 insertMap2.put("INVENTORYRESULTS", checkResult);
//			 insertMap2.put("INVENTORYDESCRIPTION", checkRemark);
//			 insertMap2.put("LASTEVENTNAME", "SaveYardInventory");
//			 insertMap2.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
//			 insertMap2.put("LASTEVENTTIME", new Date()); 
//			 insertMap2.put("LASTEVENTUSER",eventInfo.getEventUser());
//			 insertMap2.put("LASTEVENTCOMMENT","SaveYardInventory");
//			 insertMap2.put("SITENAME", siteName); 
//			 insertMap2.put("CASENO",caseNo);
//			 insertMap2.put("DEVICE", device);
//			 IDMFrameServiceProxy.getSqlTemplate().update(InsertSql, insertMap2);
			 
			  
			 // 更新盘点单据状态 
			 String updateCheckNoState = "UPDATE YARD_CHECK yc SET yc.CHECKSTATE = 'Completed' WHERE yc.SITENAME = :SITENAME AND yc.CHECKNO = :CHECKNO"; 
			 Map<String, Object> updateMap2 = new HashMap<String, Object>();
			 updateMap2.put("SITENAME", siteName); updateMap2.put("CHECKNO", checkNo);
			 IDMFrameServiceProxy.getSqlTemplate().update(updateCheckNoState, updateMap2);
			  
			 // 更新盘点单详情
			 String updateSql = "UPDATE YARD_CHECK_DETAIL SET CHECKRESULT=:CHECKRESULT , CHECKREMARK=:CHECKREMARK , CHECKER = :CHECKER, LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY,LASTEVENTTIME=:LASTEVENTTIME,LASTEVENTUSER=:LASTEVENTUSER "
			 +" WHERE SITENAME = :SITENAME AND CHECKNO = :CHECKNO AND CASENO = :CASENO AND DEVICE = :DEVICE";
			  
			 Map<String, Object> updateMap3 = new HashMap<String, Object>();
			 
			 updateMap3.put("CHECKRESULT", checkResult);
			 updateMap3.put("CHECKREMARK", checkRemark);
			 updateMap3.put("CHECKER", checker);
			 updateMap3.put("LASTEVENTNAME", "SaveYardInventoryDetail");
			 updateMap3.put("LASTEVENTTIMEKEY", System.currentTimeMillis());
			 updateMap3.put("LASTEVENTTIME", new Date()); 
			 updateMap3.put("LASTEVENTUSER",eventInfo.getEventUser()); 
			 updateMap3.put("SITENAME", siteName);
			 updateMap3.put("CHECKNO", checkNo); 
			 updateMap3.put("CASENO", caseNo);
			 updateMap3.put("DEVICE", device);
			 IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap3);
		}
	}
	
	
	
	
	public static String GenerateMaterialReceiveRequestName( String siteName) throws CustomException {
		// 获取系统当前时间
		java.util.Calendar c = java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat(
				"yyyyMMdd");

		List<String> args = new ArrayList<String>();
		String actType1 = "R";
		if(siteName.equals("B10")){
			siteName="BA";
		}else if(siteName.equals("BMDT")){
			siteName="BM";
		}else if(siteName.equals("B11")){
			siteName="BB";
		}else if(siteName.equals("BMOT")){
			siteName="BO";
		}else if(siteName.equals("B17")){
			siteName="BH";
		}else if(siteName.equals("B20")){
			siteName="BN";
		} else {
			siteName="BN";
		}
		args.add(siteName);
		args.add(actType1);
		args.add(f.format(c.getTime()));

		String ReceiveRequestActNo;

		ReceiveRequestActNo = NameServiceProxy.getNameRuleDefService()
				.generateName("ReceiveActNo", args, 1).get(0);
		return ReceiveRequestActNo;
	}

}
