package com.cim.idm.service.Impl;

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.framework.util.time.TimeUtils;
import com.cim.idm.model.AutoLibraryDetailDto;
import com.cim.idm.service.AutoLibraryService;
import com.cim.idm.service.impl.WCSServiceImpl;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 立库Service
 * @author 10539622
 *
 */
@Service
public class AutoLibraryServiceImpl implements AutoLibraryService {
	
	private static Log log = LogFactory.getLog(AutoLibraryServiceImpl.class);
	
	@Autowired 
	private WCSServiceImpl WCSServiceImpl = new WCSServiceImpl();

	/**
	 * 创建WCS搬送指令
	 * @param eventInfo
	 * @param detail
	 * @param areaName
	 * @return
	 * @throws CustomException
	 */
	public static String createCommand(EventInfo eventInfo, AutoLibraryDetailDto detail, String areaName, String transportCommand)
			throws CustomException {

//		String transportCommand="TRANS"+new TimeUtils().getCurrentEventTimeKey();
		String flag = detail.getFLAG();
		String transporttype = detail.getTRANSPORTCOMMANDTYPE();
		String inlocation=detail.getINDESTINATION();
		String outdestination = detail.getOUTDESTINATION();
		String outlocation=detail.getAREANAME();
		String palletName=detail.getMATERIALPACKINGNAME();
		String trayName=detail.getTRAYNAME();
		String isAgv=detail.getISAGV();
		String width=detail.getWIDTH();
		String diameter=detail.getDIAMETER();
		String deviation=detail.getDEVIATION();
		String weight=detail.getWEIGHT();
		String productLine=detail.getPRODUCTLINE();
		String shipRequestName=detail.getSHIPREQUESTNAME();
		String quantity=detail.getQUANTITY();
		String INITILATION=detail.getINITILATION();
		String ENDING=detail.getENDING();
		String AB=detail.getAB();
		String PORT = detail.getPORT();
		String temperature = detail.getTEMPERATURE();
		String bakingdays = detail.getBAKINGDAYS();
		if(!StringUtils.equals(flag, "TP")) {
			if("IN".equals(transporttype))
			{
				if(StringUtils.isEmpty(inlocation))
				{
					throw new CustomException("COMMAND-001");
				}
			}else if("OUT".equals(transporttype))
			{
				if(StringUtils.isEmpty(outlocation))
				{
					throw new CustomException("COMMAND-002");
				}

			}				
		}

		String[] pallet=null;
		if(StringUtils.equals(trayName, null) ) {
			trayName = "";
		}
		String[] trays = trayName.split(";");

		String PackingQty="";
		String destination="";
		if(!StringUtils.equals(flag, "TP")) {
			PackingQty=String.valueOf(trays.length);
		}else {
			PackingQty=quantity;
		}
		long priority=0;
		String stage=flag;

		eventInfo.setEventTimeKey(new TimeUtils().getCurrentEventTimeKey());
		eventInfo.setEventName("TransportCommandRequest");
		eventInfo.setEventComment("TransportCommandRequest");
		eventInfo.setEventTime( TimeStampUtil.getCurrentTimestamp());

		//查询主表是否有数据，有就不新增
		String judge = "select 1 from TRANSPORTCOMMAND where TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID ";
		String sql=" INSERT INTO TRANSPORTCOMMAND VALUES ("
				+ " :TRANSPORTCOMMANDID,:STATE,:TRANSPORTCOMMANDDETAILTYPE,:DESTINATION,:SHIPREQUESTNAME,"
				+ "	:PACKINGQTY,	:PRIORITY,	:LASTEVENTNAME,	:LASTEVENTTIME,	:LASTEVENTUSER,	:LASTEVENTCOMMENT,	"
				+ ":LASTEVENTTIMEKEY,	:REASONCODETYPE,	:REASONCODE,	:STAGE\r\n" + 
				") ";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("TRANSPORTCOMMANDID", transportCommand);
		bindMap.put("STATE", "Normal");
		bindMap.put("TRANSPORTCOMMANDDETAILTYPE", transporttype);
		bindMap.put("DESTINATION", destination);
		bindMap.put("SHIPREQUESTNAME", shipRequestName);
		bindMap.put("PACKINGQTY", PackingQty);
		bindMap.put("PRIORITY", priority);
		bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
		bindMap.put("LASTEVENTTIME", eventInfo.getEventTime());
		bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
		bindMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
		bindMap.put("REASONCODETYPE", "");
		bindMap.put("REASONCODE", "");	
		bindMap.put("STAGE", stage);	


		String sql1=" INSERT INTO TRANSPORTCOMMANDHISTORY\r\n" + 
				"SELECT TRANSPORTCOMMANDID,LASTEVENTTIMEKEY,STATE,\r\n" + 
				"TRANSPORTCOMMANDDETAILTYPE,DESTINATION,SHIPREQUESTNAME,\r\n" + 
				"PACKINGQTY,PRIORITY,LASTEVENTNAME,LASTEVENTTIME,\r\n" + 
				"LASTEVENTUSER,LASTEVENTCOMMENT,REASONCODETYPE,REASONCODE,STAGE\r\n" + 
				"FROM TRANSPORTCOMMAND\r\n" + 
				"WHERE TRANSPORTCOMMANDID =:TRANSPORTCOMMANDID ";
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("TRANSPORTCOMMANDID", transportCommand);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(judge, bindMap1);
		if (queryForList == null || queryForList.size() < 1) {
			IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		IDMFrameServiceProxy.getSqlTemplate().update(sql1, bindMap1);
		}
		
		
		
		List<Object[]> insertArgsProduct = new ArrayList<Object[]>();
		List<Object[]> insertHArgsProduct = new ArrayList<Object[]>();
		String insertsql = "";
		String insertHsql = "";

		String[] inloactions=null;
		String[] outlocations=null;
		if(!StringUtils.equals(flag, "TP")) {
			if (inloactions != null) {
				inloactions=inlocation.split(";");
			}
			if (outlocations != null) {
				outlocations=outlocation.split(";");	
			}
		}

		String palletId="";
		String outlocationname="";
		String inlocationname="";
		if(!StringUtils.equals(flag, "TP")) {
			palletId = palletName;
			if("OUT".equals(transporttype) || "MOVE".equals(transporttype))
			{
				outlocationname=outlocation;
			}

			if("IN".equals(transporttype)  || "MOVE".equals(transporttype))
			{
				inlocationname=inlocation;
			}
		}else {
			palletId="TP";
		}
		String trayID=trayName;
		insertArgsProduct.add(new Object[]{transportCommand,trayID,palletId,"Normal",eventInfo.getEventTime(),null,
				eventInfo.getEventName(),eventInfo.getEventUser(),eventInfo.getEventComment(),eventInfo.getEventTimeKey(),
				eventInfo.getEventTime(),null,null,inlocationname,outlocationname,isAgv,width,diameter,deviation,weight,productLine,
				INITILATION , ENDING, AB,PORT,temperature,bakingdays
		});
		insertHArgsProduct.add(new Object[]{transportCommand,trayID});
		if (insertArgsProduct.size() > 0)
		{
			// Pallet
			insertsql = sql_insertTransportCommandDetail();
			IDMFrameServiceProxy.getSqlTemplate().updateBatch(insertsql.toString(), insertArgsProduct);

			log.info("End Batch Pallet");
		}

		if (insertHArgsProduct.size() > 0)
		{
			// Pallet
			insertHsql = sql_insertTransportCommandDetailHistory();
			IDMFrameServiceProxy.getSqlTemplate().updateBatch(insertHsql.toString(), insertHArgsProduct);

			log.info("End Batch Pallet");
		}

		return transportCommand;
	}

