package com.cim.idm.service.Impl;

import com.cim.idm.exception.GlobalException;
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.service.OtherInService;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.CommonUtils;
import com.cim.idm.utils.EventInfoUtil;
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 com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OtherInServiceImpl implements OtherInService {

	CommonUtils CU=new CommonUtils();

	@Autowired
	private ToSAPServiceImpl toSAPService;

	/**
	 *
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingName
	 * @param user
	 * @param receiveActNo
	 * @param erpLocation
	 * @param erpFactory
	 * @param locationName
	 * @param receiveRequestName
	 * @param receiveRequestDetailName
	 * @return
	 */
	public boolean CreateBoxByOtherInfo(EventInfo eventInfo,String siteName,String materialPackingName,
			String user,String receiveActNo,String erpLocation,String erpFactory,String locationName,
			String receiveRequestName, String receiveRequestDetailName)  {
		
		
		// 470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
		//条码里面截取所需信息
		String[] split = materialPackingName.split("\\|");
		String materialSpecName = split[0];
		String chagre = split[4];
		String makeDate = CU.ChangeTime(split[5]);
		String unit = split[6];
		String qty = split[7];
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT\r\n" + 
				"	M2.MATERIALTYPE , M.SDK_ID ,M.PHASE ,M2.MATERIALSPECNAME \r\n" + 
				"FROM\r\n" + 
				"	MATERIALRECEIVEREQUESTDETAIL M\r\n" + 
				"LEFT JOIN MATERIALSPEC M2 ON\r\n" + 
				"	M.MATERIALSPECNAME = M2.MATERIALSPECNAME\r\n" + 
				"WHERE\r\n" + 
				"	M.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME\r\n" + 
				"	AND M.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME");
		//		sql.append(" AND M.SITENAME = :SITENAME ");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		hashMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		
		//入库信息存入库存表
		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("MaterialType", queryForList.get(0).get("MATERIALTYPE"));
		bindMap.put("MaterialSpecName", materialSpecName);
		bindMap.put("PackingGrade", "OK");
		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", queryForList.get(0).get("AREANAME"));
		bindMap.put("locationName", locationName);
		bindMap.put("charge",chagre);
		bindMap.put("unit",unit);
//		bindMap.put("DurableName", durableName);
//		bindMap.put("MaterialProcessGroupName",
//				"");
		bindMap.put("LastEventTimeKey",
				TimeStampUtil.getCurrentEventTimeKey());
		bindMap.put("ReceiveRequestName", receiveRequestName);
		bindMap.put("ReceiveRequestDetailName",receiveRequestDetailName);
		bindMap.put("MakeDate", makeDate);
		bindMap.put("oqaResult", makeDate);
		bindMap.put("oqaResultState", makeDate);
		bindMap.put("expiringDate", getExpridate(makeDate, materialSpecName));
		bindMap.put("ReceiveTime", eventInfo.getEventTime());
		bindMap.put("ReceiveUser", eventInfo.getEventUser());
		bindMap.put("ShipTime",makeDate);
		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", queryForList.get(0).get("SDK_ID"));
		bindMap.put("PHASE", queryForList.get(0).get("PHASE"));
		createInfo.setUserColumns(bindMap);
		MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName,materialPackingName);
		MaterialPackingServiceProxy.getMaterialPackingService().create(
				eventInfo, createInfo);
		return true;
	}


	/**
	 *
	 * @param receiveRequestName
	 * @param siteName
	 * @param eventUser
	 * @param receiveActno
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean OtherStockIn (String receiveRequestName,String siteName,String eventUser, String receiveActno) throws Exception {
		String billCode = toSAPService.qtrNoInvoice(receiveRequestName, siteName,eventUser,receiveActno);
		if (billCode == null) {
			throw new GlobalException("报送ERP失败,请联系IT处理！");
		}
		EventInfo makeEventInfo = new EventInfoUtil().makeEventInfo("OtherStockIn", eventUser, "OtherStockIn", "", "");
		//更新抬头文本状态和Box状态
		String sql = "SELECT M.SITENAME ,M.MATERIALPACKINGNAME FROM MATERIALPACKING M WHERE M.RECEIVEACTNO = :RECEIVEACTNO";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("RECEIVEACTNO", receiveActno);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		for (Map<String, Object> map : queryForList) {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey(map.get("SITENAME").toString(),map.get("MATERIALPACKINGNAME").toString());
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("unDoID", billCode);
			bindMap.put("stockState", "Stocked");
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
		}
		String sql2 = "UPDATE MATERIALRECEIVEACT M SET M.RECEIVEACTSTATE = 'Received' WHERE M.RECEIVEACTNO = :RECEIVEACTNO";
		Map<String, Object> hashMap2 = new HashMap<String,Object> ();
		hashMap2.put("RECEIVEACTNO", receiveActno);
		IDMFrameServiceProxy.getSqlTemplate().update(sql2, hashMap2);
		SaveUnDoInfo( billCode);
		//更新MES标识
		return true;
		
	}



	/**
	 *
	 * @param undoid
	 */
	public void SaveUnDoInfo( String undoid) {

		String insertUnDOMaterialPackingInfo = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,"
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG)"
				+ "select unDoID,'' as preundoid,UNDODETAILNAME,'Completed' as undoidstate,TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS UNDOIDDATE," //
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG"
				+ " from MATERIALPACKING  "
				+ " where unDoID=:UNDOID";

		Map<String, Object> bindMap_insert = new HashMap<String, Object>();
		bindMap_insert.put("UNDOID", undoid);
		IDMFrameServiceProxy.getSqlTemplate()
				.update(insertUnDOMaterialPackingInfo, bindMap_insert);

	}

	public  EventInfo makeEventInfo( String eventName, String eventUser, String eventComment,
			String reasonCodeType, String reasonCode )
	{
		EventInfo eventInfo = new EventInfo();
		
		eventInfo.setBehaviorName( "" );
		eventInfo.setEventName( eventName );
		eventInfo.setEventUser( eventUser );
		
		if ( eventComment == null )
			eventComment = "";
		
		eventInfo.setEventComment( eventComment );
		eventInfo.setEventTime( TimeStampUtil.getCurrentTimestamp());
		// Do Not Check TimeKey Validation
		eventInfo.setCheckTimekeyValidation(false);
		eventInfo.setEventTimeKey(TimeStampUtil.getCurrentEventTimeKey());
		if ( reasonCodeType == null )
			reasonCodeType = "";
		
		eventInfo.setReasonCodeType( reasonCodeType );
		
		if ( reasonCode == null )
			reasonCode = "";
		
		eventInfo.setReasonCode( reasonCode );
		
		return eventInfo;
	}
	
	
	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 "";
	}
}
