package com.eactive.eai.rms.onl.manage.rule.transformrule;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.helpers.LogLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.UUID;
import com.eactive.eai.data.entity.onl.message.EAIMessageEntity;
import com.eactive.eai.data.entity.onl.message.ServiceMessageEntity;
import com.eactive.eai.data.entity.onl.message.ServiceMessageEntityId;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.excel.ExcelSheet;
import com.eactive.eai.rms.common.excel.ExcelUtil;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.util.ContainerUtil;
import com.eactive.eai.rms.data.entity.onl.eaimsg.EAIMessageService;
import com.eactive.eai.rms.data.entity.onl.eaimsg.ServiceMessageService;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutManService;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformVo;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformItem;
import com.eactive.eai.transformer.transform.TransformValidator;
//import SCSL.SLDsFile;

@Controller
public class TransformRuleController extends BaseController {
    private static final int DATA_ROW_OFFSET = 13;
    private static final int COL_TRAN_INFO = 2;
    private static final int ROW_TRAN_NAME = 8;
    private static final int ROW_TRAN_DESC = 9;
    private static final int ROW_TRAN_TRG_LOUT = 10;
    private static final int ROW_TRAN_SRC_LOUT = 11;
    private static final int COL_INST = 2;
    private static final int COL_RES_PATH = 3;
    private static final int COL_SEQ = 4;
    private static final int COL_DEF_VALU = 5;
    private static final String TARGET_LAYOUT = "TGT_LAYOUT";
    private static final String SOURCE_LAYOUT = "SRC_LAYOUT";

    private static final Logger logger = Logger.getLogger(TransformRuleController.class);
    
    @Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;	
    
	@Autowired
	@Qualifier("transformRuleService")
	private TransformRuleService service;
	
	@Autowired
	private ServiceMessageService serviceMessageService;
	
	@Autowired
	private EAIMessageService eaiMessageEntityService;
	
    @Autowired
    private LayoutManService layoutManService;
    