	/*
	 * 可爱的sql
	 * ltg
	 * 2024.04.26
	 */
	public static String sql_insertTransportCommandDetail()
	{
		StringBuilder sql = new StringBuilder();
		sql.append(" INSERT INTO TRANSPORTCOMMANDDETAIL                                                     ");
		sql.append(" (TRANSPORTCOMMANDID,DURABLENAME,PACKINGNAME,STATE,CREATETIME,ENDTIME,LASTEVENTNAME, ");
		sql.append(" LASTEVENTUSER,LASTEVENTCOMMENT,LASTEVENTTIMEKEY,LASTEVENTTIME,REASONCODETYPE, ");
		sql.append(" REASONCODE,INDESTINATION,OUTDESTINATION,ISAGV,WIDTH,DIAMETER,DEVIATION,WEIGHT,PRODUCTLINE, INITILATION , ENDING ,AB,PORT,TEMPERATURE,BAKINGDAYS ) ");
		sql.append(" VALUES(?,?,?,?,?,?,?,    ");
		sql.append(" ?,?,?,?,?,               ");
		sql.append(" ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)       ");
		return sql.toString();
	}

	/*
	 * 可爱的sql
	 * ltg
	 * 2024.04.26
	 */
	public static String sql_insertTransportCommandDetailHistory()
	{
		StringBuilder sql = new StringBuilder();
		sql.append(" INSERT INTO TRANSPORTCOMMANDDETAILHISTORY                                                     ");
		sql.append(" SELECT TRANSPORTCOMMANDID,DURABLENAME,LASTEVENTTIMEKEY,STATE,CREATETIME,ENDTIME,LASTEVENTNAME,LASTEVENTUSER, ");
		sql.append(" LASTEVENTTIME,LASTEVENTCOMMENT,REASONCODETYPE,REASONCODE,PACKINGNAME,INDESTINATION,OUTDESTINATION,	 ");
		sql.append(" ISAGV,WIDTH,DIAMETER,DEVIATION,WEIGHT,PRODUCTLINE,PORT,TEMPERATURE,BAKINGDAYS FROM TRANSPORTCOMMANDDETAIL	 ");
		sql.append(" WHERE TRANSPORTCOMMANDID=? AND DURABLENAME=?	 ");
		return sql.toString();
	}


