package com.cim.idm.mwmsextend.material.service;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.springframework.dao.DataAccessException;

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.exception.ext.NotFoundSignal;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.material.MaterialServiceProxy;
import com.cim.idm.wmspackage.material.management.data.MaterialSpecKey;
import com.cim.idm.wmspackage.material.management.info.CreateSpecInfo;
import com.cim.idm.wmspackage.material.management.info.RemoveSpecInfo;
import com.cim.idm.wmspackage.material.management.info.SetSpecEventInfo;

public class MaterialServiceImpl {

	private static Log log = LogFactory.getLog(MaterialServiceImpl.class);
	public void create(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName,
			String materialType, 
			String materialUnit, 
			String materialGroup, 
			String desc_cn,
			String desc_en,
			String erpLocation,
			String expirationDateFlag,
			String expirationDay,
			String inspectA,
			String inspectP,
			String inspectV,
			String erpFactory,
			String maxSafetyStock,
			String minSafetyStock,
			String bondedFlag,
			String checkState) throws CustomException
	{

	
		if(siteName=="B9"){
			
			try {
				int incertFlag = 0;
				String sql = "SELECT * FROM MATERIALSPEC "
						+ "WHERE MATERIALSPECNAME = :materialSpecName";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("materialSpecName", materialSpecName);
				
				List<Map<String, Object>> queryResult = 
						IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
				if (queryResult == null || queryResult.isEmpty())
					{incertFlag = 1;}
				else{				
					throw new CustomException("CHARGEFLAG", materialSpecName);
				}

				if(incertFlag==1){
					CreateSpecInfo createSpecInfo = new CreateSpecInfo();
					createSpecInfo.setSiteName(siteName);
					createSpecInfo.setMaterialSpecName(materialSpecName);
					createSpecInfo.setMaterialType(materialType);
					createSpecInfo.setMaterialUnit((materialUnit));
					createSpecInfo.setMaterialGroup(materialGroup);
					createSpecInfo.setDesc_cn(desc_cn);
					createSpecInfo.setDesc_en(desc_en);
					createSpecInfo.setErpLocation(erpLocation);
					createSpecInfo.setExpirationDateFlag("N");
					createSpecInfo.setExpirationDay(Integer.parseInt("0"));
					
					createSpecInfo.setCheckState("CheckedIn");
					
					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("inspectA",inspectA);
					bindMap1.put("inspectP",inspectP);
					bindMap1.put("inspectV",inspectV);
					bindMap1.put("erpFactoryName", erpFactory);
					bindMap1.put("maxSafetyStock",maxSafetyStock);
					bindMap1.put("minSafetyStock", minSafetyStock);
					bindMap1.put("bondedFlag", bondedFlag);
					createSpecInfo.setUserColumns(bindMap1);
					
					createSpecInfo.setCreateUser(eventInfo.getEventUser());
					createSpecInfo.setCreateTime(eventInfo.getEventTime());
					
					eventInfo.setEventName("CreateMaterialSpec");
					
					MaterialServiceProxy.getMaterialSpecService().create(eventInfo, createSpecInfo);
				}
			} catch (DataAccessException e) {
				// TODO Auto-generated catch block
				throw new CustomException("CHARGEFLAG", materialSpecName);
			}
		}else{
	
			//B11区分F1材料和其余材料
			if(siteName.equals("B11"))
			{
				List<String> templist=new ArrayList<String>();
				String tempErpFactory="";
				if(erpFactory.equals("2800")){
					
					String[] array={"107B","107N","110B","110N"};
					templist=Arrays.asList(array);
					tempErpFactory="2811";
				}else if(erpFactory.equals("2809")){
					
					String[] array={"906B","906N","922B","922N"};
					templist=Arrays.asList(array);
					tempErpFactory="2812";
				}
				
				if(templist.contains(erpLocation))
				{
					siteName="BBF1";
					erpFactory=tempErpFactory;
				}
			}
		CreateSpecInfo createSpecInfo = new CreateSpecInfo();
		createSpecInfo.setSiteName(siteName);
		createSpecInfo.setMaterialSpecName(materialSpecName);
		createSpecInfo.setMaterialType(materialType);
		createSpecInfo.setMaterialUnit((materialUnit));
		createSpecInfo.setMaterialGroup(materialGroup);
		createSpecInfo.setDesc_cn(desc_cn);
		createSpecInfo.setDesc_en(desc_en);
		createSpecInfo.setErpLocation(erpLocation);
		createSpecInfo.setExpirationDateFlag(expirationDateFlag);
		createSpecInfo.setExpirationDay(Integer.parseInt(expirationDay));
		createSpecInfo.setCheckState("CheckedIn");
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("inspectA",inspectA);
		bindMap.put("inspectP",inspectP);
		bindMap.put("inspectV",inspectV);
		bindMap.put("erpFactoryName", erpFactory);
		bindMap.put("maxSafetyStock",maxSafetyStock);
		bindMap.put("minSafetyStock", minSafetyStock);
		bindMap.put("bondedFlag", bondedFlag);
		createSpecInfo.setUserColumns(bindMap);
		
		createSpecInfo.setCreateUser(eventInfo.getEventUser());
		createSpecInfo.setCreateTime(eventInfo.getEventTime());
		
		eventInfo.setEventName("CreateMaterialSpec");
		
		MaterialServiceProxy.getMaterialSpecService().create(eventInfo, createSpecInfo);
		}
	}
	
