package com.eactive.eai.rms.ext.mmi;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.eactive.eai.data.entity.onl.bizkey.BizKey;
import com.eactive.eai.data.entity.onl.messagekey.MessageKey;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutItemEntity;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.MessengerPlusSender;
import com.eactive.eai.rms.data.entity.onl.b2bextract.B2bExtractService;
import com.eactive.eai.rms.data.entity.onl.bizkey.BizKeyService;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutService;
import com.eactive.eai.rms.data.entity.onl.messagekey.MessageKeyService;
import com.eactive.eai.rms.data.entity.onl.stdmessage.StandardMessageInfoService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutDao;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformDao;
import com.eactive.eai.rms.onl.manage.serviceinfo.bizkey.FieldExtractInfoUIMapper;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.EaiMsgDao;

@Service("mmiSyncService")
public class MMISyncService extends OnlBaseService {
 
	@Autowired
	@Qualifier("mmiSyncDao")
	private MMISyncDao dao;

    @Autowired
    @Qualifier("transformDao")
    private TransformDao transformDao;    

    @Autowired
    @Qualifier("eaiMsgDao")
    public EaiMsgDao eaiMsgDao;
    
    @Autowired
    @Qualifier("layoutDao")
    public LayoutDao layoutDao;
    
	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;

	@Autowired
	private ComboService comboService;   
	 
	@Autowired
	private BizKeyService bizKeyService;
	
	@Autowired
	private B2bExtractService b2bExtractService;
	
	@Autowired
	private StandardMessageInfoService standardMessageInfoService;
	
	@Autowired
	private LayoutService layoutService;
	
	@Autowired
	private MessageKeyService messageKeyService;
	