	/**
	 * 绑定托盘和批次信息
	 * @param eventInfo
	 * @param durableName
	 * @param siteName
	 * @param materialPackingName
	 * @throws Exception
	 */
	public void assignTryByBox(EventInfo eventInfo,String durableName,String siteName
			,String materialPackingName) throws Exception{
//		DurableKey key=new DurableKey();
//		key.setSiteName(siteName);
//		key.setDurableName(durableName);
//
//		String sql=" SELECT * FROM  DURABLE WHERE DURABLENAME =:DURABLENAME AND SITENAME=:SITENAME";
//		Map<String, Object> bindMap = new HashMap<String, Object>();
//		bindMap.put("SITENAME", siteName);
//		bindMap.put("DURABLENAME", durableName);
//		List <Map<String,Object>> result = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
//
//		int qty=0;
//		String assignqty="0";
//
//		if(result.size()>0)
//		{
//			assignqty= result.get(0).get("ASSIGNEDPACKINGQUANTITY").toString();
//		}
//
//		qty=Integer.parseInt(assignqty);
//
//		SetEventInfo setEventInfo = new SetEventInfo();
//		Map<String, Object> trybindMap = new HashMap<String, Object>();
//		trybindMap.put("assignedPackingQuantity", qty+1);
//		setEventInfo.setUserColumns(trybindMap);
//		DurableServiceProxy.getDurableService().setEvent(key, eventInfo, setEventInfo);

		com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo1 = new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();

		MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

		MaterialPackingKey.setSiteName(siteName);
		MaterialPackingKey.setMaterialPackingName(materialPackingName);

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

		boxbindMap.put("durableName", durableName);
		boxbindMap.put("areaName", "E");
		setEventInfo1.setUserColumns(boxbindMap);

		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
				MaterialPackingKey, eventInfo, setEventInfo1);

}

	/**
	 * 解绑托盘和批次信息
	 * @param eventInfo
	 * @param durableName
	 * @param siteName
	 * @param materialPackingName
	 * @throws Exception
	 */
	public void deassignTryByBox(EventInfo eventInfo,String durableName,String siteName
			,String materialPackingName) throws Exception{

		com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo1 = new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();

		MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

		MaterialPackingKey.setSiteName(siteName);
		MaterialPackingKey.setMaterialPackingName(materialPackingName);
		//获取标签状态
		MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(MaterialPackingKey);
		String stockState = selectByKey.getStockState();
//		if (!"StockOut".equals(stockState)) {
//			throw new CustomException("标签未出库，不能解绑");
//		}

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

		boxbindMap.put("durableName", "");
		boxbindMap.put("areaName", "");
		boxbindMap.put("shelfName", "");
		setEventInfo1.setUserColumns(boxbindMap);

		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
				MaterialPackingKey, eventInfo, setEventInfo1);

	}
	
	
	public void checkDurable(String durableName) throws Exception{

//		String sql = "SELECT * FROM TRANSPORTCOMMANDDETAIL T  LEFT JOIN TRANSPORTCOMMAND M "
//				+ "ON T.TRANSPORTCOMMANDID = M.TRANSPORTCOMMANDID  WHERE T.DURABLENAME  = :DURABLENAME AND M.STATE <> 'Completed' ";
//		Map<String, Object> hashMap = new HashMap<String,Object> ();
//		hashMap.put("DURABLENAME", durableName);
//		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
//		if (queryForList != null && queryForList.size() > 0) {
//			throw new CustomException("载具" + durableName + "已存在任务，不能作业");
//		}

	}
	
	//创建立库搬送任务 在库的
	@Transactional
	public void zkTransportRequest (String transportCommand,String userId,EventInfo makeEventInfo) {
		String transportCommandRequest = WCSServiceImpl.transportCommandRequest(transportCommand,userId);
		org.json.JSONObject jsonObject = new org.json.JSONObject(transportCommandRequest);
		String returnCode = jsonObject.get("RETURNCODE").toString();
		if ("1".equals(returnCode)) {
			String message = jsonObject.get("RETURNMESSAGE").toString();
			throw new RuntimeException(message);
		} else {
			Map<String, Object> hashMap1 = new HashMap<String,Object> ();
			//循环更新库存表
			String updateSql = "SELECT t.DURABLENAME ,t.PACKINGNAME,t.INDESTINATION, t.WIDTH,t.WEIGHT,t.DIAMETER,t.DEVIATION,t.PRODUCTLINE"
					+ " FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("TRANSPORTCOMMANDID", transportCommand);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(updateSql, hashMap);
			for (Map<String, Object> map : queryForList) {
				String durablename = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
				String materialpackingname = map.get("PACKINGNAME") == null ? "" : map.get("PACKINGNAME").toString();
				String areaname2 = map.get("INDESTINATION") == null ? "" : map.get("INDESTINATION").toString();
				String width2 = map.get("WIDTH") == null ? "" : map.get("WIDTH").toString();
				String weight2 = map.get("WEIGHT") == null ? "" : map.get("WEIGHT").toString();
				String deviation = map.get("DEVIATION") == null ? "" : map.get("DEVIATION").toString();
				String diameter2 = map.get("DIAMETER") == null ? "" : map.get("DIAMETER").toString();
				String PRODUCTLINE = map.get("PRODUCTLINE") == null ? "" : map.get("PRODUCTLINE").toString();
				hashMap1.put("durableName", durablename);
				hashMap1.put("areaName", areaname2);
				if (!"".equals(width2)) {
					hashMap1.put("WIDTH", width2);
				}
				
				if (!"".equals(deviation)) {
					hashMap1.put("DEVIATION", deviation);
				}
				
				if (!"".equals(weight2)) {
					hashMap1.put("WEIGHT", weight2);
				}
				
				
				if (!"".equals(diameter2)) {
					hashMap1.put("DIAMETER", diameter2);
				}
				
				if (!"".equals(PRODUCTLINE)) {
					hashMap1.put("PRODUCTLINE", PRODUCTLINE);
				}
				
				MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialpackingname);
				com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();
				setEventInfo.setUserColumns(hashMap1);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
			}

		}
	}
	
	
	//创建立库搬送任务 不在库只在标签系统的
	@Transactional
	public void bqTransportRequest (String transportCommand,String userId,EventInfo makeEventInfo) {
		String transportCommandRequest = WCSServiceImpl.bqTransportCommandRequest(transportCommand,userId);
		org.json.JSONObject jsonObject = new org.json.JSONObject(transportCommandRequest);
		String returnCode = jsonObject.get("RETURNCODE").toString();
		if ("1".equals(returnCode)) {
			String message = jsonObject.get("RETURNMESSAGE").toString();
			throw new RuntimeException(message);
		} else {
			//循环更新库存表
			String updateSql = "SELECT t.DURABLENAME ,t.PACKINGNAME,t.INDESTINATION, t.WIDTH,t.WEIGHT,t.DIAMETER,t.DEVIATION,t.PRODUCTLINE"
					+ " FROM TRANSPORTCOMMANDDETAIL t WHERE t.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("TRANSPORTCOMMANDID", transportCommand);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(updateSql, hashMap);
			for (Map<String, Object> map : queryForList) {
				String durablename = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
				String materialpackingname = map.get("PACKINGNAME") == null ? "" : map.get("PACKINGNAME").toString();
				String areaname2 = map.get("INDESTINATION") == null ? "" : map.get("INDESTINATION").toString();
				String width2 = map.get("WIDTH") == null ? "" : map.get("WIDTH").toString();
				String weight2 = map.get("WEIGHT") == null ? "" : map.get("WEIGHT").toString();
				String deviation = map.get("DEVIATION") == null ? "" : map.get("DEVIATION").toString();
				String diameter2 = map.get("DIAMETER") == null ? "" : map.get("DIAMETER").toString();
				String PRODUCTLINE = map.get("PRODUCTLINE") == null ? "" : map.get("PRODUCTLINE").toString();
				String sql = "UPDATE\r\n" + 
						"	BS_MES_SHIPPED T\r\n" + 
						"SET\r\n" + 
						"	T.LK_WIDTH = :LK_WIDTH,\r\n" + 
						"	T.LK_DIAMETER = :LK_DIAMETER,\r\n" + 
						"	T.LK_DEVIATION = :LK_DEVIATION,\r\n" + 
						"	T.LK_WEIGHT = :LK_WEIGHT,\r\n" + 
						"	T.LK_PRODUCTLINE = :LK_PRODUCTLINE,\r\n" + 
						"	T.LK_AREANAME = :LK_AREANAME,\r\n" + 
						"	T.LK_SHELFNAME = :LK_SHELFNAME,\r\n" + 
						"	T.LK_DURABLENAME = :LK_DURABLENAME\r\n" + 
						"WHERE\r\n" + 
						"	T.LOTNAME =  :LOTNAME ";
				Map<String, Object> hashMap2 = new HashMap<String,Object> ();
				hashMap2.put("LK_WIDTH", width2);
				hashMap2.put("LK_DIAMETER", diameter2);
				hashMap2.put("LK_DEVIATION", deviation);
				hashMap2.put("LK_WEIGHT", weight2);
				hashMap2.put("LK_PRODUCTLINE", PRODUCTLINE);
				hashMap2.put("LK_AREANAME", areaname2);
				hashMap2.put("LK_SHELFNAME", "");
				hashMap2.put("LK_DURABLENAME", "");
				hashMap2.put("LOTNAME", materialpackingname);
				IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap2);
			}

		}
	}

}