	public void modify(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName,
			String description,
			String checkState,
			String createUser,
			String checkoutUser,
			String desc_cn,
			String desc_en,
			String materialType,
			String materialGroup,
			String materialGroupDescription,			
			String materialUnit,
			String expirationDateFlag,
			String expirationDay,
			String stockinEffectiveDay,
			String erpLocation,
			String materialWeight,			
			String inspectA,
			String inspectP,
			String inspectV,
			String erpFactory,
			String maxSafetyStock,
			String minSafetyStock,
			String bondedFlag)
	{

		MaterialSpecKey key = new MaterialSpecKey();
		key.setSiteName(siteName);
		key.setMaterialSpecName(materialSpecName);
		
		SetSpecEventInfo info = new SetSpecEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
				
		bindMap.put("description", description);
//		bindMap.put("checkState", checkState);
		bindMap.put("createUser", createUser);
		bindMap.put("checkoutUser", checkoutUser);
		bindMap.put("desc_cn", desc_cn);
		bindMap.put("desc_en", desc_en);
		bindMap.put("materialType", materialType);
		bindMap.put("materialGroup", materialGroup);
		bindMap.put("materialGroupDescription", materialGroupDescription);
		bindMap.put("materialUnit", materialUnit);
		
		if(siteName.equals("TM1")||siteName.equals("B9"))
		{
			String sql2 = "select distinct EXPIRATIONDAY,EXPIRATIONDATEFLAG from materialspec  WHERE  MATERIALSPECNAME = :materialSpecName and SITENAME = :siteName";
			   Map<String, Object> bindMap1 = new HashMap<String, Object>();
			   bindMap1.put("siteName", siteName);
			   bindMap1.put("materialSpecName", materialSpecName);		   		 			
				List<Map<String, Object>> queryResult=
						IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, bindMap1);
			String expirationDay1= queryResult.get(0).get("EXPIRATIONDAY").toString();
			String expirationDateFlag1= queryResult.get(0).get("EXPIRATIONDATEFLAG").toString();
			bindMap.put("expirationDay", Integer.parseInt(expirationDay1));	
			bindMap.put("expirationDateFlag", expirationDateFlag1);
		}
		else{
		bindMap.put("expirationDay", Integer.parseInt(expirationDay));	
		bindMap.put("expirationDateFlag", expirationDateFlag);
		}
		bindMap.put("stockinEffectiveDay", Integer.parseInt((stockinEffectiveDay.equals("")?"0":stockinEffectiveDay)));
		bindMap.put("erpLocation", erpLocation);
		bindMap.put("materialWeight", Double.parseDouble((materialWeight.equals("")?"0":materialWeight)));
		
		bindMap.put("inspectA", inspectA);
		bindMap.put("inspectP", inspectP);
		bindMap.put("inspectV", inspectV);
		
		bindMap.put("erpFactoryName", erpFactory);
		bindMap.put("maxSafetyStock", maxSafetyStock);
		bindMap.put("minSafetyStock", minSafetyStock);
		bindMap.put("bondedFlag", bondedFlag);
		
		info.setUserColumns(bindMap);
		
		eventInfo.setEventName("ModifyMaterialSpec");
		
