package com.cim.idm.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
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.model.BaseEntity;
import com.cim.idm.model.ErpMessageLog;
import com.cim.idm.model.MaterialPacking;
import com.cim.idm.model.PalletDto;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmsextend.generic.util.ConvertUtil;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.CreateInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/api/wms")
@EnableAutoConfiguration
public class PalletStockInAndOutController {
	
	@Autowired
	private com.cim.idm.service.Impl.ProductIntoServiceImpl ProductIntoServiceImpl;
	
	@Autowired
	private com.cim.idm.service.Impl.InvoiceServiceImpl InvoiceServiceImpl;
	
	CommonUtils untils=new CommonUtils();

	private static final Logger log = LoggerFactory.getLogger(PalletStockInAndOutController.class);
	@RequestMapping(value = "/syncMesData", method = RequestMethod.POST)
	public AjaxResult syncMesData(@RequestBody JSONObject in) {
		log.debug("***********************************");
		log.debug("***********************************");
		log.debug(in.toString());
		log.debug("***********************************");
		log.debug("***********************************");
		AjaxResult result = new AjaxResult();
		ErpMessageLog loginfo = new ErpMessageLog();
		loginfo.setServerName("MesToWms");
		loginfo.setMessageId("");

		loginfo.setEventUser(in.getString("user"));
		loginfo.setId(UUID.randomUUID().toString());
		loginfo.setInterfaceTime(ConvertUtil.getCurrTime("yyy-MM-dd HH:mm:ss"));
		loginfo.setSendMsg(in.toJSONString());
		try {
			String messagetype = in.get("messagetype").toString();
			loginfo.setEventName(String.format("%s", messagetype));
			switch (messagetype) {
			case "STOCKINPALLET" : //	托盘入库
				BaseEntity<PalletDto> PalletInDto = JSONObject.parseObject(in.toJSONString(),
						new TypeReference<BaseEntity<PalletDto>>() {
				});
				stockInPallet(PalletInDto);
				break;
			case "STOCKOUTPALLET" : //	托盘出库
				BaseEntity<PalletDto> PalletOutDto = JSONObject.parseObject(in.toJSONString(),
						new TypeReference<BaseEntity<PalletDto>>() {
				});
				stockOutPallet(PalletOutDto);
				break;
			default :
				break;
			}
			result = AjaxResult.me().setSuccess(true).setMessage("执行成功");
			loginfo.setResultCode("success");
			loginfo.setReturnMsg(JSONObject.toJSONString(result));
			// 消息保存日志，Mes推送wms的数据写入表BS_ERPMESSAGELOG中
			saveMessageLog(loginfo);
			return result;
		} catch (Exception e) {
			result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage(e.getMessage());
			loginfo.setResultCode("fail");
			loginfo.setReturnMsg(JSONObject.toJSONString(result));
			saveMessageLog(loginfo);
			return result;
		}
	}
	/**
	 * 托盘入库
	 * @param PalletDto
	 * @throws Exception 
	 */
	private void stockInPallet(BaseEntity<PalletDto> PalletDto) throws Exception {
		try {
//				String commitDate = PalletDto.getTime();
				SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date datea = null;
				datea = inputFormat.parse(PalletDto.getTime());
				String commitDate = outputFormat.format(datea);

			for (PalletDto palletDto : PalletDto.getBody()) {
					String palletname = palletDto.getPALLETNAME();//栈板
					String materialspecname = palletDto.getMATERIALSPECNAME();//料号
					String erpfactory = palletDto.getERPFACTORY();//组织
					String erplocation = palletDto.getERPLOCATION();//仓库
					String locationname = palletDto.getLOCATIONNAME();//货位
					String oqaresult = palletDto.getOQARESULT();//质检结果
					String indate = palletDto.getINDATE();//入库日期
					String phase = palletDto.getPHASE();//阶段
					String planorder = palletDto.getPLANORDER();//投放计划
					String productorder = palletDto.getPRODUCTORDER();//生产订单
					String receiverequestname = palletDto.getRECEIVEREQUESTNAME();//完工报告
					String remark = palletDto.getREMARK();//备注
					String sdk_ID = palletDto.getSDK_ID();//SDK规格
					String shiprequestdetailname = palletDto.getSHIPREQUESTDETAILNAME();//发货单行号
					String shiprequestname = palletDto.getSHIPREQUESTNAME();//发货单
//					String user = palletDto.getUSER();//作业人
//					String opCode = palletDto.getOpCode();
					String ReceiveRequestActNo = null;
					List<MaterialPacking> detail = palletDto.getDetail();
					
					
					
					String opCode = palletDto.getOpCode() == null ? "" : palletDto.getOpCode().toString();
					String user = palletDto.getUSER() == null ? "" : palletDto.getUSER().toString();
					if ("".equals(opCode) || opCode == null) {
						String sql = "SELECT  :USER || '-' || NCDATA_IDX.NEXTVAL ID FROM DUAL";
						Map<String, Object> hashMap = new HashMap<String,Object> ();
						hashMap.put("USER", user);
						List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
						opCode = queryForList.get(0).get("ID").toString();
					}
					
					List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> mpkeyList = new ArrayList<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> ();
					for (MaterialPacking materialPacking : detail) {
						
						untils.IsAtMaterialPacking(materialPacking.getMaterialPackingName(),erpfactory,erplocation,locationname,materialspecname);
						
						com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking materialPacking2 = new com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking();
						materialPacking2.setKey(new MaterialPackingKey("SDK",materialPacking.getMaterialPackingName()));
						materialPacking2.setErpFactory(erpfactory);
						materialPacking2.setErpLocation(erplocation);
						materialPacking2.setLocationName(locationname);
//						materialPacking2.setMaterialSpecName(materialspecname);
						materialPacking2.setMaterialPackingName(materialPacking.getMaterialPackingName());
						mpkeyList.add(materialPacking2);
					}
					
					//List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpkeyList);
					
//					List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> detail = palletDto.getDetail();


//				ProductIntoServiceImpl.fgStockInNew(mpkeyList, user, ReceiveRequestActNo, commitDate, opCode);
				ProductIntoServiceImpl.fgStockInByManul(mpkeyList, user, ReceiveRequestActNo, commitDate, opCode);

//					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 = "F";
//					String siteName = "SH";
//					args.add(siteName);
//					args.add(actType1);
//					args.add(f.format(c.getTime()));
//					String ReceiveRequestActNo;
//
//					ReceiveRequestActNo = NameServiceProxy.getNameRuleDefService()
//							.generateName("ReceiveActNo", args, 1).get(0);
//					
//					String pc = "(";
//					for (MaterialPacking materialPacking : detail) {
////						  "MATERIALPACKINGNAME": "箱标签",
////			                "CHARGE": "箱批次",
////			                "MATERIALQUANTITY": "数量",
////			                "UNIT": "单位",
////			                "OQARESULT" : "品质结果"
//						String materialPackingName = materialPacking.getMaterialPackingName();
//						String charge = materialPacking.getCharge();
//						String materialQuantity = materialPacking.getMaterialQuantity();
//						String unit = materialPacking.getUnit();
//						String oqaResult2 = materialPacking.getOqaResult();
//						
//						String salesPerson = materialPacking.getSalesPerson();  // 业务
//						String career_assistance = materialPacking.getCareer_assistance();
//						String business_unit = materialPacking.getBusiness_unit();
//						String durableType = materialPacking.getDurableType();
//						
//						pc += "'" +  materialPackingName + "', ";
//						
//						//根据入库信息获取完工报告
//						String sql3 = "SELECT\r\n" + 
//								"	M.RECEIVEREQUESTNAME,\r\n" + 
//								"	M.RECEIVEREQUESTDETAILNAME\r\n" + 
//								"FROM\r\n" + 
//								"	MATERIALRECEIVEREQUESTDETAIL M\r\n" + 
//								"WHERE\r\n" + 
//								"	(M.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME OR M.PRODUCTORDER  = :RECEIVEREQUESTNAME OR M.PLANORDER  = :RECEIVEREQUESTNAME)\r\n" + 
//								"	AND M.MATERIALSPECNAME = :MATERIALSPECNAME ";
//						Map<String, Object> bindMap = new HashMap<String, Object>();
//						bindMap.put("RECEIVEREQUESTNAME",receiverequestname);
//						bindMap.put("MATERIALSPECNAME",materialspecname);
//						List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql3, bindMap);
//						if (queryForList == null || queryForList.size() < 1) {
//							throw new GlobalException("生产报告未完成,请联系IT处理！");
//						}
//						EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("createfgBoxInfo", user, "createfgBoxInfo", "", "");
////						try {
////							ProductIntoServiceImpl.CreateMaterialReceiveRequestAct
////							(makeEventInfo, "SDK", queryForList.get(0).get("RECEIVEREQUESTNAME").toString(), 
////									 queryForList.get(0).get("RECEIVEREQUESTDETAILNAME").toString(), indate, 
////									 ReceiveRequestActNo, "Normal", materialQuantity, materialspecname);
////						} catch (CustomException | ParseException e) {
////							// TODO Auto-generated catch block
////							e.printStackTrace();
////							throw new GlobalException(e.toString());
////						}
//						
//						receivePalletStockIn(makeEventInfo, "SDK", materialPackingName, charge,materialQuantity,sdk_ID,remark,materialspecname,"",user, 
//								palletname, ReceiveRequestActNo, oqaresult,phase,unit,indate,erplocation, erpfactory, locationname,queryForList.get(0).get("RECEIVEREQUESTNAME").toString(), queryForList.get(0).get("RECEIVEREQUESTDETAILNAME").toString(),
//								salesPerson,career_assistance,business_unit,durableType);
//						
//					}
//					pc += "'')";
//
////					boolean fgStockIn = ProductIntoServiceImpl.fgStockIn(ReceiveRequestActNo, user,commitDate);
//					boolean fgStockIn = ProductIntoServiceImpl.fgStockIn(pc, user,commitDate,opCode);
//					if (!fgStockIn) {
//						throw new GlobalException("报送ERP失败,请联系IT处理！");
//					}
				}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	
	
	public static boolean receivePalletStockIn(EventInfo eventInfo,String siteName,String materialPackingName,String Charge,String qty,
			String sdk_ID,String remark,String materilSpecName,
			String durableName,String user,String palletName,String receiveActNo,String oqaresult,String phase,String unit,String indate,
			String erpLocation,String erpFactory,String locationName,String receiveRequestName, String receiveRequestDetailName,
			String salesPerson,String career_assistance,String business_unit,String durableType)  {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		if(queryForList != null && queryForList.size() > 1) {
			new CustomException("批次已入库");
		}
		
		//入库信息存入库存表
		CreateInfo createInfo = new CreateInfo();
		createInfo.setSiteName(siteName);
		createInfo.setMaterialPackingName(materialPackingName);// 新生成的box id
		createInfo.setMaterialPackingType("Box");
		createInfo.setContentMaterialType("");
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("superMaterialPackingName", palletName);
		bindMap.put("MaterialType", "");
		bindMap.put("MaterialSpecName", materilSpecName);
		if ("".equals(oqaresult) || oqaresult == null) {
			bindMap.put("oqaResultState", "");
		} else {
			bindMap.put("oqaResultState", "END");
		}
		bindMap.put("oqaResult", oqaresult);
		bindMap.put("PackingGrade", oqaresult);
		bindMap.put("SubPackingQuantity",qty);
		bindMap.put("MaterialCreateQuantity",qty);
		bindMap.put("MaterialQuantity", qty);// 数量
		bindMap.put("PackingState", "Released");
		bindMap.put("OldPackingState", "Released");
		bindMap.put("StockState", "Created");
		bindMap.put("OldStockState", "Created");
		bindMap.put("HoldState", "N");
		bindMap.put("AreaName", "");
		bindMap.put("unit", unit);
		bindMap.put("LocationName", locationName);
		bindMap.put("charge",Charge);
		bindMap.put("DurableName", durableName);
		bindMap.put("MaterialProcessGroupName","");
		bindMap.put("LastEventTimeKey",TimeStampUtil.getCurrentEventTimeKey());
		bindMap.put("ReceiveRequestName", receiveRequestName);
		bindMap.put("ReceiveRequestDetailName",receiveRequestDetailName);
		bindMap.put("MakeDate", indate);
//		bindMap.put("expiringDate", getExpridate(queryForList.get(0).get("SHIPTIME").toString(), queryForList.get(0).get("MATERIALSPECNAME").toString()));
		bindMap.put("expiringDate", getExpridate(indate, materilSpecName));
		bindMap.put("ReceiveTime", eventInfo.getEventTime());
		bindMap.put("ReceiveUser", eventInfo.getEventUser());
		bindMap.put("ShipTime",indate);
		bindMap.put("ShipUser",user);
		bindMap.put("ErpLocation", erpLocation);
		bindMap.put("ErpFactory", erpFactory);
		bindMap.put("receiveActNo", receiveActNo);
		bindMap.put("locationName", locationName);
		bindMap.put("StockInType", "Normal");
		bindMap.put("SDK_ID", sdk_ID);
		bindMap.put("PHASE", phase);
		
		bindMap.put("salesPerson", salesPerson);
		bindMap.put("career_assistance", career_assistance);
		bindMap.put("business_unit", business_unit);
		bindMap.put("durableType", durableType);
		
		createInfo.setUserColumns(bindMap);
		MaterialPackingServiceProxy.getMaterialPackingService().create(
				eventInfo, createInfo);
		return true;
	}
	
	public static String getExpridate(String makeDate,String materialSpecName) {
		String sql = "SELECT NVL(T.EXPIRATIONDAY,180) +   TO_TIMESTAMP(SUBSTR(:MAKEDATE,0,19),'YYYY-MM-DD HH24:MI:SS') EXP FROM MATERIALSPEC T WHERE T.MATERIALSPECNAME = :MATERIALSPECNAME";
		
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("MAKEDATE", makeDate);
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		
		if (queryForList != null && queryForList.size() > 0) {
			return queryForList.get(0).get("EXP").toString();
		}
		return "";
	}
	/**
	 * 托盘出库
	 * @param PalletDto
	 * @throws Exception 
	 */
	private void stockOutPallet(BaseEntity<PalletDto> PalletDto) throws Exception {
		try {
			
			String commitDate = PalletDto.getTime();
			String shipRequestName = "";
			String opCode  = "";
			String user = "";
			List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> list = new ArrayList<> ();
			for (PalletDto palletDto : PalletDto.getBody()) {
				String palletname = palletDto.getPALLETNAME();//栈板
				String materialspecname = palletDto.getMATERIALSPECNAME();//料号
				String erpfactory = palletDto.getERPFACTORY();//组织
				String erplocation = palletDto.getERPLOCATION();//仓库
				String locationname = palletDto.getLOCATIONNAME();//货位
				String oqaresult = palletDto.getOQARESULT();//质检结果
				String indate = palletDto.getINDATE();//入库日期
				String phase = palletDto.getPHASE() == null ? "" :  palletDto.getPHASE();//阶段
//				String planorder = palletDto.getPLANORDER();//投放计划
//				String productorder = palletDto.getPRODUCTORDER();//生产订单
//				String receiverequestname = palletDto.getRECEIVEREQUESTNAME();//完工报告
				String remark = palletDto.getREMARK();//备注
				String sdk_ID = (palletDto.getSDK_ID() == null || "~".equals(palletDto.getSDK_ID().toString())) ? "" : palletDto.getSDK_ID().toString(); //SDK规格
				
				String shiprequestdetailname = palletDto.getSHIPREQUESTDETAILNAME();//发货单行号
				shipRequestName = palletDto.getSHIPREQUESTNAME();//发货单
//				String user = palletDto.getUSER();//作业人
//				String opCode = palletDto.getOpCode() == null ? "" : palletDto.getOpCode();
				
				opCode = palletDto.getOpCode() == null ? "" : palletDto.getOpCode().toString();
				user = palletDto.getUSER() == null ? "" : palletDto.getUSER().toString();
				if ("".equals(opCode) || opCode == null) {
					String sql = "SELECT  :USER || '-' || NCDATA_IDX.NEXTVAL ID FROM DUAL";
					Map<String, Object> hashMap = new HashMap<String,Object> ();
					hashMap.put("USER", user);
					List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
					opCode = queryForList.get(0).get("ID").toString();
				}
				
				List<MaterialPacking> detail = palletDto.getDetail();
				
				for (MaterialPacking materialPacking : detail) {
//					  "MATERIALPACKINGNAME": "箱标签",
//		                "CHARGE": "箱批次",
//		                "MATERIALQUANTITY": "数量",
//		                "UNIT": "单位",
//		                "OQARESULT" : "品质结果"
					String materialPackingName = materialPacking.getMaterialPackingName();
					com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(new MaterialPackingKey("SDK", materialPackingName));
					
					if(selectByKey == null) {
						throw new CustomException("找不到出库单据里的条码" + materialPackingName);
					}
					Double fgetMaterialQuantity = Double.parseDouble(materialPacking.getMaterialQuantity());
					selectByKey.setMaterialQuantity2(fgetMaterialQuantity);
					list.add(selectByKey);
					
					String charge = materialPacking.getCharge();
					String unit = materialPacking.getUnit();
					String oqaResult2 = materialPacking.getOqaResult();
					String materialQuantity = materialPacking.getMaterialQuantity();
					String materialQuantity2 = materialQuantity; 
					String salesPerson = materialPacking.getSalesPerson();  // 业务
					String career_assistance = materialPacking.getCareer_assistance();
					String business_unit = materialPacking.getBusiness_unit();
					String durableType = materialPacking.getDurableType();
					
					stockOutPalletDessignOrAssign(materialPackingName,materialspecname,shipRequestName,materialQuantity,materialQuantity2,sdk_ID,phase,user);
				}
				
				String shipRequestType;
				String sql = "SELECT m.SHIPREQUESTTYPE FROM MATERIALSHIPREQUEST m WHERE m.SHIPREQUESTNAME = :SHIPREQUESTNAME";
				Map<String, Object> hashMap = new HashMap<String,Object> ();
				hashMap.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
				if (queryForList != null && queryForList.size() > 0) {
					String type = queryForList.get(0).get("SHIPREQUESTTYPE").toString();
					shipRequestType = type;
				} else {
					throw new CustomException("找不到出库单据" + shipRequestName);
				}
				
//				if ("4Y".equals(shipRequestType)) {
//					String ncSql = "SELECT\r\n" +
//							"	NCDATA_IDX.NEXTVAL ID,\r\n" +
//							"	'' PrintBatch,\r\n" +
//							"	m.MATERIALPACKINGNAME Barcode,\r\n" +
//							"	'transOut' PrintType,\r\n" +
//							"	m.shiprequestname SourceOrder,\r\n" +
//							"	T.BILLPK SourceOrderId,\r\n" +
//							"	T.DATAPK SourceAutoid, \r\n" +
//							"	T.PK_ORG OrgCode,\r\n" +
//							"	T.PK_MATE MaterialId,\r\n" +
//							"	T.INVCODE MaterialCode,\r\n" +
//							"	T.PK_STAGE StageId,\r\n" +
//							"	T.INVSTAGE StageCode,\r\n" +
//							"	T.BillCode WorkPlant,\r\n" +
//							"	'' WorkShop,\r\n" +
//							"	'' WorkShift,\r\n" +
//							"	'' Machine,\r\n" +
//							"	'' VolNumber,\r\n" +
//							"	'' SupCode,\r\n" +
//							"	'' CustomerCode,\r\n" +
//							"	'' SupBarcode,\r\n" +
//							"	'' CusBarcode,\r\n" +
//							"	T.INVNAME MaterialName,\r\n" +
//							"	T.MATERIALSPEC Specifications,\r\n" +
//							"	T.PK_SIZE SDKSpecificationsId,\r\n" +
//							"	T.INVSIZE SDKSpecifications,\r\n" +
//							"	M.CHARGE Batch,\r\n" +
//							"	'' JumboRollBatch,\r\n" +
//							"	m.MAKEDATE BatchDate,\r\n" +
//							"	SYSDATE PrintBatchDate,\r\n" +
//							"	m.MAKEDATE ProductDate,\r\n" +
//							"	m.EXPIRINGDATE ExpiryDate,\r\n" +
//							"	T.UNAME MainUom,\r\n" +
//							"	DECODE(m.MATERIALQUANTITY2,0, m.MATERIALQUANTITY,m.MATERIALQUANTITY2) MainQty,\r\n" +
//							"	m.FUNIT AssistUom,\r\n" +
//							"	NVL(m.FQTY, 0) AssistQty,\r\n" +
//							"	m.TRUEGG PracticalSpec,\r\n" +
//							"	1 PrintQty,\r\n" +
//							"	sysdate PrintDate,\r\n" +
//							"	LASTEVENTUSER Operator,\r\n" +
//							"	'' Salesman,\r\n" +
//							"	m.REMARK ,\r\n" +
//							"	'' DefineItem1,\r\n" +
//							"	'' DefineItem2,\r\n" +
//							"	'' DefineItem3,\r\n" +
//							"	'' DefineItem4,\r\n" +
//							"	'' DefineItem5,\r\n" +
//							"	'' DefineItem6,\r\n" +
//							"	'' DefineItem7,\r\n" +
//							"	'' DefineItem8,\r\n" +
//							"	'' DefineItem9,\r\n" +
//							"	'' DefineItem10,\r\n" +
//							"	'' DefineItem11,\r\n" +
//							"	'' DefineItem12,\r\n" +
//							"	'' DefineItem13,\r\n" +
//							"	'' DefineItem14,\r\n" +
//							"	'' DefineItem15,\r\n" +
//							"	'' DefineItem16,\r\n" +
//							"	'' DefineItem17,\r\n" +
//							"	'' DefineItem18,\r\n" +
//							"	'' DefineItem19,\r\n" +
//							"	'' DefineItem20,\r\n" +
//							"	CURRENT_TIMESTAMP Timestamp,\r\n" +
//							"	SYSDATE CreatedTime,\r\n" +
//							"	SYSDATE UpdatedTime,\r\n" +
//							"	'0' CreatedUserId,\r\n" +
//							"	'0' CreatedUserName,\r\n" +
//							"	'0' UpdatedUserId,\r\n" +
//							"	'0' UpdatedUserName,\r\n" +
//							"	'0' IsDeleted,\r\n" +
//							"	'0' TenantId,\r\n" +
//							"	'1' MaterialVersion,\r\n" +
//							"	'0' Piece,\r\n" +
//							"	'0' IsSame\r\n" +
//							"FROM\r\n" +
//							"	MATERIALPACKING m\r\n" +
//							"LEFT JOIN MATERIALSHIPREQUESTDETAIL m2 ON\r\n" +
//							"	m.SHIPREQUESTNAME = m2.SHIPREQUESTNAME\r\n" +
//							"	AND m.MATERIALSPECNAME = m2.MATERIALSPECNAME \r\n" +
//							"	AND m.SDK_ID = m2.SDK_ID \r\n" +
//							"	AND m.PHASE = m2.PHASE \r\n" +
//							"LEFT JOIN VBC_TOBILL@NC_PRD T ON\r\n" +
//							"	m2.ERPDETAILID = T.DATAPK\r\n" +
//							"WHERE\r\n" +
//							"	m.STOCKSTATE = 'Stocked'\r\n" +
//							"	AND T.BILLPK IS NOT NULL AND   m.SHIPREQUESTNAME = ? AND m.MATERIALPACKINGNAME IN ";
//					String str = "(";
//					for (MaterialPacking m : detail) {
//						str += "'" + m.getMaterialPackingName() + "',";
//					}
//					str += "'') ";
//					List<NcDataDto> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().getJdbcTemplate().query(ncSql + str,  new Object[]{shipRequestName},
//							new BeanPropertyRowMapper(NcDataDto.class));
//					new Test().savePrintData(queryForList2);
//				}
//				List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> list = detail;
			}

			String optRemark = "";
//			InvoiceServiceImpl.SendERPStockOut20240802(shipRequestName, "SDK", user, list,commitDate, opCode, optRemark);
			InvoiceServiceImpl.StockUpOutSendSAPOrMES(shipRequestName, "SDK", user, list,commitDate,opCode);
		} catch (Exception e) {
		e.printStackTrace();
		throw e;
	}
	}
	
	@Transactional
	public void stockOutPalletDessignOrAssign(String materialPackingName,String materialSpecName,String shipRequestName,String materialQuantity,String materialQuantity2,String sdk_id,String phase,String user) throws CustomException {
		
//		MaterialshipRequest materialShipRequest = JSON.toJavaObject(in, MaterialshipRequest.class);
		String type = "Assign";
//		String materialPackingName = materialShipRequest.getMaterialPackingName();//标签
//		String materialSpecName = materialShipRequest.getMaterialSpecName();
//		String shipRequestName = materialShipRequest.getShipRequestName();
//		String materialQuantity = materialShipRequest.getMaterialQuantity();
//		String materialQuantity2 = materialShipRequest.getMaterialQuantity2();
//		String sdk_id = (materialShipRequest.getSdk_id() == null || "~".equals(materialShipRequest.getSdk_id().toString())) ? "" : materialShipRequest.getSdk_id();
//		String phase = materialShipRequest.getPhase() == null ? "" :  materialShipRequest.getPhase();
//		String user = materialShipRequest.getUser();
		//查询单据类型
				String sql = "SELECT\r\n" + 
						"	m.SHIPREQUESTTYPE ,\r\n" + 
						"	m.SHIPREQUESTDETAILTYPE,\r\n" + 
						"	t.MATERIALSPECNAME ,\r\n" + 
						"	SUM(t.REQUESTQUANTITY - t.ASSIGNEDQUANTITY) MINUSQTY,t.SDK_ID,t.PHASE\r\n" + 
						"FROM\r\n" + 
						"	MATERIALSHIPREQUESTDETAIL t\r\n" + 
						"LEFT JOIN MATERIALSHIPREQUEST m ON\r\n" + 
						"	t.SHIPREQUESTNAME = m.SHIPREQUESTNAME\r\n" + 
						"WHERE\r\n" + 
						"	m.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" + 
						"	AND t.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" + 
						"	AND (:SDK_ID IS NULL\r\n" + 
						"		OR t.SDK_ID = :SDK_ID)\r\n" + 
						"	AND (:PHASE IS NULL\r\n" + 
						"		OR t.PHASE = :PHASE)\r\n" + 
						"		GROUP BY m.SHIPREQUESTTYPE ,\r\n" + 
						"	m.SHIPREQUESTDETAILTYPE,\r\n" + 
						"	t.MATERIALSPECNAME,t.SDK_ID,t.PHASE\r\n" + 
						"ORDER BY\r\n" + 
						"	t.MATERIALSPECNAME ,\r\n" + 
						"	t.SDK_ID,\r\n" + 
						"	t.PHASE";
				Map<String, Object> hashMap = new HashMap<String,Object> ();
				hashMap.put("SHIPREQUESTNAME", shipRequestName);
				hashMap.put("MATERIALSPECNAME", materialSpecName);
				hashMap.put("SDK_ID", sdk_id);
				hashMap.put("PHASE", phase);
				List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
				if(Objects.isNull(queryForList) || queryForList.isEmpty()) {
					throw new CustomException("未找到对应的数据！");
				}
				String judge = "SELECT\r\n" + 
						"	m.SDK_ID,MATERIALSPECNAME,\r\n" + 
						"	m.PHASE,\r\n" + 
						"	 :MATERIALQUANTITY2    MATERIALQUANTITY2 , " + 
						"	m.SHIPREQUESTNAME,\r\n" + 
						"	m.STOCKSTATE,\r\n" + 
						"	m.PACKINGGRADE ,\r\n" + 
						"	CASE WHEN to_char(EXPIRINGDATE, 'yyyymmdd') >= to_char(SYSDATE, 'yyyymmdd') THEN 1\r\n" + 
						"	ELSE 0 END EXP, OQARESULTSTATE \r\n" + 
						"FROM\r\n" + 
						"	MATERIALPACKING m\r\n" + 
						"WHERE\r\n" + 
						"	m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
				Map<String, Object> hashMap2 = new HashMap<String,Object> ();
				hashMap2.put("MATERIALPACKINGNAME", materialPackingName);
				hashMap2.put("MATERIALQUANTITY2", materialQuantity);
				List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(judge, hashMap2);
				if (queryForList2 != null && queryForList2.size() > 0) {
					materialSpecName = queryForList2.get(0).get("MATERIALSPECNAME") == null ? "" : queryForList2.get(0).get("MATERIALSPECNAME").toString();
					sdk_id = (queryForList2.get(0).get("SDK_ID") == null || "~".equals(sdk_id))  ? "" : queryForList2.get(0).get("SDK_ID").toString();
					phase = queryForList2.get(0).get("PHASE") == null ? "" : queryForList2.get(0).get("PHASE").toString();
					materialQuantity2 = queryForList2.get(0).get("MATERIALQUANTITY2") == null ? "" : queryForList2.get(0).get("MATERIALQUANTITY2").toString();
					String  invoice = queryForList2.get(0).get("SHIPREQUESTNAME") == null ? "" : queryForList2.get(0).get("SHIPREQUESTNAME").toString();
					String stockState = queryForList2.get(0).get("STOCKSTATE") == null ? "" : queryForList2.get(0).get("STOCKSTATE").toString();
					String packinggrade  = queryForList2.get(0).get("PACKINGGRADE") == null ? "" : queryForList2.get(0).get("PACKINGGRADE").toString();
					String exp  = queryForList2.get(0).get("EXP") == null ? "" : queryForList2.get(0).get("EXP").toString();
					String oqaresultstate  = queryForList2.get(0).get("OQARESULTSTATE") == null ? "" : queryForList2.get(0).get("OQARESULTSTATE").toString();
					if (!"Stocked".equals(stockState)) {
						throw new CustomException("条码不在库！");
					}
					if (!"OK".equals(packinggrade)) {
						throw new CustomException("批次不合格！");
					}
					if (!"1".equals(exp)) {
						throw new CustomException("批次已过期！");
					}
					if (!"END".equals(oqaresultstate)) {
						throw new CustomException("未完成质检！");
					}
//					if (!"".equals(invoice)) {
//						return AjaxResult.me().setSuccess(false).setMessage("条码已被" + invoice + "备货！");
//					}
				} else {
					throw new CustomException("未找到对应的条码！");
				}
				String shipRequestType = queryForList.get(0).get("SHIPREQUESTTYPE").toString();
				String shipRequestDetailType = queryForList.get(0).get("SHIPREQUESTDETAILTYPE").toString();
				String minusQty = queryForList.get(0).get("MINUSQTY").toString();
				BigDecimal FmaterialQuantity = new BigDecimal(materialQuantity);
				BigDecimal FminusQty = new BigDecimal(minusQty);
				BigDecimal Fzero = new BigDecimal(0);
				//"SHIPREQUESTDETAILTYPE": "4Y-Cxx-03",//跨组织领料调拨单 
				//"BLSQ4K".equals(shipRequestType) || "4Y".equals(shipRequestType) || "CKSQ4I".equals(shipRequestType)
				int dy0 = FminusQty.compareTo(Fzero);
				MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
				com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
				if ("Assign".equals(type)) {
					System.out.println("4Y".equals(shipRequestType) + "*****************");
					if ("4Y".equals(shipRequestType)) {//调拨单
						if ( "4Y-Cxx-03".equals(shipRequestDetailType)) {
							if (dy0 < 0) {//只能超发一个
								throw new CustomException("只能超发一个不能出库了！");
							}
						} 
					} else if ("BLSQ4K".equals(shipRequestType)) {//领料
						if (dy0 < 0) {//只能超发一个
							throw new CustomException("只能超发一个不能出库了！");
						}
					} else if ("CKSQ4I".equals(shipRequestType)) { //其他出库
						if (dy0 < 0) {//只能超发一个
							throw new CustomException("只能超发一个不能出库了！");
						}
					} else if ("4C".equals(shipRequestType)) {
						if (dy0 <= 0) {//只能超发一个
							throw new CustomException("销售不允许超发！");
						}
					}else {
						throw new CustomException("单据类型不正确！");
					}
				} else if ("Dessign".equals(type)) {
					
				}
				try {
					InvoiceServiceImpl.ReserveByPallet(selectByKey, shipRequestName, materialSpecName,sdk_id, phase, type, "SDK", user,materialQuantity2,"Y");
				} catch (CustomException e) {
					e.printStackTrace();
					AjaxResult.me().setSuccess(false).setMessage(e.toString());
				}
	}
	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);
	}
}