	public int mergeLayout(List<HashMap<String,Object>> layoutVos) throws Exception{
		for(HashMap<String,Object> vo : layoutVos){
			String layout = (String)vo.get("loutName");
			//서버구분코드 체크
			Optional<LayoutEntity> optionalLayoutEntity = layoutService.findById(layout);
			if (layoutService.existsById(layout)){
				String dbEaiSevrDstcd = optionalLayoutEntity.get().getEaisevrdstcd();
				String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
				if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
					throw new Exception("레이아웃("+layout+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 MMI 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
				}
			}else{
				String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
				if ("9".equals(mmiEaiSevrDstcd)){
					throw new Exception("신규 레이아웃 등록시 서버구분코드가 9 인 경우." + layout);
				}
			}
			
			//vo 의 한글 체크
			boolean isDeployHangle= false;			
			//db 의 한글체크
			boolean isDbHangle = false;

			if (optionalLayoutEntity.isPresent() && !optionalLayoutEntity.get().getLayoutItemEntities().isEmpty()){
				
				//배포 레이아웃 체크
				List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
				for(HashMap<String,Object> item : list) {
					String name = (String)item.get("loutItemName");
					if (name.getBytes().length != name.length() ){
						isDeployHangle= true;
						break;
					}
				}
				//DB 레이아웃 체크
				for(LayoutItemEntity item : optionalLayoutEntity.get().getLayoutItemEntities()){
					String name = item.getId().getLoutitemname();
					if (name.getBytes().length != name.length() ){
						isDbHangle= true;
						break;
					}
				}
				if (isDeployHangle != isDbHangle){
					//EAI 서비스코드가 1개만 존재할때 레이아웃이 다르더라도 패스 2020-10-29 오현석대리요청
					//변환까지만 연결된거 무시한다.
					List<String> interfaceLists = dao.selectInterfaceForSameLayout(vo);
					if (interfaceLists != null && interfaceLists.size() > 1){
						if (isDeployHangle){
							throw new Exception("배포 된 레이아웃("+layout+") 은 한글로 되어 있습니다. DB에 저장되어 있는 값은 영문 입니다.배포한 레이아웃이 한글이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
						}else{
							throw new Exception("배포 된 레이아웃("+layout+") 은 영문으로 되어 있습니다. DB에 저장되어 있는 값은 한글 입니다.배포한 레이아웃이 영문이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
						}
					}
				}
			}
			
			List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
			layoutDao.deleteItemAll(vo);
			layoutDao.delete(vo);
			layoutDao.insert(vo);
	    	for(HashMap<String,Object> item : list) {
    			layoutDao.insertItem(item);
	    	}
		}
		return layoutVos.size();
	}
	public int mergeTransform(List<HashMap<String,Object>> transformVos) throws Exception{
		for(HashMap<String,Object> vo : transformVos){
			//서버구분코드 체크
			HashMap detail =transformDao.selectDetail(vo);
			if (detail != null){
				String dbEaiSevrDstcd = (String)detail.get("EAISEVRDSTCD");
				String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
				String cnvsnName = (String)vo.get("cnvsnName");
				if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
					throw new Exception("변환("+cnvsnName+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 MMI 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
				}
			}else{
				String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
				if ("9".equals(mmiEaiSevrDstcd)){
					throw new Exception("신규 변환 등록시 서버구분코드가 9 인 경우." + (String)vo.get("cnvsnName"));
				}
			}
			
			transformDao.deleteTransformItem(vo);
			transformDao.deleteTransformSourceResult(vo);
			transformDao.deleteTransform(vo);
			
			transformDao.insert(vo);
			List<HashMap<String,Object>> layouts = (List<HashMap<String,Object>>)vo.get("layouts");
			for(HashMap<String,Object>layout : layouts){
				transformDao.insertTransformSourceResult(layout);
			}
			List<HashMap<String,Object>> mappings = (List<HashMap<String,Object>>)vo.get("mappings");
			for(HashMap<String,Object> mapping : mappings){
				try{
					transformDao.insertTransformItem(mapping);
				}catch(DuplicateKeyException e){
					throw new Exception("변환 항목 중복 오류 " + mapping);
				}
			}
		}
		return transformVos.size();
	}
	public String mergeInterface(HashMap<String,Object> interfaceVo) throws Exception {
        HashMap he01 = (HashMap)interfaceVo.get("he01");
        String eaiSvcName = (String)he01.get("eaiSvcName");
        
        logger.info ("-1. 내부 표준 전문 INSERT ----------------------------------------------------");
        // 1. 내부 표준 전문 INSERT
        //    비표준에서 표준으로 가는 경우 표준으로 전환하기 위한 정보 이므로 내부로 갈 때만 처리

        //eai 서비스 기준으로 목록 조회
        List<Map<String, Object>> listHs04 = dao.selectHS04(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
        String[] filters = new String[]{"COMMON_bnkCd","COMMON_chnlDstcd","COMMON_cmpxTranDmndDstcd","COMMON_cnclDstcd","COMMON_groupCoCd","COMMON_mdiaDstcd","COMMON_screnNo","COMMON_sysOperEvirnDstcd"};
        Map<String,String> beforeData = dao.selectHS05(new HashMap(){{put("eaiSvcName",eaiSvcName);put("filters",filters);}});
        
        for(Map map : listHs04){
        	dao.deleteHS04((HashMap)map);
        	dao.deleteHS05((HashMap)map);
        }
        @SuppressWarnings("unchecked")
		ArrayList<HashMap<String, Object>> hs04s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("hs04");
        if (hs04s != null){
        	//내부표준전문 업무 서비스키 중복 체크
        	for(HashMap<String,Object> map : hs04s){
        		String bzwkSvcKeyName = (String)map.get("bzwkSvcKeyName");
        		List<String> eaiList = dao.selectHS04ForBzwkSvcKeyName(new HashMap(){{put("bzwkSvcKeyName",bzwkSvcKeyName);}});
        		if (eaiList != null && eaiList.size() > 0){
        			String dupEaiSvcName = "";
        			for(String data : eaiList){
        				dupEaiSvcName = "," + data;
        			}
        			throw new Exception("내부표준전문의 업무서비스키 중복 오류입니다.다른 EAI서비스코드("+dupEaiSvcName+") 에서 서비스키("+bzwkSvcKeyName+") 를 사용하고 있습니다.");
        		}
        	}
        	
        	for(HashMap<String,Object> map : hs04s){
        		ArrayList<HashMap<String,Object>> hs05s = (ArrayList<HashMap<String,Object>>)map.get("hs05");
        		dao.insertHS04(map);
        		for(HashMap<String,Object> submap : hs05s){
        			String key = submap.get("bzwkSvcKeyName") + "," + submap.get("columnName");
        			String data = beforeData.get(key);
        			if (data != null){
        				submap.put("columnValue", data);
        			}
        			dao.insertHS05(submap);
        		}
        	}
        }

        logger.info ("-2. EAI메세지 INSERT -------------------------------------------------------");
        // 2. EAI메세지 INSERT
        dao.mergeHE01((HashMap<String,Object>)interfaceVo.get("he01"));
        eaiSvcNameVali(interfaceVo);
        ArrayList<HashMap<String,Object>> he02s =  (ArrayList<HashMap<String,Object>>)interfaceVo.get("he02");
        for(HashMap<String,Object> map : he02s){
        	dao.mergeHE02(map);
        }
        //순서변경 위에서 무조건삭제 하는 방식에서 merge후 he02s가 1건일 경우 2번째 시퀀스 삭제
        if(he02s != null && he02s.size() == 1){
        	//EAI메시지 SERVICE 2번 은 삭제
        	dao.deleteHe02SvcPrcssNo(new HashMap(){{put("eaiSvcName",eaiSvcName);put("svcPrcssNo",2);}});
        }

        // logger.info("-3. 참조메시지ID INSERT ----------------------------------------------------");
        // 3. 참조메시지ID INSERT
        ArrayList<HashMap<String, Object>> ms02s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("ms02");
        if (ms02s != null && ms02s.size() > 0 ){
        	//TransformVo vo = new TransformVo();
        	//vo.setEaiSvcName(eaiSvcName);
        	eaiMsgDao.deleteRefForEaiSvcName(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
        	for(HashMap<String,Object> map : ms02s){
        		eaiMsgDao.insertRef(map);
        	}
        }
        
		return null;
	}
	public boolean mergeMessageKey(HashMap<String,Object> interfaceVo, String userId) throws Exception {
        //메시지Key 
		List<String[]> fr04s = (List<String[]>)interfaceVo.get("fr04");
        
        HashMap he01 = (HashMap)interfaceVo.get("he01");
        String eaiSvcName = (String)he01.get("eaiSvcName");
        String adptrBzwkGroupName = (String)he01.get("gstatSysAdptrBzwkGroupName");
        boolean isMessageKeySame = true;
        if (fr04s != null && fr04s.size()>0){
        	//select 
        	List<MessageKey> dbdata = messageKeyService.findByAdptrBzwkGroupNameAndIoDstcd(adptrBzwkGroupName, "I");
        	
        	isMessageKeySame = messageCheck(fr04s, dbdata);
           	//쪽지알림
        	StringBuffer sb = new StringBuffer();
        	if (!isMessageKeySame){
        		sb.append("어댑터업무그룹명 : " + adptrBzwkGroupName ).append("<br>");
        		sb.append("EAI서비스코드   : " + eaiSvcName ).append("<br>");
                if (dbdata != null && dbdata.size() > 0 ){
                	sb.append("현재 설정 정보" ).append("<br>");
                	sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
                	sb.append("<tr>");
                	sb.append("<td>메시지 구분코드</td>");
                	sb.append("<td>입출력 구분코드</td>");
                	sb.append("<td>그룹 순차번호</td>");
                	sb.append("<td>필드 처리번호</td>");
                	sb.append("<td>메시지 필드 시작위치값</td>");
                	sb.append("<td>메시지 필드 길이</td>");
                	sb.append("</tr>");
                	for(MessageKey messageKey : dbdata){
                    	sb.append("<tr>");
						sb.append("<td>" + messageKey.getId().getMsgdstcd() + "</td>");
						sb.append("<td>" + messageKey.getId().getIodstcd() + "</td>");
						sb.append("<td>" + messageKey.getId().getGroupinorno() + "</td>");
						sb.append("<td>" + messageKey.getId().getFldprcssno() + "</td>");
						sb.append("<td>" + messageKey.getMsgfldstartsituval() + "</td>");
						sb.append("<td>" + messageKey.getMsgfldlen() + "</td>");
                    	sb.append("</tr>");

                	}
                	sb.append("</table>");
                }
                sb.append("요청 설정자 (" + userId + ")").append("<br>");
                sb.append("요청 설정 정보 " ).append("<br>");
            	sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
            	sb.append("<tr>");
            	//sb.append("<td>메시지 구분코드</td>");
            	//sb.append("<td>입출력 구분코드</td>");
            	//sb.append("<td>그룹 순차번호</td>");
            	sb.append("<td>필드 처리번호</td>");
            	sb.append("<td>메시지 필드 시작위치값</td>");
            	sb.append("<td>메시지 필드 길이</td>");
            	sb.append("</tr>");             
            	
                for(int i=0;i< fr04s.size();i++){
                	String[] fr04 = fr04s.get(i);
                	if (fr04.length == 2){
                		sb.append("<tr>");
                		//sb.append("<td>"+m.get("msgDstcd")+"</td>");
                		//sb.append("<td>"+m.get("ioDstcd")+"</td>");
                		//sb.append("<td>"+m.get("groupInorNo")+"</td>");
                		sb.append("<td>"+(i+1)+"</td>");
                		sb.append("<td>"+fr04[0]+"</td>");
                		sb.append("<td>"+fr04[1]+"</td>");
                		sb.append("</tr>");
                	}

                }
                MessengerPlusSender sender = MessengerPlusSender.getInstance();
        		String url         = monitoringContext.getStringProperty("rms.messenger.url");
        		String srvCode     = monitoringContext.getStringProperty("rms.messenger.srvCode");
        		String recipient   = monitoringContext.getStringProperty("rms.messenger.recipient");
        		String send        = monitoringContext.getStringProperty("rms.messenger.send");
        		String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias");
        		logger.debug("send MessengerPlus data : " + sb.toString());
                sender.execute(url, srvCode, recipient, send, "EAI 어댑터 구분필드 추출정보 변경요청", sb.toString(), "", senderAlias);
        	}
        }
        return isMessageKeySame;
	}
	private boolean messageCheck(List<String[]> fr04s, List<MessageKey> selectData) throws Exception{
       
        List<String[]> dbGroup = new ArrayList<>();
        HashMap<String,List<String[]>> dbGroups = new HashMap<>();
        
		for (MessageKey messageKey : selectData) {
			String groupNumber = Integer.toString(messageKey.getId().getGroupinorno());
			if (dbGroups.containsKey(groupNumber)) {
				dbGroup = dbGroups.get(groupNumber);
			} else {
				dbGroup = new ArrayList<String[]>();
				dbGroups.put(groupNumber, dbGroup);
			}
			dbGroup
					.add(new String[] { Integer.toString(messageKey.getMsgfldstartsituval()),
							Integer.toString(messageKey.getMsgfldlen()) });
		}
    	
    	//false 일 경우 message전송
        //check
        //신규등록
        if (dbGroups.size() == 0 && fr04s.size() >0){
        	return false;
        }
        
        for (String key : dbGroups.keySet()){
        	dbGroup = dbGroups.get(key);
        	if (dbGroup.size() == fr04s.size()){
        		int trueCount = 0;
        		for(int i=0;i< dbGroup.size() ;i++ ){
        			if (Arrays.equals(dbGroup.get(i), fr04s.get(i))){
        				trueCount++;
        			}
        		}
        		if (dbGroup.size()==trueCount){
        			return true;
        		}
        	}
        }
        return false;
		
	}
	
	@Autowired
	private FieldExtractInfoUIMapper fieldExtractInfoUIMapper;
	
	public String mergeTraceKey(HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> tracekeys) throws Exception {
		logger.info(" 추적관리필드 INSERT -----------------------------------------------------");
		// 4. 추적관리필드 INSERT
        HashMap he01 = (HashMap)interfaceVo.get("he01");
        final String eaiSvcName = (String)he01.get("eaiSvcName");
		
		bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
		if (tracekeys== null || tracekeys.size()==0){
			return null;
		}		
		for (HashMap<String, Object> tracekey : tracekeys) {
			BizKey bizKey = fieldExtractInfoUIMapper.map(tracekey);
			bizKeyService.save(bizKey);
		}
		return null;
	}
	public boolean transactionMMISync( HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> layoutVos, List<HashMap<String,Object>> transformVos, List<HashMap<String,Object>> tracekeys, String userId) throws Exception  {
        logger.info("-------------------<< transactionMMISync >>----------------------------");
        logger.debug("{}",interfaceVo);

        logger.info("-------------------<< session 값체크>>----------------------------");
        boolean isOnline = false;
        for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
        	if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
        		isOnline = true;
        		break;
        	}
        }

        if (!isOnline){
        	throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
        }
        mergeLayout(layoutVos);
        mergeTransform(transformVos);
        mergeInterface(interfaceVo);
        mergeTraceKey(interfaceVo, tracekeys);

		return mergeMessageKey(interfaceVo, userId);
	}
	public Map<String,Map<String, String>> selectAdapterForNickName(String src, String tgt, String resSrc) throws Exception {
		Map<String, Map<String, String>> result = new HashMap<String,Map<String,String>>();
		 
		if (!StringUtils.isEmpty(src)){
			Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",src);}});
			if (nickname == null || nickname.size()==0){
				throw new Exception("어댑터 닉네임 ("+src+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
			}
			result.put("SRC", nickname);
		}
		if (!StringUtils.isEmpty(tgt) && !"DUMMY000".equals(tgt)){
			Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",tgt);}});
			if (nickname == null || nickname.size()==0){
				throw new Exception("어댑터 닉네임 ("+tgt+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
			}
			result.put("TGT", nickname);
		}
		if (!StringUtils.isEmpty(resSrc)){
			Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",resSrc);}});
			if (nickname == null || nickname.size()==0){
				throw new Exception("어댑터 닉네임 ("+resSrc+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
			}
			result.put("RES_SRC", nickname);
		}
		return result;
	}
	
	public void deleteInterface( HashMap<String,Object> inter ) throws Exception  {
    	//interface 삭제할 경우 
    	//    - interface삭제 (he01,he02,fr01,ms02)
    	//    - altkey,tracekey 삭제 (fr03) interface 기준으로 삭제
    	//    - 내부표준전문 삭제 (hs04,hs05) interface 기준으로 삭제
    	//    - 변환삭제 (tr01,tr02,tr03) interface 기준으로 삭제
    	
		
		logger.info("-------------------<<deleteMMISync >>----------------------------");
        logger.debug("{}",inter);

        logger.info("-------------------<< session 값체크>>----------------------------");
        boolean isOnline = false;
        for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
        	if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
        		isOnline = true;
        		break;
        	}
        }
        if (!isOnline){
        	throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
        }

        String eaiSvcName = (String)inter.get("eaiSvcName");
        HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("eaiSvcName",eaiSvcName);}};
        eaiMsgDao.delete(paramMap);
        eaiMsgDao.deleteSvc(paramMap);
        eaiMsgDao.deleteRefForEaiSvcName(paramMap);
        eaiMsgDao.deleteCondRuleForEaiSvcName(paramMap);
        
        //alterkey, tracekey 삭제
        bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
        //내부표준전문삭제
        List<String> bzwkSvcKeyNames = (List<String>)inter.get("bzwkSvcKeyName");
        if (bzwkSvcKeyNames != null){
        	for(String bzwkSvcKeyName : bzwkSvcKeyNames){
        		standardMessageInfoService.deleteById(bzwkSvcKeyName);
        	}
        	
        }
        
        //변환삭제
        List<String> transforms = (List<String>)inter.get("transform");
        if (transforms != null){
        	for(String transform : transforms){
        		HashMap<String,Object> map = new HashMap<String,Object>(){{put("cnvsnName",transform);}};
        		//1.delete transform  //TR01 삭제
        		transformDao.deleteTransform(map);
        		//2.delete transform  //TR02 삭제
        		transformDao.deleteTransformSourceResult(map);
        		//3.delete transform  //TR03 삭제
        		transformDao.deleteTransformItem(map);
        	}
        	
        }

	}
	public void deleteLayout(HashMap<String,Object> layouts) throws Exception  {
	
		logger.info("-------------------<<deleteLayout >>----------------------------");
		logger.debug("{}",layouts);
		
		logger.info("-------------------<< session 값체크>>----------------------------");
		boolean isOnline = false;
		for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
			if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
				isOnline = true;
				break;
			}
		}
		