		MaterialServiceProxy.getMaterialSpecService().setEvent(key, eventInfo, info);
		
	}
	
	public void createMaterialSpecShipDef(String siteName,String materialSpecName,
			String ERPLocation,String ERPFactoryName,String type)throws Exception{
		String sql = "";
		if(type.equals("Create")){
			sql = "INSERT INTO BS_MATERIALSHIPDEF "
					+ " ( "
					+ " SITENAME, "
					+ " MATERIALSPECNAME, "
					+ " ERPFACTORYNAME, "
					+ " ERPLOCATION "
					+ " ) "
					+ " VALUES ( "
					+ " :SITENAME,"
					+ " :MATERIALSPECNAME, "
					+ " :ERPFACTORYNAME, "
					+ " :ERPLOCATION "
					+ " ) ";
		}
		else if(type.equals("Update")){
			sql = " UPDATE BS_MATERIALSHIPDEF SET ERPFACTORYNAME=:ERPFACTORYNAME,ERPLOCATION=:ERPLOCATION "
					+ " WHERE SITENAME=:SITENAME "
					+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
		}
		else if(type.equals("Remove")){
			sql = " DELETE FROM BS_MATERIALSHIPDEF "
					+ " WHERE SITENAME=:SITENAME "
					+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
		}
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("ERPFACTORYNAME", ERPFactoryName);
		bindMap.put("MATERIALSPECNAME", materialSpecName);
		bindMap.put("SITENAME", siteName);
		bindMap.put("ERPLOCATION",ERPLocation);
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		
	}
	
	public void createSpec(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName,
			String description,
			String checkState, 

			String createUser,

			String checkoutUser,
			String desc_cn,
			String desc_en,
			String materialType,
			String materialGroup,
			String materialGroupDescription,
			
			String materialUnit,
			String expirationDateFlag,
			String expirationDay,
			String stockinEffectiveDay,
			String erpLocation,
			String materialWeight,
			String erpFactoryname,
			String materialSpecType)
	{
		CreateSpecInfo createSpecInfo = new CreateSpecInfo();
		createSpecInfo.setSiteName(siteName);
		createSpecInfo.setMaterialSpecName(materialSpecName);
		createSpecInfo.setDescription(description);
		createSpecInfo.setCheckState(checkState);
				
		createSpecInfo.setCreateUser(createUser);
		
		createSpecInfo.setCheckoutUser(checkoutUser);
		createSpecInfo.setDesc_cn(desc_cn);
		createSpecInfo.setDesc_en(desc_en);
		createSpecInfo.setMaterialType(materialType);
		createSpecInfo.setMaterialGroup(materialGroup);
		createSpecInfo.setMaterialGroupDescription(materialGroupDescription);
		createSpecInfo.setMaterialUnit(materialUnit);
		createSpecInfo.setExpirationDateFlag(expirationDateFlag);
		createSpecInfo.setExpirationDay(Integer.parseInt(expirationDay));
		createSpecInfo.setStockinEffectiveDay(Integer.parseInt(stockinEffectiveDay));
		createSpecInfo.setErpLocation(erpLocation);

		double f = Double.parseDouble(materialWeight);
		
		createSpecInfo.setMaterialWeight(f);
		
		
		Map<String, Object> bindMap1 = new HashMap<String, Object>();		
		bindMap1.put("erpFactoryName", erpFactoryname);
		bindMap1.put("materialSpecType", materialSpecType);
		createSpecInfo.setUserColumns(bindMap1);
		
		MaterialServiceProxy.getMaterialSpecService().create(eventInfo, createSpecInfo);
		
		String sql = "INSERT INTO BS_MATERIALSPECCHARGEFLAG (ERPFACTORYNAME,MATERIALSPECNAME,ERPCHARGEFLAG,EVENTUSER,EVENTTIME," +
				 " EXPIRATIONDATEFLAG,EXPIRATIONDAY,INSPECTA,INSPECTP,INSPECTV) VALUES (:erpFactoryname,:materialSpecName,:erpChargeFlag,:eventUser,:eventTime," +
				 " :expirationDateFlag,:expirationDay,:INSPECTA,:INSPECTP,:INSPECTV)";
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("erpFactoryname", erpFactoryname);
		bindMap.put("materialSpecName", materialSpecName);
		bindMap.put("erpChargeFlag", expirationDateFlag);
		bindMap.put("eventUser", eventInfo.getEventUser());
		bindMap.put("eventTime", eventInfo.getEventTime());
		bindMap.put("expirationDateFlag", expirationDateFlag);
		bindMap.put("expirationDay", expirationDay);
		bindMap.put("INSPECTA", "");
		bindMap.put("INSPECTP", "");
		bindMap.put("INSPECTV", "");
		
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		
	}
	
	public void modifySpec(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName,
			String description,
			String checkState,
			String createUser,
			String checkoutUser,
			String desc_cn,
			String desc_en,
			String materialType,
			String materialGroup,
			String materialGroupDescription,			
			String materialUnit,
			String expirationDateFlag,
			String expirationDay,
			String stockinEffectiveDay,
			String erpLocation,
			String materialWeight,	
			String erpFactoryname,
			String inspectA,
			String inspectP,
			String inspectV,
			String materialSpecType)
	{
		MaterialSpecKey key = new MaterialSpecKey();
		key.setSiteName(siteName);
		key.setMaterialSpecName(materialSpecName);
		
		SetSpecEventInfo info = new SetSpecEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
				
		bindMap.put("description", description);
		bindMap.put("checkState", checkState);
		bindMap.put("createUser", createUser);
		bindMap.put("checkoutUser", checkoutUser);
		bindMap.put("desc_cn", desc_cn);
		bindMap.put("desc_en", desc_en);
		bindMap.put("materialType", materialType);
		bindMap.put("materialGroup", materialGroup);
		bindMap.put("materialGroupDescription", materialGroupDescription);
		bindMap.put("materialUnit", materialUnit);
		bindMap.put("expirationDateFlag", expirationDateFlag);
		bindMap.put("expirationDay", Integer.parseInt(expirationDay));		
		bindMap.put("stockinEffectiveDay", Integer.parseInt((stockinEffectiveDay.equals("")?"0":stockinEffectiveDay)));
		bindMap.put("erpLocation", erpLocation);
		bindMap.put("materialWeight", Double.parseDouble((materialWeight.equals("")?"0":materialWeight)));
//		bindMap.put("inspectA", inspectA);
//		bindMap.put("inspectP", inspectP);
//		bindMap.put("inspectV", inspectV);
		bindMap.put("materialSpecType", materialSpecType);
		info.setUserColumns(bindMap);
		
		eventInfo.setEventName("ModifyMaterialSpec");
		
		MaterialServiceProxy.getMaterialSpecService().setEvent(key, eventInfo, info);
		
		String sql = "UPDATE BS_MATERIALSPECCHARGEFLAG SET EXPIRATIONDATEFLAG = :EXPIRATIONDATEFLAG , EXPIRATIONDAY = :EXPIRATIONDAY WHERE ERPFACTORYNAME = :ERPFACTORYNAME AND MATERIALSPECNAME= :MATERIALSPECNAME";
		
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		
		bindMap1.put("EXPIRATIONDATEFLAG", expirationDateFlag);
		bindMap1.put("EXPIRATIONDAY", Integer.parseInt(expirationDay));
		bindMap1.put("ERPFACTORYNAME", erpFactoryname);
		bindMap1.put("MATERIALSPECNAME", materialSpecName);
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap1);
		
	}
	
	public void reomveSpec(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName)
	{
       /* String sql="DELETE FROM BS_MATERIALSPECCHARGEFLAG WHERE MATERIALSPECNAME=:MATERIALSPECNAME";
		
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("MATERIALSPECNAME", materialSpecName);
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap1);*/
		
		MaterialSpecKey key = new MaterialSpecKey();
		key.setSiteName(siteName);
		key.setMaterialSpecName(materialSpecName);
		RemoveSpecInfo info = new RemoveSpecInfo();
		eventInfo.setEventName("DeleteMaterialSpec");
		MaterialServiceProxy.getMaterialSpecService().remove(key, eventInfo, info);
		
		
		
	}
	public void createShowLifeSign(List<String> siteNameList,List<String> materialSpecNameList ,EventInfo eventInfo)
		throws Exception
	{
		List<MaterialSpecKey> keyList = new ArrayList<MaterialSpecKey>();
		for(int i=0;i<materialSpecNameList.size();i++){
			MaterialSpecKey  keyInfo = new MaterialSpecKey();
			keyInfo.setMaterialSpecName(materialSpecNameList.get(i));
			keyInfo.setSiteName(siteNameList.get(i));
			keyList.add(keyInfo);
		}
		SetSpecEventInfo setEventInfo = new SetSpecEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("boardFlag","Y");
		setEventInfo.setUserColumns(bindMap);
		try {
			MaterialServiceProxy.getMaterialSpecService().setEvent(keyList, eventInfo, setEventInfo);
		}catch(IDMFrameDBErrorSignal ex){
			log.error(ex,ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex,ex);
			throw ex;
		}
			
	}
	public void removeShowLifeSign(List<String> siteNameList,List<String> materialSpecNameList,EventInfo eventInfo)
			throws Exception
		{
			List<MaterialSpecKey> keyList = new ArrayList<MaterialSpecKey>();
			for(int i=0;i<materialSpecNameList.size();i++){
				MaterialSpecKey  keyInfo = new MaterialSpecKey();
				keyInfo.setMaterialSpecName(materialSpecNameList.get(i));
				keyInfo.setSiteName(siteNameList.get(i));
				keyList.add(keyInfo);
			}
			SetSpecEventInfo setEventInfo = new SetSpecEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("boardFlag","N");
			setEventInfo.setUserColumns(bindMap);
			try {
				MaterialServiceProxy.getMaterialSpecService().setEvent(keyList, eventInfo, setEventInfo);
			}catch(IDMFrameDBErrorSignal ex){
				log.error(ex,ex);
				throw ex;
			}catch(NotFoundSignal ex){
				log.error(ex,ex);
				throw ex;
			}
				
		}
	public String checkChargeFlag(EventInfo eventInfo,String flag, 
			String materialSpecName,String erpFactoryName, String expirationDateFlag,String expirationDay, String inspectA,String inspectP,String inspectV,String del_flag,String bondedFlag ) throws CustomException{
		try {
			int incertFlag = 0;
			String sql = "SELECT * FROM BS_MATERIALSPECCHARGEFLAG "
					+ "WHERE ERPFACTORYNAME = :ERPFactoryName AND  MATERIALSPECNAME = :materialSpecName";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("ERPFactoryName", erpFactoryName);
			bindMap.put("materialSpecName", materialSpecName);
			
			List<Map<String, Object>> queryResult = 
					IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
			if (queryResult == null || queryResult.isEmpty())
				incertFlag = 1;
			else{
				//if(!flag.equals(queryResult.get(0).get("ERPCHARGEFLAG")!=null?queryResult.get(0).get("ERPCHARGEFLAG").toString():""))
					incertFlag = 2;
			}
			if(incertFlag==1){
				 String sql_insert = "INSERT INTO BS_MATERIALSPECCHARGEFLAG(ERPFACTORYNAME, MATERIALSPECNAME,ERPCHARGEFLAG, expirationDateFlag,EXPIRATIONDAY,EVENTTIME, EVENTUSER,INSPECTA,INSPECTP,INSPECTV,BONDEDFLAG) "
						   + "VALUES(:ERPFactoryName, :materialSpecName, :erpChargeFlag, :expirationDateFlag, :expirationDay, :eventTime, :eventUser,:inspectA,:inspectP,:inspectV,:BONDEDFLAG)";
				 Map<String, Object> bindMap1 = new HashMap<String, Object>();
				 bindMap1.put("ERPFactoryName", erpFactoryName);
				 bindMap1.put("materialSpecName", materialSpecName);
				 bindMap1.put("erpChargeFlag", flag);
				 bindMap1.put("eventUser", eventInfo.getEventUser());
				 bindMap1.put("eventTime", eventInfo.getEventTime());
				 if(!(expirationDay==null||expirationDay.equals("0")))
				 {
					 expirationDateFlag="X";
				 }
				 else
				 {
					 expirationDay="0";
					 }
				 bindMap1.put("expirationDateFlag", expirationDateFlag);
				 
				 bindMap1.put("expirationDay", expirationDay);
				 bindMap1.put("inspectA", inspectA);
				 bindMap1.put("inspectP", inspectP);
				 bindMap1.put("inspectV", inspectV);
				 bindMap1.put("BONDEDFLAG", bondedFlag);
				 IDMFrameServiceProxy.getSqlTemplate().update(sql_insert, bindMap1);
			}
			if(incertFlag==2)
			{
				
				if(del_flag.equals("2")||del_flag.equals("1"))
				{
				 String sql_update = "update BS_MATERIALSPECCHARGEFLAG SET ERPCHARGEFLAG = :erpChargeFlag,expirationDateFlag=:expirationDateFlag,EXPIRATIONDAY=:expirationDay,INSPECTA=:inspectA,INSPECTP=:inspectP,INSPECTV=:inspectV,BONDEDFLAG=:BONDEDFLAG  WHERE ERPFACTORYNAME = :ERPFactoryName AND  MATERIALSPECNAME = :materialSpecName ";
				 if(erpFactoryName.equals("3010")||erpFactoryName.equals("3019"))//B9
				 {
					 sql_update = "update BS_MATERIALSPECCHARGEFLAG SET ERPCHARGEFLAG = :erpChargeFlag,INSPECTA=:inspectA,INSPECTP=:inspectP,INSPECTV=:inspectV,BONDEDFLAG=:BONDEDFLAG  WHERE ERPFACTORYNAME = :ERPFactoryName AND  MATERIALSPECNAME = :materialSpecName ";
				 }
				 Map<String, Object> bindMap2 = new HashMap<String, Object>();
				 bindMap2.put("ERPFactoryName", erpFactoryName);
				 bindMap2.put("materialSpecName", materialSpecName);
				 bindMap2.put("erpChargeFlag", flag);
				 if(!(expirationDay==null||expirationDay.equals("0")))
				 {
					 expirationDateFlag="X";
					 
				 }
				 else
				 {
					 expirationDay="0";
					 }
				 bindMap2.put("expirationDateFlag", expirationDateFlag);
				 if(!(erpFactoryName.equals("1310")||erpFactoryName.equals("1319")))
				 {
				 bindMap2.put("expirationDay", expirationDay);
				 }
				 else{
					 if(queryResult.get(0).get("EXPIRATIONDAY")==null){
						 bindMap2.put("expirationDay", ""); 
					 }
					 else{
					 bindMap2.put("expirationDay", queryResult.get(0).get("EXPIRATIONDAY").toString()); 
					 }
					 if(queryResult.get(0).get("EXPIRATIONDATEFLAG")==null){
						 bindMap2.put("expirationDateFlag", ""); 
					 }
					 else{
					 bindMap2.put("expirationDateFlag", queryResult.get(0).get("EXPIRATIONDATEFLAG").toString());
					 }
				 }
				 bindMap2.put("inspectA", inspectA);
				 bindMap2.put("inspectP", inspectP);
				 bindMap2.put("inspectV", inspectV);
				 bindMap2.put("BONDEDFLAG", bondedFlag);
				 IDMFrameServiceProxy.getSqlTemplate().update(sql_update, bindMap2);
				}
				
				if(del_flag.equals("3"))
				{
					
					String sql_vauled_novalued="SELECT TYPE FROM BS_ERPLOCATION  WHERE ERPFACTORYNAME=:ERPFACTORYNAME";
					Map<String, Object> ErpLocationValue = new HashMap<String, Object>();
					ErpLocationValue.put("ERPFACTORYNAME", erpFactoryName);
					List<Map<String, Object>> value_or_not=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_vauled_novalued, ErpLocationValue);
					String ValueType= value_or_not.size()>0?value_or_not.get(0).get("TYPE").toString():"";
					if(ValueType.equals("Valued"))
					{
					    String sql_delete="DELETE FROM BS_MATERIALSPECCHARGEFLAG WHERE MATERIALSPECNAME=:MATERIALSPECNAME";
						
						Map<String, Object> bindMap1 = new HashMap<String, Object>();
						bindMap1.put("MATERIALSPECNAME", materialSpecName);
						IDMFrameServiceProxy.getSqlTemplate().update(sql_delete, bindMap1);
					}
					if(ValueType.equals("NoValued"))
					{
						String sql_delete_1="DELETE FROM BS_MATERIALSPECCHARGEFLAG WHERE MATERIALSPECNAME=:MATERIALSPECNAME AND ERPFACTORYNAME=:ERPFACTORYNAME";
						
						Map<String, Object> ErpLocationValue_1 = new HashMap<String, Object>();
						ErpLocationValue_1.put("MATERIALSPECNAME", materialSpecName);
						ErpLocationValue_1.put("ERPFACTORYNAME", erpFactoryName);
						IDMFrameServiceProxy.getSqlTemplate().update(sql_delete_1, ErpLocationValue_1);
					}
				}
				}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			throw new CustomException("CHARGEFLAG", materialSpecName);
		}
		
		flag=flag.equals("X")?"Y":"N";
		return flag;
	}
	public String checkMaterialSpec(String flag,
			String siteName, 
			String materialSpecName,String erpFactoryName) throws CustomException{
		Boolean exitFlag = true;
		
		String sql = "SELECT * FROM MATERIALSPEC "
				+ "WHERE SITENAME = :siteName and MATERIALSPECNAME = :materialSpecName";
		
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("siteName", siteName);
		bindMap.put("materialSpecName", materialSpecName);
		
		List<Map<String, Object>> queryResult = 
				IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		
		if (queryResult == null || queryResult.isEmpty())
			exitFlag = false;
		
		//判断当前数据是否是有价值工厂，materialSpec：PK【SiteName，MaterialSpec】；
		//ERP中PK【ERPFactory，MaterialSpec】。根据ERPFactory获得SiteName是有价值工厂还是无价值工厂，
		//如果当前数据为有价值工厂创建，并且ERP传过来的是无价值工厂的数据，则不修改
		String sql2="SELECT TYPE FROM BS_ERPLOCATION  WHERE ERPFACTORYNAME=:ERPFACTORYNAME";
		Map<String,String> facMap=new HashMap<String, String>();
		facMap.put("ERPFACTORYNAME",exitFlag&&queryResult.get(0).get("ERPFACTORYNAME")!=null?
				queryResult.get(0).get("ERPFACTORYNAME").toString():"");
		
		List<Map<String, Object>> factoryResult=
				IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, facMap);
		String oldValueType= factoryResult.size()>0?factoryResult.get(0).get("TYPE").toString():"NoValued";
		
		Map<String,String> oldfacMap=new HashMap<String, String>();
		oldfacMap.put("ERPFACTORYNAME",erpFactoryName);
		factoryResult=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, oldfacMap);
		String newValueType=factoryResult.size()>0?factoryResult.get(0).get("TYPE").toString():"NoValued";
		//
