package com.cim.idm.controller;

import com.alibaba.fastjson.JSONObject;
import com.cim.idm.constants.receive.ReceiveTypeEnums;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.exception.IDMFrameDBErrorSignal;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.model.dto.delivery.StoreDetailDto;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.model.po.delivery.MaterialDelivery;
import com.cim.idm.model.vo.DeliveryReceiveDetailVo;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl;
import com.cim.idm.service.IDeliveryService;
import com.cim.idm.service.Impl.SDKMaterialPackingServiceImpl;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.GenericServiceProxy;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.material.MaterialServiceProxy;
import com.cim.idm.wmspackage.material.management.data.MaterialSpec;
import com.cim.idm.wmspackage.material.management.data.MaterialSpecKey;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.info.CreateInfo;
import com.cim.idm.wmspackage.materialreceiverequestact.MaterialReceiveRequestActServiceProxy;
import com.cim.idm.wmspackage.materialreceiverequestact.management.info.CreateReceiveRequestBatchInfo;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.MaterialReceiveRequestActDetailServiceProxy;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.management.info.ActDetailIncreaseInfo;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.management.info.CreateActDetailInfo;
import com.cim.idm.wmspackage.materialreceivetactdetail.management.data.MaterialReceiveActDetailKey;
import com.cim.idm.wmspackage.materialshiprequestdetail.MaterialShipRequestDetailServiceProxy;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.data.MaterialShipRequestDetailKey;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.MakeShipDetailIncreaseAssignedInfo;
import com.cim.idm.wmspackage.materialshiprequesttooem.MaterialShipRequestToOEMServiceProxy;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.data.MaterialShipRequestToOEMKey;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.info.MakeOEMDecreaseAssignedInfo;
import com.cim.idm.wmspackage.name.NameServiceProxy;
import com.cim.idm.wmspackage.receiverequestdetail.ReceiveRequestDetailServiceProxy;
import com.cim.idm.wmspackage.receiverequestdetail.management.data.MaterialReceiveRequestDetailKey;
import com.cim.idm.wmspackage.receiverequestdetail.management.info.MakeDetailIncreaseReceivedInfo;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api("不已批次管理入库")
@RestController
@RequestMapping("/api/NoCharge")
@EnableAutoConfiguration
public class NoChargeStockIn {

	private static Log log = LogFactory.getLog(MaterialReceiveRequestServiceImpl.class);
	SDKMaterialPackingServiceImpl SDKMP = new SDKMaterialPackingServiceImpl();

	@Resource
	private IDeliveryService deliveryService;

	@Autowired
	private ToSAPServiceImpl toSAPServiceImpl;

