//package com.cim.idm.controller;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.cim.idm.data.ErpMessageLog;
//import com.cim.idm.exception.GlobalException;
//import com.cim.idm.framework.IDMFrameServiceProxy;
//import com.cim.idm.framework.data.EventInfo;
//import com.cim.idm.framework.orm.SqlTemplate;
//import com.cim.idm.framework.util.sys.SystemPropHelper;
//import com.cim.idm.framework.util.time.TimeStampUtil;
//import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
//import com.cim.idm.service.Impl.ProductIntoServiceImpl;
//import com.cim.idm.service.Impl.ReturnStockIntoServiceImpl;
//import com.cim.idm.service.QMSService;
//import com.cim.idm.service.impl.ToSAPServiceImpl;
//import com.cim.idm.util.MessageLogUtil;
//import com.cim.idm.utils.AjaxResult;
//import com.cim.idm.utils.CommonUtils;
//import com.cim.idm.utils.EventInfoUtil;
//import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
//import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
//import com.cim.idm.wmspackage.name.NameServiceProxy;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiResponse;
//import io.swagger.annotations.ApiResponses;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//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.sql.Timestamp;
//import java.text.ParseException;
//import java.util.*;
//
//@Api("接收MES请求接口")
//@RestController
//@RequestMapping("/api/wms")
//@Slf4j
//public class MESController {
//
//
//	@Autowired
//	private ToSAPServiceImpl toSAPService;
//	@Autowired
//	private SqlTemplate sqlTemplate;
//	@Autowired
//	private ProductIntoServiceImpl productIntoServiceImpl;
//	@Autowired
//	private ReturnStockIntoServiceImpl returnStockIntoServiceImpl;
//	@Autowired
//	private QMSService qmsService;
//
//
//	// 提取公共方法：更新库存
//	private void updateMaterialPackingStock(List<String> boxIdList, List<String> qtyList) {
//	    String sqlu = "UPDATE MATERIALPACKINGMDC m SET m.MATERIALQUANTITY = m.MATERIALQUANTITY - :QTY, "
//	                + "m.EVENTTIME = SYSDATE, m.EVENTNAME = :EVENTNAME WHERE m.CHARGE = :CHARGE";
//	    for (int j = 0; j < boxIdList.size(); j++) {
//	        Map<String, Object> bp = new HashMap<>();
//	        bp.put("CHARGE", boxIdList.get(j));
//	        bp.put("QTY", qtyList.get(j));
//	        bp.put("EVENTNAME", "MESCONSUME");
//	        IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bp);
//	    }
//	}
//
//	// 提取公共方法：插入BS_MES_SHIPPED表
//	@Transactional
//	private void insertIntoBsMesShipped(Map<String, Object> bindMap)  throws RuntimeException {
//	    String insertSql = "INSERT INTO BS_MES_SHIPPED(LOTNAME, QTY, UNIT, REQUESTNAME, AREA, "
//	                     + "PRODUCTSPECNAME, PRODUCTNAME, SDK_ID, PHASE, RECEIVE_FLAG, REMARK, SHIPTIME, "
//	                     + "SHIPUSER, SITENAME, MATERIALSPECTYPE, INVENTORYTYPE, SALENO, SALEDETAILNO, "
//	                     + "ERPLOCATION, CHARGE, LOCATIONNAME, OPERATIONTYPE, ERPFACTORY, GXID) "
//	                     + "VALUES(:LOTNAME, :QTY, :UNIT, :REQUESTNAME, :AREA, :PRODUCTSPECNAME, "
//	                     + ":PRODUCTNAME, :SDK_ID, :PHASE, 'N', :REMARK, :SHIPTIME, 'MES', 'SDK', "
//	                     + ":MATERIALSPECTYPE, :INVENTORYTYPE, :SALENO, :SALEDETAILNO, :ERPLOCATION, "
//	                     + ":CHARGE, :LOCATIONNAME, :OPERATIONTYPE, :ERPFACTORY, :GXID)";
//		int update = sqlTemplate.update(insertSql, bindMap);
//		if (update != 1) {
//			throw new RuntimeException("插入BS_MES_SHIPPED表失败");
//		}
//	}
//
//	// 优化后的materialConsume_Request方法
//
//	@ApiOperation(value = "物料消耗请求")
//	@RequestMapping(value = "/meswms_materialconsume_request", method = RequestMethod.POST)
//	public AjaxResult materialConsume_Request(@RequestBody JSONArray in) {
//	    log.debug("***********************************");
//	    log.debug("RCRQ " + in.toString());
//	    log.debug("***********************************");
//	    AjaxResult result = new AjaxResult();
//	    ErpMessageLog loginfo = new ErpMessageLog();
//	    loginfo.setServerName("MESToWms");
//	    loginfo.setMessageId("");
//	    loginfo.setEventUser("MES");
//	    loginfo.setId(TimeStampUtil.getCurrentEventTimeKey());
//	    loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
//	    loginfo.setSendMsg(in.toJSONString());
//	    loginfo.setEventName("materialConsume_Request");
//
//	    List<String> boxIdList = new ArrayList<>();
//	    List<String> qtyList = new ArrayList<>();
//	    String wo = "";
//	    try {
//	        for (int i = 0; i < in.size(); i++) {
//	            JSONObject jb = in.getJSONObject(i);
//	            String charge = jb.getString("charge"); // 批号
//	            String qty = jb.getString("qty"); // 消耗数量
//	            wo = jb.getString("requestName"); // 工单
//	            boxIdList.add(charge);
//	            qtyList.add(qty);
//	        }
//	        // 调用SAP服务
//	        String undoId = toSAPService.mesMaterialConsume(boxIdList, qtyList, "MES", wo);
//	        // 更新库存
//	        updateMaterialPackingStock(boxIdList, qtyList);
//
//	        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
//	        loginfo.setResultCode("0");
//	        loginfo.setReturnMsg(JSONObject.toJSONString(result));
//	    } catch (Exception e) {
//	        log.error("物料消耗失败: {}", e.getMessage());
//	        result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage(e.toString());
//	        loginfo.setResultCode("1");
//	        loginfo.setReturnMsg(JSONObject.toJSONString(result));
//	    } finally {
//	        MessageLogUtil.writeMessageLog(loginfo);
//	    }
//	    return result;
//	}
//
//	//MES接收物料后调用。触发WMS进行出库过帐。zd.2024.8.23
//	@ApiOperation(value = "物料出库请求")
//	@RequestMapping(value = "/meswms_materialout_request", method = RequestMethod.POST)
//	public AjaxResult materialOutByMES(@RequestBody JSONArray in) {
//		log.debug("***********************************");
//		log.debug("RCRQ "+in.toString());
//		log.debug("***********************************");
//		AjaxResult result = new AjaxResult();
//		ErpMessageLog loginfo = new ErpMessageLog();
//		loginfo.setServerName("MESToWms");
//		loginfo.setMessageId("");
//		loginfo.setEventUser("MES");
//		loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
//		loginfo.setSendMsg(in.toJSONString());
//		loginfo.setEventName("MaterialOut_Request");
//
//		List<String> boxIdList = new ArrayList<> ();
//		String shipRequestName="";
//		for (int i = 0; i < in.size(); i++) {
//			JSONObject jb = in.getJSONObject(i);
//			String charge = jb.get("charge").toString();//批号
//			shipRequestName= jb.get("shipRequestName").toString();//领料单号
//			boxIdList.add(charge);
//
//		}
//		try {
//
//			String billCode=new ToSAPServiceImpl().ProductionStockOut_NEW(shipRequestName, "SDK", "MES",boxIdList);
//
//			EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("CompleteShipRequest", "MES", "CompleteShipRequest:MES Receive");
//			new CommonUtils().SaveUnDoInfo_ForSap(boxIdList, billCode, makeEventInfo);
//
//
//			result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
//			loginfo.setResultCode("S");
//			loginfo.setReturnMsg(JSONObject.toJSONString(result));
//			// 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
//			MessageLogUtil.writeMessageLog(loginfo);
//		}catch(Exception e) {
//			result = AjaxResult.me().setSuccess(false).setErrorCode(1).setMessage("执行失败");
//			loginfo.setResultCode("E");
//			loginfo.setReturnMsg(JSONObject.toJSONString(result));
//			// 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
//			MessageLogUtil.writeMessageLog(loginfo);
//		}
//		return result;
//	}
//
//	@ApiOperation(value = "取消入库请求")
//	@RequestMapping(value = "/meswms_cancelship_request", method = RequestMethod.POST)
//	public AjaxResult cancelShipByMES(@RequestBody JSONArray in) {
//		log.debug("***********************************");
//		log.debug("RCRQ "+in.toString());
//		log.debug("***********************************");
//		AjaxResult result = new AjaxResult();
//		ErpMessageLog loginfo = new ErpMessageLog();
//		loginfo.setServerName("MESToWms");
//		loginfo.setMessageId("");
//		loginfo.setEventUser("MES");
//		loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
//		loginfo.setSendMsg(in.toJSONString());
//		loginfo.setEventName("CancelShip_Request");
//
//		List<String> boxIdList = new ArrayList<> ();
//		//首先查看要退料还是退产成品
//		//
//		for (int i = 0; i < in.size(); i++) {
//			JSONObject jb = in.getJSONObject(i);
//			String charge = jb.get("charge").toString();//批号
//			boxIdList.add(charge);
//
//		}
//		try {
//			String sqld = "DELETE FROM BS_MES_SHIPPED  b WHERE b.CHARGE in(:BOXIDLIST) AND NVL(b.receive_flag,'N')<>'Y' ";
//			Map<String, Object> hashMap = new HashMap<String,Object> ();
//			hashMap.put("BOXIDLIST", boxIdList);
//			IDMFrameServiceProxy.getSqlTemplate().update(sqld, hashMap);
//
//			result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
//			loginfo.setResultCode("S");
//			loginfo.setReturnMsg(JSONObject.toJSONString(result));
//			// 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
//			MessageLogUtil.writeMessageLog(loginfo);
//		}catch(Exception e) {
//			result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage("执行失败");
//			loginfo.setResultCode("E");
//			loginfo.setReturnMsg(JSONObject.toJSONString(result));
//			// 消息保存日志，erp推送wms的数据写入表BS_ERPMESSAGELOG中
//			MessageLogUtil.writeMessageLog(loginfo);
//		}
//		return result;
//	}
//
//
//	// 优化后的shipByMES方法
//	@ApiOperation(value = "物料入库请求")
//	@RequestMapping(value = "/meswms_ship_request", method = RequestMethod.POST)
//	public AjaxResult shipByMES(@RequestBody JSONArray in)  {
//	    log.debug("***********************************");
//	    log.debug("RCRQ " + in.toString());
//	    log.debug("***********************************");
//	    AjaxResult result = new AjaxResult();
//	    ErpMessageLog loginfo = new ErpMessageLog();
//	    try {
//	        loginfo.setServerName("MESToWms");
//	        loginfo.setMessageId("");
//	        loginfo.setEventUser("MES");
//	        loginfo.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
//	        loginfo.setSendMsg(in.toJSONString());
//	        loginfo.setEventName("Ship_Request");
//
//	        List<String> boxIdList = new ArrayList<>();
//	        List<String> barCodeList = new ArrayList<>();
//	        String stockInType = "";
//	        String operationType = "";
//	        if (in != null && in.size() > 0) {
//	            for (int i = 0; i < in.size(); i++) {
//	                JSONObject jo = in.getJSONObject(i);
//	                String charge = jo.getString("charge");
//	                String lotname = jo.getString("lotName");
//	                boxIdList.add(charge);
//	                barCodeList.add(lotname);
//
//	                // 插入BS_MES_SHIPPED表
//	                Map<String, Object> bindMap = new HashMap<>();
//	                bindMap.put("LOTNAME", lotname);
//	                bindMap.put("QTY", jo.getDoubleValue("qty"));
//	                bindMap.put("UNIT", jo.getString("unit"));
//	                bindMap.put("REQUESTNAME", jo.getString("requestName"));
//	                bindMap.put("AREA", jo.getString("area"));
//	                bindMap.put("PRODUCTSPECNAME", jo.getString("productSpecName"));
//	                bindMap.put("PRODUCTNAME", jo.getString("productName"));
//	                bindMap.put("SDK_ID", jo.getString("sdkId"));
//	                bindMap.put("PHASE", jo.getString("phase"));
//	                bindMap.put("REMARK", jo.getString("remark"));
//	                bindMap.put("SHIPTIME", TimeStampUtil.getTimestamp(jo.getString("shipTime")));
//	                bindMap.put("SHIPUSER", jo.getString("shipUser"));
//	                bindMap.put("INVENTORYTYPE", jo.getString("inventoryType"));
//	                bindMap.put("SALENO", jo.getString("saleNo"));
//	                bindMap.put("SALEDETAILNO", jo.getString("saleDetailNo"));
//	                bindMap.put("ERPLOCATION", jo.getString("erpLocation"));
//	                bindMap.put("LOCATIONNAME", jo.getString("locationName"));
//	                bindMap.put("OPERATIONTYPE", jo.getString("operationType"));
//	                bindMap.put("ERPFACTORY", jo.getString("erpFactory"));
//	                bindMap.put("MATERIALSPECTYPE", jo.getString("stockInType"));
//	                bindMap.put("CHARGE", charge);
//	                bindMap.put("GXID", jo.getString("gxId"));
//
//	                insertIntoBsMesShipped(bindMap);
//	            }
//	        }
//	        result = AjaxResult.me().setSuccess(true).setErrorCode(200).setMessage("执行成功");
//	        loginfo.setResultCode("S");
//	        loginfo.setReturnMsg(JSONObject.toJSONString(result));
//	    } catch (Exception e) {
//	        log.error("发货失败: {}", e.getMessage());
//	        result = AjaxResult.me().setSuccess(false).setErrorCode(500).setMessage(e.toString());
//	        loginfo.setResultCode("E");
//	        loginfo.setReturnMsg(JSONObject.toJSONString(result));
//	    } finally {
//	        MessageLogUtil.writeMessageLog(loginfo);
//	    }
//	    return result;
//	}
//}
//
//