//		if(oldValueType.equals("Valued")&&newValueType.equals("NoValued"))
//			flag="5";
		
		if (exitFlag && flag.equals("1")&&oldValueType.equals("Valued")){
			//throw new CustomException("INT-0001", materialSpecName);
			flag="5";
		}
		if (exitFlag && flag.equals("1")&&oldValueType.equals("NoValued")&&newValueType.equals("NoValued")){
			//throw new CustomException("INT-0001", materialSpecName);
			flag="5";
		}
		if (exitFlag && flag.equals("1")&&(newValueType.equals("Valued")&&oldValueType.equals("NoValued"))){
			//throw new CustomException("INT-0001", materialSpecName);
			flag="2";
		}
		if (!exitFlag &&  flag.equals("2")){//(flag.equals("2") || flag.equals("3"))){
			flag="1";
		}
		if (exitFlag &&  flag.equals("3")&&oldValueType.equals("Valued")&&newValueType.equals("NoValued")){//(flag.equals("2") || flag.equals("3"))){
			flag="5";
		}
		if (exitFlag && flag.equals("2")&&(newValueType.equals("NoValued")&&oldValueType.equals("Valued"))){
			//throw new CustomException("INT-0001", materialSpecName);
			flag="5";
		}
		if (!exitFlag &&  flag.equals("3")){//(flag.equals("2") || flag.equals("3"))){
			flag="5";
		}
		
		return flag;
	}
	
	public void materialManagement(EventInfo eventInfo,Document message)
	{
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = bodyElement
				.getChild("MATERIALSPECLIST");
				
		for (Iterator<?> iterator = materialPackingListElement
				.getChildren().iterator(); iterator.hasNext();) {
			Element panelE = (Element) iterator.next();
			String materialSpecName = panelE.getChild(
					"MATERIALSPECNAME").getText();
			String expirationDay = panelE.getChild(
					"EXPIRATIONDAY").getText();
			String ERPfactory = panelE.getChild(
					"ERPFACTORYNAME").getText();
			
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("EXPIRATIONDAY",expirationDay);
			bindMap.put("MATERIALSPECNAME",materialSpecName);			
			bindMap.put("ERPFACTORY",ERPfactory);
			String sql1 = "SELECT * FROM BS_MATERIALSPECCHARGEFLAG WHERE MATERIALSPECNAME = :MATERIALSPECNAME AND ERPFACTORYNAME = :ERPFACTORY";
			String sql = "UPDATE BS_MATERIALSPECCHARGEFLAG SET EXPIRATIONDAY = :EXPIRATIONDAY, EXPIRATIONDATEFLAG = 'X' WHERE MATERIALSPECNAME = :MATERIALSPECNAME AND ERPFACTORYNAME = :ERPFACTORY";
			List<Map<String, Object>> queryResult = 
					IDMFrameServiceProxy.getSqlTemplate().queryForList(sql1, bindMap);
			if(queryResult.size()>0){
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
			}
			
		}
				
	}
	public void MaterialJIEZHUAN(EventInfo eventInfo,Document message)
	{
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = bodyElement
				.getChild("MATERIALSPECLIST");
				
		for (Iterator<?> iterator = materialPackingListElement
				.getChildren().iterator(); iterator.hasNext();) {
			Element panelE = (Element) iterator.next();
			String materialSpecName = panelE.getChild(
					"MATERIALSPECNAME").getText();
			String jiezhuandan = panelE.getChild(
					"JIEZHUANDAN").getText();
			String siteName = panelE.getChild(
					"SITENAME").getText();
			String supplieNo = panelE.getChild(
					"SUPPLIERNO").getText();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("JIEZHUANDAN",jiezhuandan);
			bindMap.put("MATERIALSPECNAME",materialSpecName);
			bindMap.put("siteName",siteName);
			bindMap.put("SUPPLIERNO",supplieNo);
			String sql = "UPDATE MATERIALRECEIVEREQUESTDETAIL B SET B.ZSQBH=:JIEZHUANDAN WHERE B.RECEIVEREQUESTNAME IN (SELECT A.RECEIVEREQUESTNAME FROM MATERIALRECEIVEREQUEST A WHERE A.SITENAME=:siteName AND A.SUPPLIERNO=:SUPPLIERNO AND to_char(A.LASTEVENTTIME,'yyyy/mm') >=to_char(TRUNC(add_months(trunc(sysdate),-1),'MM'),'yyyy/mm')  AND A.RECEIVEREQUESTNAME LIKE '33%') AND B.SITENAME=:siteName AND B.MATERIALSPECNAME=:MATERIALSPECNAME";
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
			
		}
	}
	public void StorageRelationManagement(EventInfo eventInfo,Document message)
		{
			Element root = message.getDocument().getRootElement();
			Element bodyElement = root.getChild("Body");
			Element StorageList=bodyElement.getChild("STORAGELIST");		
			for (Iterator<?> iterator = StorageList.getChildren().iterator(); iterator.hasNext();) {
				Element panelE = (Element) iterator.next();
				String StorageName = panelE.getChild("STORAGENAME").getText();
				String ERPLocation = panelE.getChild("ERPLOCATION").getText();
				String siteName = panelE.getChild("SITENAME").getText();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("STORAGENAME", StorageName);
				bindMap.put("ERPLOCATION",ERPLocation);
				bindMap.put("SITENAME",siteName);
				String sql = "UPDATE STORAGE S SET S.ERPLOCATION=:ERPLOCATION WHERE  STORAGENAME=:STORAGENAME AND SITENAME=:SITENAME";
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
				
			}
				
	}
    
	
	public void updatecheckactlocation(EventInfo eventInfo,Document message)
	{
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element CheckList=bodyElement.getChild("CHECKPLANLIST");		
		for (Iterator<?> iterator = CheckList.getChildren().iterator(); iterator.hasNext();) {
			Element panelE = (Element) iterator.next();
			String CheckPlanName=panelE.getChild("CHECKPLANNAME").getText();
			String StorageName = panelE.getChild("ACTLOCATION").getText();
			String MaterialPackingName = panelE.getChild("MATERIALPACKINGNAME").getText();
			String SiteName = panelE.getChild("SITENAME").getText();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("ACTLOCATION", StorageName);
			bindMap.put("MATERIALPACKINGNAME",MaterialPackingName);
			bindMap.put("SITENAME",SiteName);
			bindMap.put("CHECKPLANNAME",CheckPlanName);
			String sql = "UPDATE CHECKRECORD SET ACTLOCATION=:ACTLOCATION WHERE  MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME AND CHECKPLANNAME=:CHECKPLANNAME";
			IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
			
		}
			
      }
	//修改寿命时间和标识
	public void modifyLifeSpec(EventInfo eventInfo, 
			String siteName, 
			String materialSpecName,			
			String expirationDateFlag,
			String expirationDay)
	{
		MaterialSpecKey key = new MaterialSpecKey();
		key.setSiteName(siteName);
		key.setMaterialSpecName(materialSpecName);
		
		SetSpecEventInfo info = new SetSpecEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
				
		bindMap.put("expirationDateFlag", "N");
		bindMap.put("expirationDay", Integer.parseInt(expirationDay));		
	
		info.setUserColumns(bindMap);
		
		eventInfo.setEventName("ModifyMaterialLifeSpec");
		
		MaterialServiceProxy.getMaterialSpecService().setEvent(key, eventInfo, info);
		
		String sql = "UPDATE BS_MATERIALSPECCHARGEFLAG SET EXPIRATIONDATEFLAG = :EXPIRATIONDATEFLAG , EXPIRATIONDAY = :EXPIRATIONDAY WHERE  MATERIALSPECNAME= :MATERIALSPECNAME";
		
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		
		bindMap1.put("EXPIRATIONDATEFLAG", expirationDateFlag);
		bindMap1.put("EXPIRATIONDAY", Integer.parseInt(expirationDay));
		
		bindMap1.put("MATERIALSPECNAME", materialSpecName);
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap1);
		
	}
	
	//B3结转单方法
	public void MaterialTransfer(EventInfo eventInfo,Document message)
	{
		Element root = message.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = bodyElement
				.getChild("MATERIALSPECLIST");
				
		for (Iterator<?> iterator = materialPackingListElement
				.getChildren().iterator(); iterator.hasNext();) {
			Element panelE = (Element) iterator.next();
			String materialSpecName = panelE.getChild(
					"MATERIALSPECNAME").getText();
			String jiezhuandan = panelE.getChild(
					"JIEZHUANDAN").getText();
			String siteName = panelE.getChild(
					"SITENAME").getText();
			
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("JIEZHUANDAN",jiezhuandan);
			bindMap.put("MATERIALSPECNAME",materialSpecName);
			bindMap.put("siteName",siteName);
			String sql = "UPDATE MATERIALSPEC SET JIEZHUANDAN = :JIEZHUANDAN WHERE MATERIALSPECNAME = :MATERIALSPECNAME AND SITENAME = :siteName";
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
			
		}
	}

}
