package com.cim.idm.controller;

import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.template.workflow.BpelExecuter;
import com.cim.idm.model.BarCodeDto;
import com.cim.idm.model.ErpMessageLog;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.BarCodeAnalyUtils;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.util.ConvertUtil;
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 com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/wms")
@EnableAutoConfiguration
public class WCSController {
	
    @Autowired(required = false)
    private BpelExecuter bpelExecuter;
	
	private static final Logger log = LoggerFactory.getLogger(WCSController.class);

	@RequestMapping(value = "/TransportCommandCompleted", method = RequestMethod.POST)
	public String SyncErpData(@RequestBody JSONObject in) {
		log.debug("***********************************");
		log.debug("***********************************");
		log.debug(in.toString());
		log.debug("***********************************");
		log.debug("***********************************");
		//		 {"PALLETNAME":"470110856|1|C|75mm*1000m|SHBP01JT12023052400092|20230524|11|75","SHELFNAME":"F-11-01-01","TRAYNAME":"050101","TRANSPORTCOMMANDID":"TRANS202405010925233345514","WEIGHT":"0","TRANSPORTCOMMANDTYPE":"IN"}

		//		TRANSPORTCOMMANDTYPE
		//		TRANSPORTCOMMANDID
		//		TRAYNAME
		//		PALLETNAME
		//		SHELFNAME

		//		TRANSPORTCOMMANDID
		//		RETURNCODE
		//		RETURNMESSAGE
		//通过ID获取立库的货区，托盘库的货区不自动解绑，AGV的要更新货区跟托盘字段
		String TRANSPORTCOMMANDTYPE = in.get("TRANSPORTCOMMANDTYPE") == null ? "" : in.get("TRANSPORTCOMMANDTYPE") .toString();
		String TRANSPORTCOMMANDID = in.get("TRANSPORTCOMMANDID")  == null ? "" : in.get("TRANSPORTCOMMANDID").toString();
		String TRAYNAME = in.get("TRAYNAME") == null ? "" : in.get("TRAYNAME").toString();
		AjaxResult result = new AjaxResult();
		ErpMessageLog loginfo = new ErpMessageLog();
		loginfo.setServerName("WCSToWms");
		loginfo.setMessageId("");
		loginfo.setEventName("WCS" + TRANSPORTCOMMANDTYPE);
		loginfo.setEventUser("WCS");
		loginfo.setId(UUID.randomUUID().toString());
		loginfo.setInterfaceTime(ConvertUtil.getCurrTime("yyy-MM-dd HH:mm:ss"));
		loginfo.setSendMsg(in.toJSONString());
		result = AjaxResult.me().setSuccess(true).setMessage("执行成功");
		loginfo.setResultCode("success");
		loginfo.setReturnMsg(JSONObject.toJSONString(result));
		saveMessageLog(loginfo);
		String SHELFNAME = in.get("SHELFNAME") == null ? "" : in.get("SHELFNAME").toString();
		String PALLETNAME = in.get("PALLETNAME") == null ? "" : in.get("PALLETNAME").toString();
		//判断是否是WMS下任务给立库，如果是则根据ID去更新状态，如果不是需要根据货位去判断是出库还是入库
		if (!"".equals(TRANSPORTCOMMANDID)) {
			String sql = "SELECT T.ISAGV,M.TRANSPORTCOMMANDDETAILTYPE,T.INDESTINATION,T.OUTDESTINATION  FROM TRANSPORTCOMMANDDETAIL T "
					+ "LEFT JOIN TRANSPORTCOMMAND M ON T.TRANSPORTCOMMANDID = M.TRANSPORTCOMMANDID WHERE T.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
			hashMap2.put("TRANSPORTCOMMANDID", TRANSPORTCOMMANDID);
			String INDESTINATION = "";
			String ISAGV = "";
			String OUTDESTINATION = "";
			List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap2);
			if (queryForList != null && queryForList.size() > 0) {
				OUTDESTINATION = queryForList.get(0).get("OUTDESTINATION") == null ? "" : queryForList.get(0).get("OUTDESTINATION").toString();
				ISAGV = queryForList.get(0).get("ISAGV") == null ? "" : queryForList.get(0).get("ISAGV").toString();
				INDESTINATION = queryForList.get(0).get("INDESTINATION") == null ? "" : queryForList.get(0).get("INDESTINATION").toString();
			}
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			Map<String, Object> bmap = new HashMap<String,Object> ();
			hashMap.put("shelfName", SHELFNAME);
			bmap.put("shelfName", SHELFNAME);
			if (!"".equals(SHELFNAME)) {
				hashMap.put("areaName", SHELFNAME.substring(0, 1));
				bmap.put("areaName", SHELFNAME.substring(0, 1));
			}
			if ("OUT".equals(TRANSPORTCOMMANDTYPE) && !"E".equals(OUTDESTINATION)) {
				hashMap.put("durableName", "");
				hashMap.put("areaName", "");
				bmap.put("durableName", "");
				bmap.put("areaName", "");
			}
			if (("IN".equals(TRANSPORTCOMMANDTYPE)  || "MOVE".equals(TRANSPORTCOMMANDTYPE)) ) {
				hashMap.put("durableName", TRAYNAME);
				hashMap.put("areaName", SHELFNAME.substring(0, 1));
				bmap.put("durableName", TRAYNAME);
				bmap.put("areaName", SHELFNAME.substring(0, 1));
				
			}
			
			String[] palletArr = PALLETNAME.split(";");
			for (String pallet : palletArr) {
				try {
//					MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",pallet);
					EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("WCSStockTo" + TRANSPORTCOMMANDTYPE, "WCS", "WCSStockTo" + TRANSPORTCOMMANDTYPE);
					SetEventInfo setEventInfo = new SetEventInfo();
					setEventInfo.setUserColumns(hashMap);
//					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
					//修改更新方法
					BarCodeDto barCodeDto = BarCodeAnalyUtils.AnalyBarCode(pallet);
					if (barCodeDto != null) {
						String materialSpecName = barCodeDto.getMaterialSpecName();
						String charge = barCodeDto.getCharge();
						MaterialPacking barCodeByMaterialPackingId = BarCodeAnalyUtils.getBarCodeByMaterialPackingId(materialSpecName, charge);
						if (barCodeByMaterialPackingId != null) {
							MaterialPackingKey key = barCodeByMaterialPackingId.getKey();
							MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, makeEventInfo, setEventInfo);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				bmap.put("PALLETNAME", pallet);
				String sql22 = "UPDATE BS_MES_SHIPPED T SET T.LK_AREANAME = :areaName,T.LK_SHELFNAME = :shelfName, T.LK_DURABLENAME = :durableName WHERE T.LOTNAME = :PALLETNAME ";
				IDMFrameServiceProxy.getSqlTemplate().update(sql22, bmap);
			}
			//更新任务状态
			String updateSql = "UPDATE TRANSPORTCOMMAND T  SET T.STATE  = 'Completed' WHERE T.TRANSPORTCOMMANDID = :TRANSPORTCOMMANDID";
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
		}  else {
			//{"PALLETNAME":"302110849|1|S|1900mm|24-10-31-SHJC07-A003|20241031|11|6954;","SHELFNAME":"C-01-09-01","TRAYNAME":"400644","WEIGHT":"0"}
			String chk = "SELECT PORTNO,PORTNAME,AREANAME FROM PORT WHERE PORTNO = :PORT";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("PORT", SHELFNAME);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(chk, hashMap);
			Map<String, Object> uMap = new HashMap<String,Object> ();
			Map<String, Object> bmap = new HashMap<String,Object> ();
			//出库过滤掉托盘库  E-00-01-02  E-00-01-01
			if (queryForList != null && queryForList.size() > 0) {//出库
				if (!" E-00-01-02".equals(SHELFNAME) && ! "E-00-01-01".equals(SHELFNAME)) {
					uMap.put("shelfName", "");
					uMap.put("durableName", "");
					uMap.put("areaName", "");
					
					bmap.put("shelfName", "");
					bmap.put("durableName", "");
					bmap.put("areaName", "");
				}
			} else {
				uMap.put("durableName", TRAYNAME);
				uMap.put("shelfName", SHELFNAME);
				
				bmap.put("durableName", TRAYNAME);
				bmap.put("shelfName", SHELFNAME);
				if (!"".equals(SHELFNAME)) {
					uMap.put("areaName", SHELFNAME.substring(0, 1));
					bmap.put("areaName", SHELFNAME.substring(0, 1));
				}
			}
			String[] palletArr = PALLETNAME.split(";");
			for (String pallet : palletArr) {
				 try {
					 //					MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",pallet);
					 EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("WCSStockTo" + TRANSPORTCOMMANDTYPE, "WCS", "WCSStockTo" + TRANSPORTCOMMANDTYPE);
					 SetEventInfo setEventInfo = new SetEventInfo();
					 setEventInfo.setUserColumns(hashMap);
//					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
					 //修改更新方法
					 BarCodeDto barCodeDto = BarCodeAnalyUtils.AnalyBarCode(pallet);
					 if (barCodeDto != null) {
						 String materialSpecName = barCodeDto.getMaterialSpecName();
						 String charge = barCodeDto.getCharge();
						 MaterialPacking barCodeByMaterialPackingId = BarCodeAnalyUtils.getBarCodeByMaterialPackingId(materialSpecName, charge);
						 if (barCodeByMaterialPackingId != null) {
							 MaterialPackingKey key = barCodeByMaterialPackingId.getKey();
							 MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, makeEventInfo, setEventInfo);
						 }
					 }
				} catch (Exception e) {
					// TODO: handle exception
				}
				bmap.put("PALLETNAME", pallet);
				String sql = "UPDATE BS_MES_SHIPPED T SET T.LK_AREANAME = :areaName,T.LK_SHELFNAME = :shelfName, T.LK_DURABLENAME = :durableName WHERE T.LOTNAME = :PALLETNAME ";
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bmap);
			}
		}
		JSONObject body = new JSONObject(true);
		body.put("TRANSPORTCOMMANDID",in.get("TRANSPORTCOMMANDID"));
		body.put("RETURNCODE","200");
		body.put("RETURNMESSAGE","");
		return body.toJSONString();
	}
	
	
	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);
	}
	
}