	@Transactional
	@RequestMapping(value = "/NoChargeStockIn", method = RequestMethod.POST)
	public AjaxResult NoChargeStockIn(@RequestBody JSONObject in ) throws Exception {
		// 将字符串转换为JSONArray对象  

		String ERPFACTORY="";
		String ERPLOCATION="";
		String LOCATIONNAME="";
//		String RECEIVEREQUESTNAME="";
//		String RECEIVEREQUESTDETAILNAME="";
		String MATERIALSPECNAME="";
		String MATERIALUNITDESC="";
		String MATERIALUNIT="";
		String REQUESTQUANTITY="";
		String RECEIVEDQUANTITY="";
		String ThisAcceptNumber="";
		String user="";
		String SiteName="";
		String MAKEDATE="";
		String receiveAct="";
		String sdkid="";
		String commitDate = "";
		String opCode = "";
		String siteName = (String)in.get("SITENAME");
		// 判定是否是到货单
		StoreDetailDto storeDetailDto = new StoreDetailDto();
		storeDetailDto.setSiteName(siteName);
		storeDetailDto.setDocumentName((String)in.get("RECEIVEREQUESTNAME"));
		MaterialDelivery byKey = deliveryService.getByKey(storeDetailDto);
		Boolean isDelivery = Objects.nonNull(byKey);
		//1、首先生成入库单
		//获取抬头文本
		try {
			receiveAct=GenerateMaterialReceiveRequestName("SDK","NoPO");
		} catch (CustomException e) {
			e.printStackTrace();
		}
		user=(String) in.get("USER");
		commitDate = in.get("commitDate").toString();
		opCode = in.get("opCode") == null ? "" : in.get("commitDate").toString();
		LinkedHashMap<String,String> linkedHashMap  = ( LinkedHashMap<String,String>) in.get("BOXLIST"); 
		EventInfo makeEventInfo=new EventInfoUtil().makeEventInfo("NoChargeStockIn", user, "NoChargeStockIn", "", "");
		//3、遍历map中的值
		Iterator it = linkedHashMap.entrySet().iterator();
		//校验仓库和货位的对应关系是否存在

		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Map NoPoList=(Map) entry.getValue();
			ERPFACTORY=(String) NoPoList.get("ERPFACTORY");
			ERPLOCATION=(String) NoPoList.get("ERPLOCATION");
			LOCATIONNAME= (NoPoList.get("LOCATIONNAME") == null  || "null".equals(NoPoList.get("LOCATIONNAME").toString())) ? "" : NoPoList.get("LOCATIONNAME").toString();
			MATERIALSPECNAME=(String) NoPoList.get("MATERIALSPECNAME");
			RECEIVEDQUANTITY=(String) NoPoList.get("RECEIVEDQUANTITY").toString();
			ThisAcceptNumber=(String) NoPoList.get("THISACCEPTNUMBER").toString();
			BigDecimal freceiveQty = new BigDecimal(ThisAcceptNumber);//实收数量
//			if (freceiveQty.compareTo(BigDecimal.ZERO) <= 0) {
//				return AjaxResult.me().setSuccess(false).setMessage("接收数量不能小于0");
//			}
			String is_oven = "N";
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(MATERIALSPECNAME);
			materialSpecKey.setSiteName("SDK");

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);
			String maturationflag = materialSpec.getMATURATIONFLAG();//熟化标识
			String is_CON_TEMP = materialSpec.getIS_CON_TEMP();//恒温恒湿
			/*
			//判断仓库是否启用了货位，但货位为空
			String sql = "SELECT be.USE_LOCATION,be.CONST_TEMP,be.IS_OVEN FROM BS_ERPLOCATION be WHERE be.ERPLOCATIONNAME = :ERPLOCATION";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("ERPLOCATION", ERPLOCATION);
			hashMap.put("LOCATIONNAME", LOCATIONNAME);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if (queryForList == null || queryForList.size() < 1) {
				throw new RuntimeException("仓库不存在");
			} else {
				String string = queryForList.get(0).get("USE_LOCATION") == null ? "" : queryForList.get(0).get("USE_LOCATION").toString();//启用货位
				String const_temp = queryForList.get(0).get("CONST_TEMP") == null ? "" : queryForList.get(0).get("CONST_TEMP").toString(); //恒温标识
				is_oven = queryForList.get(0).get("IS_OVEN") == null ? "" : queryForList.get(0).get("IS_OVEN").toString(); //熟化标识
				if ("Y".equals(string) && ("".equals(LOCATIONNAME) || LOCATIONNAME == null ))  {
					throw new RuntimeException("仓库启用了货位，但货位为空");
				}
				if ("N".equals(string) && (!"".equals(LOCATIONNAME)) )  {
					throw new RuntimeException("仓库未启用货位，货位为空");
				}

				if (!"".equals(LOCATIONNAME)) {
					String sql2 = "SELECT * FROM STORAGESPEC S WHERE S.STORAGENAME = :LOCATIONNAME AND S.ERPLOCATION = :ERPLOCATION ";
					List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, hashMap);
					if (queryForList2 == null || queryForList2.size() < 1) {
						throw new RuntimeException("仓库与货位对应关系不正确");
					}
				}

				String ckhw = "Y".equals(const_temp) ? "恒温恒湿" : "非恒温恒湿";
				String wlhw = "Y".equals(is_CON_TEMP) ? "恒温恒湿" : "非恒温恒湿";
				
				
				String cksh = "Y".equals(is_oven) ? "熟化" : "非熟化";
				String wlsh = "Y".equals(maturationflag) ? "熟化" : "非熟化";
				if (!const_temp.equals(is_CON_TEMP)) {
					throw new RuntimeException("仓库" + ckhw + "; 物料" + wlhw);
				}
				
				if (!is_oven.equals(maturationflag)) {
					throw new RuntimeException("仓库" + cksh + "; 物料" + wlsh);
				}
				
			}
			*/
		}

		Iterator its = linkedHashMap.entrySet().iterator();
		while (its.hasNext()) {
			Map.Entry entry = (Map.Entry) its.next();
			Map NoPoList=(Map) entry.getValue();
			ERPFACTORY=(String) NoPoList.get("ERPFACTORY");
			ERPLOCATION=(String) NoPoList.get("ERPLOCATION");
			LOCATIONNAME= (NoPoList.get("LOCATIONNAME") == null  || "null".equals(NoPoList.get("LOCATIONNAME").toString())) ? "" : NoPoList.get("LOCATIONNAME").toString();
			MATERIALSPECNAME=(String) NoPoList.get("MATERIALSPECNAME");
			MATERIALUNITDESC=(String) NoPoList.get("MATERIALUNITDESC");
			MATERIALUNIT=(String) NoPoList.get("MATERIALUNIT");
			REQUESTQUANTITY=(String) NoPoList.get("REQUESTQUANTITY").toString();
			RECEIVEDQUANTITY=(String) NoPoList.get("RECEIVEDQUANTITY").toString();
			ThisAcceptNumber= NoPoList.get("THISACCEPTNUMBER").toString();
			if ("0".equals(ThisAcceptNumber)) {
				continue;
			}
			SiteName=(String) NoPoList.get("SiteName");
			MAKEDATE=NoPoList.get("MakeDate") == null ? TimeStampUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss") : NoPoList.get("MakeDate").toString();
			sdkid=(String) NoPoList.get("SDK_ID");
			if(ThisAcceptNumber!=""&&ThisAcceptNumber!=null&&ThisAcceptNumber!="0")
			{
				// 获取单据详情
				List<DeliveryReceiveDetailVo> receiveByMaterialSpec = deliveryService.getReceiveByMaterialSpec(storeDetailDto.getDocumentName(), MATERIALSPECNAME, isDelivery);
				if (!receiveByMaterialSpec.isEmpty()) {
					for (DeliveryReceiveDetailVo vo : receiveByMaterialSpec) {
						//2、获取EventInfo
						makeEventInfo = new EventInfoUtil().makeEventInfo("NoChargeStockIn", user, "NoChargeStockIn", "", "");
						//4、写入入库单明细
						try {
							CreateMaterialReceiveRequestAct(makeEventInfo,"SDK",vo.getReceiveRequestName(),vo.getReceiveRequestDetailName(),MAKEDATE,receiveAct,"NoPO",ThisAcceptNumber,MATERIALSPECNAME);
						} catch (CustomException | ParseException e) {
							e.printStackTrace();
						}
						//5、查询物料是否启用批次
						String sql="SELECT CASE WHEN m.IS_BATCH  = 'Y' THEN '是' WHEN m.IS_BATCH  = '是' THEN '是' ELSE '否'  END AS REPLACED_VALUE ,DECODE(m.IQCFLAG,'Y','是','否')  IQCFLAG FROM MATERIALSPEC m WHERE m.MATERIALSPECNAME =:MATERIALSPECNAME";
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("MATERIALSPECNAME", MATERIALSPECNAME);
						List<Map<String, Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
						String IsBatch=(String) list.get(0).get("REPLACED_VALUE");
						String IQCFLAG=(String) list.get(0).get("IQCFLAG");
						//6、创建标签
						try {
							//插入过账条码
							PackingAndSub( makeEventInfo, "SDK","",  ThisAcceptNumber, "1",ThisAcceptNumber, "N",vo.getReceiveRequestName(),vo.getReceiveRequestDetailName(),MATERIALSPECNAME,receiveAct, MAKEDATE, "","", "","", ERPLOCATION, ERPFACTORY,"", "", "","","",LOCATIONNAME,"","",MATERIALUNIT,IsBatch,IQCFLAG,sdkid);


						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		//7、过账
		// 采购单
		List<MaterialReceiveRequest> requests = new ArrayList<>();
		if (isDelivery) {
			// 到货单据
			requests = deliveryService.getReceiveByDelivery(storeDetailDto);
		} else {
			requests.add(deliveryService.getReceiveByKey(storeDetailDto));
		}
		for (MaterialReceiveRequest request : requests) {
			String billcode = null;
			// 采购订单
//			if (ReceiveTypeEnums.isPurchase(request.getReceiveRequestType())) {
				Map<String,Object> args = new HashMap<>();
				billcode = toSAPServiceImpl.PurStockIn(request.getReceiveRequestName(), siteName, user, args,commitDate);
//			}else {
//				billcode = toSAPServiceImpl.SaleReturn(request.getReceiveRequestName(), siteName, user, commitDate, opCode);
//			}
			// @TODO 其他类型
			if (billcode == null || "".equals(billcode)) {
				return AjaxResult.me().setErrorCode(500).setSuccess(false).setMessage("SAP过账失败");
			}
			//8、更新物料凭证
			SDKMP.updateUndoID(receiveAct,makeEventInfo,billcode);
			//9、接收ERP返回消息更新WMS凭证
			// SDKMP.SaveUnDoInfo(receiveAct,billcode);
			SDKMP.SaveUnDoInfo(billcode,commitDate);//传值错误，导致凭证信息未存储，已修改。zd.2024.9.24
			//10、更新库存状态
			//SDKMP.updateStockState(receiveAct,makeEventInfo,billcode);
			SDKMP.updateStockState(makeEventInfo, billcode,opCode);

		}
		return AjaxResult.me().setMessage("入库成功");
	}

	/*
	 * Name : GenerateMaterialReceiveRequestName Desc : This function is
	 * GenerateMaterialReceiveRequestName Author : boe cim dev. Date :
	 * 2016.02.17
	 */
	public static String GenerateMaterialReceiveRequestName( String siteName, String actType) throws CustomException {
		// 获取系统当前时间
		Calendar c = Calendar.getInstance();
		SimpleDateFormat f = new SimpleDateFormat(
				"yyyyMMdd");

		List<String> args = new ArrayList<String>();
		String actType1 = "";
		if (actType.equals("Normal") || actType.equals("Manual")|| actType.equals("ManualR")
				||actType.equals("BMDTOEM")  ||actType.equals("B5OEM")
				|| actType.equals("Reserve") ||actType.equals("ERPReserve")|| actType.equals("NormalIDO")
				|| actType.equals("NoPO")||actType.equals("SHIPOEM")) {
			actType1 = "R";
		}else if (actType.equals("RMA") || actType.equals("OEMReturn")) {
			actType1 = "F";
		}
		else if (actType.equals("Scrapped")) {
			actType1 = "B";
		} else if (actType.equals("Refund") || actType.equals("RefundOEM")
				|| actType.equals("WO") || actType.equals("POOEM")
				|| actType.equals("ManualT")||actType.equals("MES")||actType.equals("MESRefund")) {
			actType1 = "T";
		} else if (actType.equals("STCO")) {
			actType1 = "C";
		}else if(actType.equals("PSO"))
		{
			actType1 = "S";
		}
		else if(actType.equals("unUsual"))
		{
			actType1="U";
		}
		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("SDK")){
			siteName="SDK";
		}
		args.add(siteName);
		args.add(actType1);
		args.add(f.format(c.getTime()));

		String ReceiveRequestActNo;

		ReceiveRequestActNo = NameServiceProxy.getNameRuleDefService()
				.generateName("ReceiveActNo", args, 1).get(0);
		try {
			return ReceiveRequestActNo;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add(siteName);
			args.add(actType);
			args.add(f.format(c.getTime()));
			ReceiveRequestActNo = NameServiceProxy.getNameRuleDefService()
					.generateName("ReceiveActNo", args, 1).get(0);
			return ReceiveRequestActNo;
		}
	}

	/*
	 * Name : CreateMaterialReceiveRequestAct Desc :
	 * CreateMaterialReceiveRequestAct Author : boe cim dev. Date : 2016.02.17
	 */
	public void CreateMaterialReceiveRequestAct(EventInfo eventInfo,
			String siteName, String receiveRequestName,
			String ReceiveRequestDetailName, String makeDate,
			String receiveActNo, String actType, String receiveQuantity,
			String subMaterialSpecName) throws CustomException, ParseException {
		String actType1 = "";
		String newReceiveRequestDetailName = "";
		if (actType.equals("POOEM")) {
			newReceiveRequestDetailName = ReceiveRequestDetailName + "_"
					+ subMaterialSpecName;
		}
		// receiveRequestName="lixiaolongtest1";
		// ReceiveRequestDetailName="lixiaolongtestDetail";
		// makeDate="2016-02-17 20:17:59";
		// receiveActNo="testabc1";

		/*
		 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 * Timestamp date = (Timestamp) sdf.parse(makeDate);
		 */

		float ReceiveQuantity = Float.parseFloat(receiveQuantity);

		// receiveActInfo
		MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
		// MaterialReceiveActDetail materialReceiveActDetail = new
		// MaterialReceiveActDetail();
		CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();
		//
		materialReceiveActDetailKey.setSiteName(siteName);
		materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
		if (actType.equals("POOEM")) {
			materialReceiveActDetailKey.setReceiveRequestDetailName(newReceiveRequestDetailName);
		} else {
			materialReceiveActDetailKey.setReceiveRequestDetailName(ReceiveRequestDetailName);
		}

		materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
		materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

		// materialReceiveActDetail=
		// MaterialReceiveRequestActDetailServiceProxy.getMaterialReceiveRequestActDetailService().selectByKey(materialReceiveActDetailKey);

		String sql = "SELECT * FROM materialreceiveactdetail WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("sitename", siteName);
		bindMap.put("receiveRequestName", receiveRequestName);
		if (actType.equals("POOEM")) {
			bindMap.put("ReceiveRequestDetailName", newReceiveRequestDetailName);
		} else {
			bindMap.put("ReceiveRequestDetailName", ReceiveRequestDetailName);
		}
		bindMap.put("receiveActNo", receiveActNo);
		bindMap.put("makeDate", Timestamp.valueOf(makeDate));

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);

		String sql1 = "SELECT * FROM materialreceiveact "
				+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName  and receiveActNo=:receiveActNo ";

		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("sitename", siteName);
		bindMap1.put("receiveRequestName", receiveRequestName);
		bindMap1.put("receiveActNo", receiveActNo);

		List<Map<String, Object>> queryResult1 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql1, bindMap1);
		if (queryResult1.size() != 0) {
			actType1 = queryResult1.get(0).get("ACTTYPE").toString();
		}
		if (queryResult1.size() == 0) {
			CreateReceiveRequestBatchInfo createActBatchInfo = new CreateReceiveRequestBatchInfo();
			List<CreateReceiveRequestBatchInfo> createReceiveRequestBatchInfo = new ArrayList<CreateReceiveRequestBatchInfo>();

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

			List<String> materialReceiveRequestAct;
			// String quantity="10";
			String product = "qwe";
			String grade = "w";
			String line = "q";
			String revisionCode = "r";

			createActBatchInfo.setSiteName(siteName);
			createActBatchInfo.setReceiveRequestName(receiveRequestName);
			createActBatchInfo.setReceiveactNO(receiveActNo);
			createActBatchInfo.setReceiveActState("Created");

			bindMap2.put("actType", actType);
			// bindMap2.put("receiveActState", );
			createActBatchInfo.setUserColumns(bindMap2);

			createReceiveRequestBatchInfo.add(createActBatchInfo);

			MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().create(eventInfo,createReceiveRequestBatchInfo);
		}

		if (queryResult.size() == 0) {
			createActDetailInfo.setReceiveActNO(receiveActNo);
			createActDetailInfo.setReceiveRequestName(receiveRequestName);
			if (actType.equals("POOEM")) {
				createActDetailInfo
				.setReceiveRequestDetailName(newReceiveRequestDetailName);
			} else {
				createActDetailInfo
				.setReceiveRequestDetailName(ReceiveRequestDetailName);
			}
			createActDetailInfo.setSiteName(siteName);

			// Date date1 = new Date();//获取当前时间
			// SimpleDateFormat sdf = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// String str = sdf.format(date1);//时间存储为字符串
			// System.out.println(str);
			createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
			createActDetailInfo.setReceiveQuantity(ReceiveQuantity);

			Map<String, Object> bindMap3 = new HashMap<String, Object>();
			bindMap3.put("receiveActState", "Created");
			createActDetailInfo.setUserColumns(bindMap3);

			MaterialReceiveRequestActDetailServiceProxy
			.getMaterialReceiveRequestActDetailService().create(
					eventInfo, createActDetailInfo);

			//			因为float精度问题，再更新一次
			try {
				log.info("创建BOX点击，更新抬头文本明细行大数据 ==========> ");
				String updateSql= " UPDATE MATERIALRECEIVEACTDETAIL SET RECEIVEQUANTITY = :QTY WHERE RECEIVEACTNO = :RECEIVEACTNO"
						+ " AND RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
				Map<String, Object> updateMap = new HashMap<String, Object>();
				updateMap.put("QTY", receiveQuantity);
				updateMap.put("RECEIVEACTNO", receiveActNo);
				updateMap.put("RECEIVEREQUESTNAME", receiveRequestName);
				updateMap.put("RECEIVEREQUESTDETAILNAME", createActDetailInfo.getReceiveRequestDetailName());
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
			} catch (IDMFrameDBErrorSignal e) {
				//				e.printStackTrace();
				log.info("创建BOX，更新抬头文本明细行大数据时失败 ==========> ");
			}

		} else {
			ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
			actDetailIncreaseInfo.setReceiveQuantity(ReceiveQuantity);

			MaterialReceiveRequestActDetailServiceProxy
			.getMaterialReceiveRequestActDetailService()
			.increaseReceivedQuantity(materialReceiveActDetailKey,
					eventInfo, actDetailIncreaseInfo);
		}

		if (actType.equals("NoPO") || actType1.equals("NoPO")
				|| actType.equals("Normal") || actType1.equals("Normal")
				|| actType.equals("NormalIDO") || actType1.equals("NormalIDO")) {
			//if(!siteName.equals("B7")){
			if(siteName.equals("B7")){
				MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
				MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
				materialReceiveRequestDetailKey
				.setReceiveRequestName(receiveRequestName);
				materialReceiveRequestDetailKey.setSiteName(siteName);
				materialReceiveRequestDetailKey
				.setReceiveRequestDetailName(ReceiveRequestDetailName);

				makeDetailIncreaseReceivedInfo.setIncreaseQuantity(ReceiveQuantity);

				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
				.increaseReceivedQuantity(materialReceiveRequestDetailKey,
						eventInfo, makeDetailIncreaseReceivedInfo);

			}else {
				//float型计算精度缺失问题
				Map<String, Object> bindMapF = new HashMap<String, Object>();
				Map<String, Object> bindMapFU = new HashMap<String, Object>();
				String receivedQuantiryF="";
				bindMapF.put("receiveRequestName",receiveRequestName);
				bindMapF.put("ReceiveRequestDetailName", ReceiveRequestDetailName);
				bindMapF.put("sitename", siteName);
				String sqlF="SELECT  RECEIVEDQUANTITY FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME=:sitename AND RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEREQUESTDETAILNAME=:ReceiveRequestDetailName";
				String sqlFU="UPDATE MATERIALRECEIVEREQUESTDETAIL SET RECEIVEDQUANTITY=:receivedQuantity WHERE SITENAME=:sitename AND RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEREQUESTDETAILNAME=:ReceiveRequestDetailName";
				List<Map<String, Object>> queryResultF = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlF, bindMapF);
				if(queryResultF.size()!=0){
					receivedQuantiryF=queryResultF.get(0).get("RECEIVEDQUANTITY").toString();
				}
				//				BigDecimal receivequantity=new BigDecimal(String.valueOf(ReceiveQuantity));
				BigDecimal receivequantity=new BigDecimal(String.valueOf(receiveQuantity));
				BigDecimal receivedQuantiry=new BigDecimal(receivedQuantiryF);
				bindMapFU.put("receivedQuantity", receivequantity.add(receivedQuantiry).doubleValue());
				bindMapFU.put("sitename", siteName);
				bindMapFU.put("receiveRequestName", receiveRequestName);
				bindMapFU.put("ReceiveRequestDetailName", ReceiveRequestDetailName);
				IDMFrameServiceProxy.getSqlTemplate().update(sqlFU, bindMapFU);
			}


		}
		// else if(actType.equals("POOEM"))
		// {
		// MakeOEMIncreaseInfo makeOEMIncreaseInfo =new MakeOEMIncreaseInfo();
		// MaterialShipRequestToOEMKey materialShipRequestToOEMKey =new
		// MaterialShipRequestToOEMKey();
		// materialShipRequestToOEMKey.setReceiveRequestName(receiveRequestName);
		// materialShipRequestToOEMKey.setSiteName(siteName);
		// materialShipRequestToOEMKey.setReceiveRequestDetailName(ReceiveRequestDetailName);
		//
		// makeOEMIncreaseInfo.setIncreaseQuantity(ReceiveQuantity);
		//
		// MaterialShipRequestToOEMServiceProxy.getMaterialShipRequestToOEMService().in(materialShipRequestToOEMKey,
		// eventInfo, makeOEMIncreaseInfo);
		// }
		else if (actType.equals("POOEM") || actType1.equals("POOEM")) {

			MakeOEMDecreaseAssignedInfo makeOEMDecreaseAssignedInfo = new MakeOEMDecreaseAssignedInfo();
			MaterialShipRequestToOEMKey materialShipRequestToOEMKey = new MaterialShipRequestToOEMKey();
			materialShipRequestToOEMKey
			.setReceiveRequestName(receiveRequestName);
			materialShipRequestToOEMKey.setSiteName(siteName);
			materialShipRequestToOEMKey
			.setReceiveRequestDetailName(ReceiveRequestDetailName);
			materialShipRequestToOEMKey
			.setSubMaterialSpecName(subMaterialSpecName);
			makeOEMDecreaseAssignedInfo.setAssignedQuantity(ReceiveQuantity);

			MaterialShipRequestToOEMServiceProxy
			.getMaterialShipRequestToOEMService()
			.decreaseAssignedQuantity(materialShipRequestToOEMKey,
					eventInfo, makeOEMDecreaseAssignedInfo);
		}
		// else if(!actType.equals("POOEM")||!actType1.equals("POOEM"))
		else {
			if(siteName.equals("B7")){
				MakeShipDetailIncreaseAssignedInfo makeShipDetailIncreaseAssignedInfo = new MakeShipDetailIncreaseAssignedInfo();
				MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
				materialShipRequestDetailKey.setShipRequestName(receiveRequestName);
				materialShipRequestDetailKey.setSiteName(siteName);
				materialShipRequestDetailKey
				.setShipRequestDetailName(ReceiveRequestDetailName);

				makeShipDetailIncreaseAssignedInfo
				.setAssignedQuantity(ReceiveQuantity);

				MaterialShipRequestDetailServiceProxy
				.getMaterialShipRequestDetailService()
				.increaseAssignedQuantity(materialShipRequestDetailKey,
						makeShipDetailIncreaseAssignedInfo);
			}else{
				//float型计算精度缺失问题
				Map<String, Object> bindMapF = new HashMap<String, Object>();
				Map<String, Object> bindMapFU = new HashMap<String, Object>();
				String receivedQuantiryF="";
				bindMapF.put("shipRequestName",receiveRequestName);
				bindMapF.put("shipRequestDetailName", ReceiveRequestDetailName);
				bindMapF.put("sitename", siteName);
				String sqlF="SELECT  ASSIGNEDQUANTITY FROM MATERIALSHIPREQUESTDETAIL WHERE SITENAME=:sitename AND SHIPREQUESTNAME=:shipRequestName AND SHIPREQUESTDETAILNAME=:shipRequestDetailName";
				String sqlFU="UPDATE MATERIALSHIPREQUESTDETAIL SET ASSIGNEDQUANTITY=:receivedQuantity WHERE SITENAME=:sitename AND SHIPREQUESTNAME=:shipRequestName AND SHIPREQUESTDETAILNAME=:shipRequestDetailName";
				List<Map<String, Object>> queryResultF = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlF, bindMapF);
				if(queryResultF.size()!=0){
					receivedQuantiryF=queryResultF.get(0).get("ASSIGNEDQUANTITY").toString();
				}
				//				BigDecimal receivequantity=new BigDecimal(String.valueOf(ReceiveQuantity));
				BigDecimal receivequantity=new BigDecimal(String.valueOf(receiveQuantity));
				BigDecimal receivedQuantiry=new BigDecimal(receivedQuantiryF);
				bindMapFU.put("receivedQuantity", receivequantity.add(receivedQuantiry).doubleValue());
				bindMapFU.put("sitename", siteName);
				bindMapFU.put("shipRequestName", receiveRequestName);
				bindMapFU.put("shipRequestDetailName", ReceiveRequestDetailName);
				IDMFrameServiceProxy.getSqlTemplate().update(sqlFU, bindMapFU);
			}	
		}
	}

	public static String Packing(EventInfo eventInfo, String siteName,
			String areaName, String receiveQty, String boxQuantity,
			String EveryBoxQuantity, String boxFlag, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName,
			String receiveActNo, String makeDate, String shipRequestName,
			String shipRequestDetailName, String reasonCodeType,
			String reasonCode, String erpLocation, String erpFactory,
			String charge, String supplierName, String NPFlag,String expirationDay,String supplierCharge,
			String locationName,String phase,String specName,String materialUnit,
			String IS_BATCH,String IQCFLAG,String sdkid) throws Exception {

		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<String> boxId;
		float EveryBoxQuantity1 = 0;
		BigDecimal everyQty = new BigDecimal(receiveQty);
		BigDecimal sumQty = BigDecimal.ZERO;
		try {
			if (boxFlag.equals("Y")) {
				float tempV = Math.round((Float.valueOf(receiveQty) - (Float
						.valueOf(boxQuantity) - 1)
						* Float.valueOf(EveryBoxQuantity)) * 100);
				// float v=(float) (tempV/100.00);
				EveryBoxQuantity1 = (float) (tempV / 100.00);
				// float num=(float)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
					boxQuantity, makeDate,"WL",erpFactory);

			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			// try{
			// materialSpec=MaterialSpecServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
			// }
			// catch(NotFoundSignal e)
			// {
			// e.s
			// }
			Map<String, Object> box_quantity = new HashMap<String, Object>();
			int i = 0;			
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				if (i == boxId.size() - 1) {
					EveryBoxQuantity = Float.valueOf(receiveQty) - Float.valueOf(EveryBoxQuantity) * (boxId.size() - 1) + "";
				}
				//470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
				String newBoxId = materialSpecName + "|1|" + phase + "|" + specName + "|" + boxId.get(i) + "|" 
						+ makeDate.replace("-", "").substring(0, 8) + "|" + materialUnit + "|" + EveryBoxQuantity;
				materialPacking.setMaterialPackingName(newBoxId);
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());				
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
						: receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;
				//bindMap.put("ReceiveTime", eventInfo.getEventTime());
				//bindMap.put("ReceiveUser", eventInfo.getEventUser());
				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("SDK_ID", sdkid);
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if(expirationDay==null||expirationDay.equals(""))
				{
					if(materialSpec.getExpirationDay()>0)
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();  
						rightNow.setTime(endTime);  
						if(siteName.equals("TM1"))
						{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
							rightNow.set(Calendar.DAY_OF_MONTH,rightNow.get(Calendar.DAY_OF_MONTH)-1);
						}
						else{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());  
						}
						Date dt1 = rightNow.getTime();  
						expirationDay = sDateFormat.format(dt1);  
					}
					else 
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();  
						rightNow.setTime(endTime);  
						rightNow.add(Calendar.MONTH, 48);  
						Date dt1 = rightNow.getTime();  
						expirationDay = "2099-12-31 00:00:00";  

						//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
						//endTime = (endTime).(materialSpec.getExpirationDay());
					}
					//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
					//endTime = (endTime).(materialSpec.getExpirationDay());
				}


				//this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
				bindMap.put("makeDate", makeDate);
				bindMap.put("expiringDate", expirationDay.substring(0,expirationDay.indexOf(" "))+" 00:00:00");
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("unit", materialUnit);
				if ("是".equals(IS_BATCH)) {
					bindMap.put("charge", boxId.get(i));
				}
				if ("否".equals(IQCFLAG)) {
					bindMap.put("oqaResultState", GenericServiceProxy.getConstantMap().OQA_State_End);
					bindMap.put("oqaResult","OK");
					bindMap.put("packingGrade", "OK");
				} else {
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
				}
				//bindMap.put("phase", phase);
				//bindMap.put("supplierCharge", supplierCharge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				bindMap.put("locationName", locationName);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);

				box_quantity.put(boxId.get(i), EveryBoxQuantity);  // 防大数据float精度丢失

				/** 计算最后一箱的数量 */
				//				BigDecimal nextQty = new BigDecimal(EveryBoxQuantity);
				//				sumQty = sumQty.add(nextQty);
				//				if(nextQty.compareTo(everyQty.subtract(sumQty)) > 0) {
				//					EveryBoxQuantity = everyQty.subtract(sumQty).toString();
				//				}

			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

			//			因为float精度问题，再更新一次
			try {
				//				for(CreateInfo creatInfo : listMaterialPacking) {
				//					String updateSql= " UPDATE MATERIALPACKING SET MATERIALCREATEQUANTITY = :QTY,MATERIALQUANTITY = :QTY"
				//							+ " WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND SITENAME = :SITENAME";
				//					Map<String, Object> updateMap = new HashMap<String, Object>();
				//					updateMap.put("QTY", box_quantity.get(creatInfo.getMaterialPackingName()));
				//					updateMap.put("MATERIALPACKINGNAME", creatInfo.getMaterialPackingName());
				//					updateMap.put("SITENAME", siteName);
				//					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
				//				}
			} catch (IDMFrameDBErrorSignal e) {
				//				e.printStackTrace();
				log.info("创建BOX，更新大数据时失败 ==========> ");
			}

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}

	public static String PackingAndSub(EventInfo eventInfo, String siteName,
								 String areaName, String receiveQty, String boxQuantity,
								 String EveryBoxQuantity, String boxFlag, String receiveRequestName,
								 String receiveRequestDetailName, String materialSpecName,
								 String receiveActNo, String makeDate, String shipRequestName,
								 String shipRequestDetailName, String reasonCodeType,
								 String reasonCode, String erpLocation, String erpFactory,
								 String charge, String supplierName, String NPFlag,String expirationDay,String supplierCharge,
								 String locationName,String phase,String specName,String materialUnit,
								 String IS_BATCH,String IQCFLAG,String sdkid) throws Exception {

		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<String> boxId;
		float EveryBoxQuantity1 = 0;
		BigDecimal everyQty = new BigDecimal(receiveQty);
		BigDecimal sumQty = BigDecimal.ZERO;
		try {
			if (boxFlag.equals("Y")) {
				float tempV = Math.round((Float.valueOf(receiveQty) - (Float
						.valueOf(boxQuantity) - 1)
						* Float.valueOf(EveryBoxQuantity)) * 100);
				// float v=(float) (tempV/100.00);
				EveryBoxQuantity1 = (float) (tempV / 100.00);
				// float num=(float)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
					boxQuantity, makeDate,"WL",erpFactory);

			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			// try{
			// materialSpec=MaterialSpecServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
			// }
			// catch(NotFoundSignal e)
			// {
			// e.s
			// }
			Map<String, Object> box_quantity = new HashMap<String, Object>();
			int i = 0;
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				if (i == boxId.size() - 1) {
					EveryBoxQuantity = Float.valueOf(receiveQty) - Float.valueOf(EveryBoxQuantity) * (boxId.size() - 1) + "";
				}
				//470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
				String newBoxId = materialSpecName + "|1|" + phase + "|" + specName + "|" + boxId.get(i) + "|"
						+ makeDate.replace("-", "").substring(0, 8) + "|" + materialUnit + "|" + EveryBoxQuantity;
				materialPacking.setMaterialPackingName(newBoxId);
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "Created");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
						: receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;
				bindMap.put("ReceiveTime", eventInfo.getEventTime());
				bindMap.put("ReceiveUser", eventInfo.getEventUser());
				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("SDK_ID", sdkid);
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if(expirationDay==null||expirationDay.equals(""))
				{
					if(materialSpec.getExpirationDay()>0)
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						if(siteName.equals("TM1"))
						{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
							rightNow.set(Calendar.DAY_OF_MONTH,rightNow.get(Calendar.DAY_OF_MONTH)-1);
						}
						else{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
						}
						Date dt1 = rightNow.getTime();
						expirationDay = sDateFormat.format(dt1);
					}
					else
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						rightNow.add(Calendar.MONTH, 48);
						Date dt1 = rightNow.getTime();
						expirationDay = "2099-12-31 00:00:00";

						//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
						//endTime = (endTime).(materialSpec.getExpirationDay());
					}
					//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
					//endTime = (endTime).(materialSpec.getExpirationDay());
				}


				//this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
				bindMap.put("makeDate", makeDate);
				bindMap.put("expiringDate", expirationDay.substring(0,expirationDay.indexOf(" "))+" 00:00:00");
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("unit", materialUnit);
				if ("是".equals(IS_BATCH)) {
					bindMap.put("charge", boxId.get(i));
				}
				if ("否".equals(IQCFLAG)) {
					bindMap.put("oqaResultState", GenericServiceProxy.getConstantMap().OQA_State_End);
					bindMap.put("oqaResult","OK");
					bindMap.put("packingGrade", "OK");
				} else {
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
				}
				bindMap.put("phase", phase);
				//bindMap.put("supplierCharge", supplierCharge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				bindMap.put("locationName", locationName);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);

				String insertSql = "INSERT INTO MATERIALPACKINGSUB T (T.MATERIALPACKINGNAME,T.RECEIVEREQUESTNAME,T.RECEIVEREQUESTDETAILNAME,T.QTY) "
						+ "VALUES (:MATERIALPACKINGNAME, :RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:QTY)";
				Map<String, Object> hashMap2 = new HashMap<String,Object> ();
				hashMap2.put("MATERIALPACKINGNAME", newBoxId);
				hashMap2.put("RECEIVEREQUESTNAME", receiveRequestName);
				hashMap2.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName);
				hashMap2.put("QTY", EveryBoxQuantity);
				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);

				box_quantity.put(boxId.get(i), EveryBoxQuantity);  // 防大数据float精度丢失

				/** 计算最后一箱的数量 */
				//				BigDecimal nextQty = new BigDecimal(EveryBoxQuantity);
				//				sumQty = sumQty.add(nextQty);
				//				if(nextQty.compareTo(everyQty.subtract(sumQty)) > 0) {
				//					EveryBoxQuantity = everyQty.subtract(sumQty).toString();
				//				}

			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

			//			因为float精度问题，再更新一次
			try {
				//				for(CreateInfo creatInfo : listMaterialPacking) {
				//					String updateSql= " UPDATE MATERIALPACKING SET MATERIALCREATEQUANTITY = :QTY,MATERIALQUANTITY = :QTY"
				//							+ " WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND SITENAME = :SITENAME";
				//					Map<String, Object> updateMap = new HashMap<String, Object>();
				//					updateMap.put("QTY", box_quantity.get(creatInfo.getMaterialPackingName()));
				//					updateMap.put("MATERIALPACKINGNAME", creatInfo.getMaterialPackingName());
				//					updateMap.put("SITENAME", siteName);
				//					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
				//				}
			} catch (IDMFrameDBErrorSignal e) {
				//				e.printStackTrace();
				log.info("创建BOX，更新大数据时失败 ==========> ");
			}

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}
}