		if (!isOnline){
			throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
		}
		String loutName = (String)layouts.get("loutName");
		HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("loutName",loutName);}};
		layoutDao.delete(paramMap);
		layoutDao.deleteItemAll(paramMap);

	}
	public  List<String> selectTransformListForEaiSvcName(HashMap<String,Object> map){
		return dao.selectTransformListForEaiSvcName(map);
	}
	public  List<String> selectBzwkSvcKeyNameForEaiSvcName(HashMap<String,Object> map){
		return dao.selectBzwkSvcKeyNameForEaiSvcName(map);
	}
//	public static void main(String[] args) throws Exception{  //취약점 수정
//		
//	}
	public  boolean selecAppIsYn(HashMap<String,Object> map){
		int count = dao.selecAppIsYn(map);
		if (count==0) {
			return false;
		}else{
			return true;
			
		}
	}
	
	public void eaiSvcNameVali (HashMap<String,Object> interfaceVo) throws Exception {
		/*
		 20200902 
		Flow Control -> B2B일 때
		모니터링 코드(MMI_B2B_BZWKDSTCD)에 정의되어 있는 업무구분코드에 서비스코드 앞3자리가 있을 때
		라우팅 추출 정보가 없을때 
		메신저 발송
		*/
        HashMap he01 = (HashMap)interfaceVo.get("he01");
        String eaiSvcName = (String)he01.get("eaiSvcName");
        String flowCtrl = (String)he01.get("flowCtrlRoutName"); //플로우컨트롤명
        String bzwkDstcd = eaiSvcName.substring(0, 3);//서비스코드 앞 3자리
        String eaiSevrTxt = "";
        
        boolean isB2b = false;		//플로우컨트롤이 b2b인지
        boolean isCode = false;		//모니터링 코드에 정의되어 있는지
        boolean isRoutCnt = false;	//라우팅추출정보가 없을 때 
        String eaiSevrDstcd = (String)he01.get("eaiSevrDstcd");	//서버구분코드
        List<ComboVo> sevrCdList = comboService.getFromCode("INOUT_TYPE");//EAI서버구분코드
		if (!sevrCdList.isEmpty()) {
			for (ComboVo m : sevrCdList) {
				if (eaiSevrDstcd.equals(m.getCode())) {
					eaiSevrTxt = m.getCodename();
					break;
				}
			}
		}
        if (flowCtrl.indexOf("B2B")>-1){	//flowControl => B2B일때
        	isB2b = true;
        }
        //Monitoring Code에 서비스코드 앞 3자리가 정의되어 있는지
        List<ComboVo> bzwkDstcdList =  comboService.getMonitoringCodeSortedByIdCode("MMI_B2B_BZWKDSTCD");
        for(ComboVo m : bzwkDstcdList){
        	if(bzwkDstcd.equals(m.getCodename())){
        		isCode = true;
        		break;
        	}
        }
        //라우팅추출정보가 없을때 
        long routCnt = b2bExtractService.count(eaiSvcName);
        if(routCnt == 0){
        	isRoutCnt = true;
        }
        if (isB2b && isCode && isRoutCnt){
        	if(!"1".equals(eaiSevrDstcd) && eaiSvcName.endsWith("1")){	//내부가 아니고 서비스코드가 S01 or R01 1로 끝날때 pass
        		return;
        	}
        	
           	//쪽지알림
        	//라우팅 필드추출 정보 관리에 XXXXXXXX 서비스코드가 미등록 상태입니다.
        	//EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다.
        	
        	StringBuffer sb = new StringBuffer();
    		sb.append("EAI서비스코드 : " + eaiSvcName ).append("<br>");
    		sb.append("EAI서버구분 : ["+eaiSevrDstcd+"] " + eaiSevrTxt ).append("<br>");
        	sb.append("라우팅 추출 정보 관리에 서비스코드("+eaiSvcName+")가 미등록 상태입니다." ).append("<br>");
        	sb.append("EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다." ).append("<br>");
            
            MessengerPlusSender sender = MessengerPlusSender.getInstance();
    		String url         = monitoringContext.getStringProperty("rms.messenger.url","http://172.17.179.45/HMemoService");
    		String srvCode     = monitoringContext.getStringProperty("rms.messenger.srvCode","EAI002");
    		String recipient   = monitoringContext.getStringProperty("rms.messenger.recipient","1622512;1562325;2852883;3331839;S010795;");
    		String send        = monitoringContext.getStringProperty("rms.messenger.send","1562325");
    		String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias","EAI시스템");
    		logger.debug("send MessengerPlus data : " + sb.toString());
            sender.execute(url, srvCode, recipient, send, "라우팅 필드추출정보 등록요청", sb.toString(), "", senderAlias);
        }   
	}
}