	@RequestMapping(value= "/onl/admin/rule/transformRuleMan.view")
	private String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}    
    @RequestMapping(value= "/onl/admin/rule/transformRuleMan.json",params = "cmd=LIST_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response,String eaiSvcName) throws Exception {
		Map resultMap = new HashMap();
		resultMap.put("eaiSvcNameRows" , "");
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;            
    }  
      
	public int DecFile(String prop,String keyFilePath,String srcFile,String dstFile) throws Exception{
//
//		SLDsFile sFile = new SLDsFile();
//
//		sFile.SettingPathForProperty(prop); 
//		
//		int retVal = sFile.CreateDecryptFileDAC (
//		keyFilePath,
//		"SECURITYDOMAIN",
//		srcFile,
//		dstFile);
//		logger.info( " CreateDecryptFileDAC [" + retVal + "]");
		int retVal =0;
		return retVal;
	}
    
    
    @RequestMapping(value= "/onl/admin/rule/transformRuleMan2.file",params = "cmd=UPLOAD",method=RequestMethod.POST)
    public ModelAndView handleFileUpload2(HttpServletRequest request,@RequestParam("file") List<MultipartFile> files)throws Exception{
    	// List<MultipartFile> files 
    	String srcFilePath =null;  
    	String dstFilePath =null;
    	String PropPath  =null;
    	String keyFilePath =null;
      
		String orgFileNm = null;
		String fileExtension = null;
		String srcFile,dstFile = null;
		String name = "";
		String status = "성공";
		String message = "";
	    String msgAddon = "" ;
	    
	    List<HashMap<String,Object>> result = new ArrayList<HashMap<String,Object>>();
    	List<HashMap<String,Object>> list = null;
    	HashMap resultMap = new HashMap();
    	
		List<String> fileNames = new ArrayList<String>();
		
		logger.info("files : "+files.size());
		
		///////////////////////////
		srcFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_SFPATH);
    	dstFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_DFPATH); 
    	PropPath  = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_PROP);
    	keyFilePath = monitoringContext.getStringProperty(MonitoringContext.SOFTCAMP_KEY);
    	
		///////////////////////////
    	if(srcFilePath == null || dstFilePath== null || PropPath == null || keyFilePath == null){
    		message = "문서암호화 해제 property를 확인해주세요."; 
	    	
			resultMap.put("message"  , message);
			resultMap.put("rows"     , result);
			ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
			return modelAndView;
		}
    	
    	//LOG 파일 위치 프라퍼티로 
        String defaultLogPath = monitoringContext.getStringProperty(
                MonitoringContext.DEFAULT_LOG_PATH, "/fslog/eai/");
    	
        srcFilePath = defaultLogPath + ContainerUtil.getInstanceName()+srcFilePath;
        dstFilePath = defaultLogPath + ContainerUtil.getInstanceName()+dstFilePath;
        
        logger.info("srcFilePath : "+srcFilePath);
    	logger.info("dstFilePath : "+dstFilePath);
    	
    	File sdir = new File(srcFilePath);
    	if (sdir != null && !sdir.exists()) {
            boolean success = sdir.mkdirs();
            if (!success) {
                LogLog.error("Failed to create srcFilePath directory structure: " + 
                             sdir);
                message = "문서암호화 해제 property를 확인해주세요.";
                resultMap.put("message"  , message);
    			resultMap.put("rows"     , result);
    			ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
    			return modelAndView;
            }
        }
    	
    	File tdir = new File(dstFilePath);
    	if (tdir != null && !tdir.exists()) {
            boolean success = tdir.mkdirs();
            if (!success) {
                LogLog.error("Failed to create dstFilePath directory structure: " + 
                		tdir);
                message = "문서암호화 해제 property를 확인해주세요.";
                resultMap.put("message"  , message);
    			resultMap.put("rows"     , result);
    			ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
    			return modelAndView;
            }
        }
    	
		int idx = 0;
		
		if(files.size()>0 && files != null){
			//int cnt = 0;
			for(MultipartFile file : files){
				//test코드
				/*if(cnt ==0){
					dstFile = "C:\\test\\5d3bfa5d-8573-4184-b086-9be1dd1462a7_Dec.xls"; //overwrite on
				}else{
					dstFile = "C:\\test\\02162f58-ee8d-4e2f-b561-658736b19616_Dec.xls";
				}
		 		cnt ++;*/
				
				orgFileNm = file.getOriginalFilename();
				idx = orgFileNm.lastIndexOf(".");
				//파일 확장자
				fileExtension = "."+orgFileNm.substring(idx+1);
				
				UUID uuid = UUID.randomUUID();
		 		name = uuid.toString();
				BufferedOutputStream stream = null;
	            try {
	            	
	                byte[] bytes = file.getBytes();
	                stream =new BufferedOutputStream(new FileOutputStream(new File(srcFilePath +name+fileExtension)));
	                stream.write(bytes);
	                message = "You successfully uploaded " + name + "!";
	            } catch (Exception e) {
	                message = "You failed to upload " + name + " => " + e.getMessage();
	            } finally{
	            	if (stream != null)try {stream.close();} catch (IOException e) {}
	            }
		        srcFile= srcFilePath +name+fileExtension;
		 		dstFile= dstFilePath +name+"_Dec"+fileExtension;
		  		
		 		logger.info("srcFile : "+srcFile);
		 		logger.info("dstFile : "+dstFile);
			
	 			//문서복호화   0:성공   -36:원본파일이 비암호화문서 성공과 동일적용
	 			int decRtn = DecFile(PropPath,keyFilePath,srcFile,dstFile);
			
				if(!(decRtn == 0 || decRtn == -36) ){
					if(decRtn == 1000){
						message = "["+decRtn+"]"+"원본파일이 없습니다";
					}else if(decRtn == 3000){
						message = "["+decRtn+"]"+"키 파일이 없습니다";
					}else{
						message = "["+decRtn+"]"+"복호화 실패하였습니다.";
					}
					
					//error message
					resultMap.put("message"  , message);
					resultMap.put("rows"     , result);
					ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
					return modelAndView;
				}
				
		 		fileNames.add(dstFile);
			}
			
		} else {
            message = "You failed to upload " + name + " because the file was empty.";
            //retrun
            resultMap.put("message"  , message);
    		resultMap.put("rows"     , result);
    		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
    		return modelAndView;
            
        }
		
		String [] sheetNames = {"변환 정의서"};
		int maxcolumn = 6;
		   //3. sheet to memory
	    List<Map<String,Object>> mSheet = new ArrayList<Map<String,Object>>();
	    
	    if(fileNames != null){
			for(int k =0;k<fileNames.size();k++){
				 try{
					
					ExcelSheet[] sheets = null; //취약점소스 수정 2020.08.27
					if(fileNames.get(k) != null){
						sheets = (ExcelSheet[])ExcelUtil.loadExcelFile(fileNames.get(k));
					}
			    	
			    	if(sheets != null){
			    		for (int i=0;i<sheets.length;i++){
				        	String[][] data = null;
				        	for(int j=0;j<sheetNames.length;j++){
				        		if (sheetNames[j].equals(sheets[i].getName())){
				        			int index = 0;
									while (sheets[i].existsRow(index)) {
										index++;
									}
									data = new String[index][maxcolumn];
									for(int row=0;row<index;row++){
										for(int col=0;col<maxcolumn;col++){
											data[row][col]=sheets[i].getCellString(row, col);
										}
									}
									 
									Map<String,Object> h = new HashMap<String,Object>();
									h.put("sheetName", sheets[i].getName());
									h.put("data", data);
									mSheet.add(h);
				        		}else{
				        			//sheet 명명규칙 오류
				        		}
				        	}
				        }
			    	}
			        
			    }catch(Exception e){
			    	throw new Exception("형식에 맞지않는 자료 입니다."+e.getMessage());
			    }
			    
			    if(mSheet.size()==0){
			    	throw new Exception("유효한 시트명이 존재 하지 않습니다.") ;
			    	
			    }
			}
	    }
		
		logger.info("mSheet : "+mSheet.size());
		String tranName = "";
	    String eaiSvcCode = "" ;
		
    	String msg = "";
    	try {
	        for (int i=0;i<mSheet.size();i++){
	        	String[][] arrData = (String[][])mSheet.get(i).get("data");
	        	String sheetName = (String)mSheet.get(i).get("sheetName");
	        	boolean isAccessable = false ;
	        	
	        	try{
	        		msg = "";
	        		status = "성공";
					 ///////////////////////
		            // type & version
	        		//String type = arrData[2][2];
			        //String version = arrData[3][2];
			        eaiSvcCode = arrData[4][2];
			        String ow      = arrData[6][4];
	
		            if( eaiSvcCode == null ) eaiSvcCode = "" ;            
		            if( ow == null ) ow = "" ;
		            boolean overwrite = false ;
		            if( ow.equals("O") || ow.equals("o") ) {
		                overwrite = true ;
		            }            
		            logger.info("overwrite : "+overwrite);
		            SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		            
		            String  roleId   = SessionManager.getRoleIdString(request);
		            boolean isAdmin = false;
		            EAIMessageEntity eaiMessageEntity = null;
	            	String bizCode = "";
	            	String eaiMsg_SevrDstCd = "";
	            	
		            //admin 권한 체크    
		            if(roleId.indexOf("admin") > -1){ //admin 일경우 
		            	isAdmin =  true;
		            }
		            
		            if(!isAdmin){
		            	if(eaiSvcCode.equals("")){
			            	status = "실패";
		                	msg = "EAI서비스코드는 필수항목입니다" ;
		                    logger.error(msg);
			            	throw new Exception("EAI서비스코드는 필수항목입니다");
		            	}
		            }
		            
		            //EAI 서비스코드, 변환명  SRC TAR 레이아웃명 필수 체크
		          if(arrData[ROW_TRAN_NAME][COL_TRAN_INFO].equals("")){
		            	status = "실패";
	                	msg = "레이아웃 변환명은 필수항목입니다" ;
	                    logger.error(msg);
		            	throw new Exception("레이아웃 변환명은 필수항목입니다");
		            }else if(arrData[ROW_TRAN_TRG_LOUT][COL_TRAN_INFO].equals("")){
		            	status = "실패";
	                	msg = "타겟 레이아웃명은 필수항목입니다" ;
	                    logger.error(msg);
		            	throw new Exception("타겟 레이아웃명은 필수항목입니다");
		            }else if(arrData[ROW_TRAN_SRC_LOUT][COL_TRAN_INFO].equals("")){
		            	status = "실패";
	                	msg = "원천 레이아웃명은 필수항목입니다" ;
	                    logger.error(msg);
		            	throw new Exception("원천 레이아웃명은 필수항목입니다");
		            }
		            
		            //EAI서비스코드로 서버구분코드 조회 
		            if(!"".equals(eaiSvcCode)){
		            	eaiMessageEntity = eaiMessageEntityService.getById(eaiSvcCode);
		            	bizCode = eaiMessageEntity.getEaibzwkdstcd();
		            	eaiMsg_SevrDstCd = eaiMessageEntity.getEaisevrdstcd();
		            }else{
		            	eaiMsg_SevrDstCd = "9"; //admin이 서비스코드 없는 변환 등록시
		            	isAccessable = true;     //서비스코드가 없어 업무구분코드 권한체크 할 수 없음 true 로 강제 지정
		            }
		            
		            logger.info("eaiSvcCode : " + eaiSvcCode +" eaiMsg_SevrDstCd : " + eaiMsg_SevrDstCd);
	                
		            /////////////////////
		            // parse
		            
		            Transform t = new Transform();
		            t.setName(arrData[ROW_TRAN_NAME][COL_TRAN_INFO]);
		            t.setDescription(arrData[ROW_TRAN_DESC][COL_TRAN_INFO]);
		            t.setLastUpdateDate(DATE_FORMAT.format(new Date()).substring(0, 16));
	
		            tranName = t.getName();
		            
		            ///////////////////
		            // target layout
		            String targetLayoutName = arrData[ROW_TRAN_TRG_LOUT][COL_TRAN_INFO];
		            logger.info("targetLayoutName : " + targetLayoutName );
		            
		            //타겟 레이아웃 서버구분코드 조회  
	            	Map<String, Object> tgtMap = layoutManService.selectDetail(targetLayoutName);
	            	HashMap tgtDetailMap = (HashMap) tgtMap.get("detail");
	            	//타겟 레이아웃 없을시 에러
	            	if(tgtDetailMap == null){
	            		status = "실패";
	                	msg = "타겟 레이아웃이 존재하지 않습니다." ;
	                    logger.warn(msg);
		            	throw new Exception(msg);
	            	}
	            	
	            	String tgt_SevrDstCd = String.valueOf(tgtDetailMap.get("EAISEVRDSTCD"));
	            	
	            	logger.info("tgt EAISEVRDSTCD compare : " + eaiMsg_SevrDstCd + ", " +tgt_SevrDstCd);
	            	
	            	//인터페이스 서버구분코드와 비교 타겟 서비스구분코드와 같거나 9 이면 됨
	            	if(eaiMsg_SevrDstCd.equals("9")){
	            		if(!tgt_SevrDstCd.equals("9")){  
	            			status = "실패";
		                	msg = "타겟레이아웃 EAI서버구분코드가 일치하지 않습니다." ;
		                    logger.warn(msg);
			            	throw new Exception("타겟레이아웃 EAI서버구분코드가 일치하지 않습니다.");
	            		}
	            	}else {  //1,2,3,4 일경우
	            		if(!tgt_SevrDstCd.equals("9")){  
		            		if(!eaiMsg_SevrDstCd.equals(tgt_SevrDstCd)){
		            			status = "실패";
			                	msg = "타겟레이아웃 EAI서버구분코드가 일치하지 않습니다." ;
			                    logger.warn(msg);
				            	throw new Exception("타겟레이아웃 EAI서버구분코드가 일치하지 않습니다.");
		            		}
	            		}
	            	}
	            	
		            Layout targetLayout = service.loadLayout(targetLayoutName);
		            logger.info("targetLayout : "+targetLayout);
		            if (targetLayout == null) {
		                String error = "target layout not found ! - "
		                        + targetLayoutName;
		                logger.error( error ) ;
		                throw new Exception(error);
		            } else {
		                t.setTargetLayout(targetLayout);
		            }
	
		            ////////////////////
		            // source layouts
		            String sourceLayoutNames = arrData[ROW_TRAN_SRC_LOUT][COL_TRAN_INFO];
		            StringTokenizer tokens = new StringTokenizer(sourceLayoutNames, "\n");
	
		            while (tokens.hasMoreTokens()) {
		                String sourceLayoutName = tokens.nextToken().trim();
		                logger.info("sourceLayout :" + sourceLayoutName );
		                
		                //원천 레이아웃 서버구분코드 조회  
		            	//HashMap srcMap = layoutManService.selectDetail(targetLayoutName);
		            	HashMap srcDetailMap = (HashMap) tgtMap.get("detail");
		            	if(srcDetailMap == null){
		            		status = "실패";
		                	msg = "소스 레이아웃이 존재하지 않습니다." ;
		                    logger.warn(msg);
			            	throw new Exception(msg);
		            	}
		            	
		            	String src_SevrDstCd = String.valueOf(srcDetailMap.get("EAISEVRDSTCD"));
		            	
		            	logger.info("src EAISEVRDSTCD compare : " + eaiMsg_SevrDstCd + ", " +src_SevrDstCd);
		            	//인터페이스 서버구분코드와 비교 타겟 서비스구분코드와 같거나 9 이면 됨
		            	if(eaiMsg_SevrDstCd.equals("9")){
		            		if(!src_SevrDstCd.equals("9")){  
		            			status = "실패";
			                	msg = "원천레이아웃 EAI서버구분코드가 일치하지 않습니다." ;
			                    logger.warn(msg);
				            	throw new Exception("원천레이아웃  EAI서버구분코드가 일치하지 않습니다.");
		            		}
		            	}else {  //1,2,3,4 일경우
		            		if(!src_SevrDstCd.equals("9")){  
			            		if(!eaiMsg_SevrDstCd.equals(src_SevrDstCd)){
			            			status = "실패";
				                	msg = "원천레이아웃  EAI서버구분코드가 일치하지 않습니다." ;
				                    logger.warn(msg);
					            	throw new Exception("원천레이아웃  EAI서버구분코드가 일치하지 않습니다.");
			            		}
		            		}
		            	}
		            	
		            	//소스 레이아웃 없을시 에러
		                Layout sourceLayout = service.loadLayout(sourceLayoutName);
		                if (sourceLayout == null) {
		                    // layoutJdbcDao.load()
		                    String error = "source layout not found ! - "
		                            + sourceLayoutName;
		                    logger.error( error ) ;
		                    throw new Exception(error);
		                }
	
		                t.addSourceLayout(sourceLayout);
		            }
		            
		            int cellNum = 0;
		            for (int currentRow = DATA_ROW_OFFSET; currentRow < arrData.length; currentRow++) {
		                TransformItem item = new TransformItem();
		                //둘다 값이 필수
		                if(!arrData[currentRow][COL_RES_PATH].equals("") && !arrData[currentRow][COL_INST].equals("")){
		                	item.setTransform(t);
			                item.setResultItemPath(arrData[currentRow][COL_RES_PATH]);
			                item.setInstruction(arrData[currentRow][COL_INST]);
			                item.setDefaultValue(arrData[currentRow][COL_DEF_VALU]);
			                item.setSeqNo(CommonUtil.getInt(arrData[currentRow][COL_SEQ]));
			                if (item.getSeqNo() == 0) {
			                    item.setSeqNo(999);
			                }
			               
		                    t.addTransformItem(item);
		                }
		                
		                //둘중 하나 없을시 에러
		                if((!arrData[currentRow][COL_RES_PATH].equals("") && arrData[currentRow][COL_INST].equals("")) ||
		                	 arrData[currentRow][COL_RES_PATH].equals("") && !arrData[currentRow][COL_INST].equals("")) {
		                	status = "실패";
		                	msg = (cellNum+1) + "번째 변환 아이템 입력 오류입니다." ;
		                    logger.error(msg);
		                    throw new Exception("변환 아이템 입력 오류입니다.");
		                }
		                
		                cellNum++;
		            }
	
		            //////////////////
		            // set overwrite
		           
		            t.setOverwrite(overwrite);
	
		            /////////////////
		            // validation check
		            // 1. source layout does not exist
		            // 2. target layout does not exist
		            // 3. if( instruction is not "" )  try { Parser parse.parse(instruction) }
		            //     
		            
		            
		            logger.info("TR EXCEL UPLOAD : STEP 1" );
		            
		            Map map = new TreeMap();
		            map.put(t.getName(), t);
		            
		            //변환함수 map 넘기기
		            List<Map<String,Object>> transFuncList = service.selectAllTransFuncList();
		            
		            Map<String,Object> transFuncMap = new HashMap();
		      	    for(Map<String,Object> tmp : transFuncList ){
		      		  transFuncMap.put(tmp.get("CNVSNFUNTNNAME").toString(), tmp.get("CNVSNFUNTNDESC"));
		      	    }
		            
		            TransformValidator.trasnFormValidate(map,transFuncMap);
		          
		            logger.info("TR EXCEL UPLOAD : STEP 2 validate check OK " );
		            
		            /////////////////
		            // save transform
		            TransformVo vo = new TransformVo();
		            vo.setCnvsnName(t.getName());
		            vo.setCnvsnDesc(t.getDescription());
		            vo.setLastAmndHMS(CommonUtil.getToday(""));
	
		            /////////////////
		            // overwrite ?
		            if (t.getOverwrite()) {
		                // delete transform , TR01, TR02, TR03                    
		                service.deleteTransform(vo);
		            }
		           
		            logger.info("TR EXCEL UPLOAD : STEP 3 overwrite process OK " );
		            
		            /////////////////
		            // insert transform  : insert into TSEAITR01 (CnvsnName, CnvsnDesc) values(?,?)
		            try{
		            	 service.insertTransform(vo,eaiMsg_SevrDstCd);
		            }catch (Exception e){
		            	status = "실패";
		            	msg = "변환중복 등록입니다.";
		            	logger.error("변환중복 등록에러:" + e.getMessage() );
		            }
		           
	
		            logger.info("TR EXCEL UPLOAD : STEP 4 process OK " );
		            /////////////////
		            // insert target layout : insert into TSEAITR02 (cnvsnName, LoutName, SourceRsultDstcd) values(?,?,?)
		            vo.setLoutName(t.getTargetLayout().getName());
		            vo.setSourcRsultDstcd(TARGET_LAYOUT);
		            service.insertTransformLayout(vo);
		          
		            logger.info("TR EXCEL UPLOAD : STEP 5 target layout process OK " );
		            /////////////////
		            // insert source layouts(multi) : 
		            String srcFirstLayoutName = "" ;
		            Iterator it = t.getSourceLayoutNames();
		            while (it.hasNext()) {
		                String layoutName = (String) it.next();
		                vo.setLoutName(layoutName);
		                vo.setSourcRsultDstcd(SOURCE_LAYOUT);
		                service.insertTransformLayout(vo);
		                
		                if( "".equals(srcFirstLayoutName) ) {
		                    srcFirstLayoutName = layoutName ;
		                }
		            }
		            
		            logger.info("TR EXCEL UPLOAD : STEP 6 source layout process OK " );
		            
		            /////////////////
		            // insert transform items : insert into TSEAITR03 
		            // ( CnvsnName, CnvsnRsultItemPathName, CnvsnCmdName, CnvsnItemBascVal, CnvsnItemSerno)
		            // values ( ?, ?, ?, ?, ? )
		            List itemList = t.getTransformItemList();
		           
		            TransformItem transformItem = null;
		            for (int K = 0; K < itemList.size(); K++) {
		                transformItem = (TransformItem) itemList.get(K);
		                vo.setCnvsnRsultItemPathName(transformItem.getResultItemPath());
		                vo.setCnvsnCmdName(transformItem.getInstruction());
		                vo.setCnvsnItemBascVal(transformItem.getDefaultValue());
		                vo.setCnvsnItemSerno(transformItem.getSeqNo());
		                service.insertTransformItem(vo);
		            }
		            
		            logger.info("TR EXCEL UPLOAD : STEP 7 item process OK all process is finished ! " );
		            	
	            	logger.info("eai Message bizcode : "+bizCode);
	                // 업무권한체크				
	            	String userId = "";
	            	userId= SessionManager.getUserId(request);
	            	if(!"".equals(eaiSvcCode)){ //서비스 코드 있을경우
		                if (!"".equals(userId)) {
		                    List<HashMap> bzCdCondition = service.getUserBizCode(userId);
		                    
		                    for(HashMap bizMap : bzCdCondition){
		                    	String bizKy = (String)bizMap.get("BIZCODE");
		                    	if( bizKy.indexOf(bizCode) > -1 ) {
			                           isAccessable = true ;
			                       }
		                    }
		                }
	                
		                if( isAccessable == false ) {
		                	status = "실패";
		                    msgAddon = "접근권한이 없는 EAI 서비스코드를 사용하여 excel 업로드를 시도 했습니다.(서비스코드=" + eaiSvcCode + ", 업무그룹=" + bizCode ;
		                    logger.error(msgAddon);
		                } else {
		                	HashMap svcMap = new HashMap();
		                	
		                    String cnvsnType = vo.getCnvsnName();
		                    cnvsnType = cnvsnType.substring(cnvsnType.length()-3);
		                    vo.setCnvsnType(cnvsnType);
		                    
		                    logger.info("cnvsnType : "+cnvsnType);
		                    
	                    	svcMap.put("eaiSvcName", eaiSvcCode);
	 	                    svcMap.put("cnvsnType", cnvsnType);
	 	                    svcMap.put("cnvsnName", tranName);
	 	                   
							ServiceMessageEntity serviceMessageEntity = serviceMessageService
									.getById(new ServiceMessageEntityId(eaiSvcCode, 1));
	 	                    // 기동 : SVCMOTIVUSEDSTCD    수동 : PSVINTFACDSTICNAME
	 	                    String sync1 = eaiMessageEntity.getSvcmotivusedstcd();
	 	                    String sync2 = String.valueOf(serviceMessageEntity.getPsvintfacdsticname());
	 	                    
	 	                    // A-A 타입인 경우  요청/응답 구분없이 모두 요청전문으로 처리한다.
	 	                    if( "ASYN".equals(sync1) && "ASYN".equals(sync2) ) {
	 	                        if( "REQ".equals(vo.getCnvsnType()) || "RES".equals(vo.getCnvsnType()) ) {
	 	                            svcMap.put("cnvsnType", "REQ");
	 	                        }
	 	                    }
	 	                    logger.info("svcMap :"+svcMap.toString());
	 	                    //TSEAIHE02 UPDATE
	 	                    service.updateTransfromEaiSvcName(svcMap);
		                }
	            	}
		            
		            if( ! "".equals(msgAddon) ) {
		                msg = msg + "\n" + msgAddon ;
		            }
		            
		            //Reload
		            if( "성공".equals(status) ) {
		            	 logger.info("Reload START");
		                try {
		                    String msgInit = "[메모리동기화 처리결과:" + tranName + "]";
		                    msg = msg +msgInit ;
	
		                    if( isAccessable ) {
		                    	CommonCommand command = null;
		    	            	//변환 Reload
		    	            	command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",tranName);
		    					if (!validate(agentUtilService.broadcast(command))){
		    						msg = msg + "\n[변환 동기화 오류:" + tranName + "]" ;
		    						status = "실패";
		    						//throw new Exception("변환 동기화 오류 "+tranName);
		    					}
		    					//eai서비스 Reload
		    					if( !(eaiSvcCode == null || eaiSvcCode.length() == 0) ){
		    						command = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand",eaiSvcCode);
		    						if (!validate(agentUtilService.broadcast(command))){
		    							msg = msg + "\n[EAI 메시지 동기화 오류:" + eaiSvcCode + "]" ;
		    							status = "실패";
		    							//throw new Exception("EAI 메시지 동기화 오류 "+eaiSvcCode);
		    						}
		    	            	}
		                    }else{
		                    	 msg ="해당 업무코드 권한이 없어 동기화 하지 않았습니다";
		                    }
		                    
		                } catch ( Exception e ) {
		                	throw new Exception("전문레이아웃변환매핑 메모리동기화 에러 "+e.getMessage());
		                }
		            }        
		            		       
		            HashMap<String,Object> row2 = new HashMap<String,Object>();
	        		list = new ArrayList<HashMap<String,Object>>();
	        		row2.put("SHEETNAME" , sheetName);
	        		row2.put("TRNANAME", tranName);
	        		row2.put("EAISVCCODE", eaiSvcCode);
	        		row2.put("RESULT"    , status);
	        		row2.put("MESSAGE"   ,msg);
	        		list.add(row2);
	        		
	        	}catch(Throwable e){
	        		HashMap<String,Object> row = new HashMap<String,Object>();
	        		list = new ArrayList<HashMap<String,Object>>();
	        		row.put("SHEETNAME" , sheetName);
	        		row.put("TRNANAME", tranName);
	        		row.put("EAISVCCODE", eaiSvcCode);
	        		row.put("RESULT"    , status);
	        		row.put("MESSAGE"   ,msg);
	        		list.add(row);
	        	}
	        	
	        	result.addAll(list);
	        }   
        
    	} catch (Throwable e) {
			message = e.getMessage();
		}
    	//HashMap resultMap = new HashMap();
		resultMap.put("message"  , message);
		resultMap.put("rows"     , result);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);	
		return modelAndView;
	}     

    private boolean validate(HashMap<String,Object> map ){
    	for(String key : map.keySet()){
    		Object o = map.get(key);
    		if (o instanceof String){
    			if("success".equals((String)o)){
    				;
    			}else{
    				return false;
    			}
    		}else{
    			return false;
    		}
    	}
    	return true;
    }
}
