package com.eactive.eai.rms.onl.common.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

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.CommonUtil;
import com.eactive.eai.rms.common.util.ItsmSmsSender;

public class RecvTranCdErrorLogSendSmsJob implements Job{

	/**
	 * Logger
	 */
	private static final Logger logger = Logger.getLogger(RecvTranCdErrorLogSendSmsJob.class);
    
	private ItsmSchedulerService service;
	private transient MonitoringContext monitoringContext;

	private  String DIVISION = "INFO"; 			// 전문구분
	private  int REQ_GRP_MODE = 3; 			    // 요청구분자
	private  String SEND_EMPNO = "1562325"; 		// 발송자사번
	private  String SEND_TYPE = "P"; 			    // 발송대상타입
	private  String APP_CODE = "EAI"; 			// 어플리케이션코드
	private  String PROGRAM_NAME = "RecvTranCdErrorLog";			// 프로그램명
	private  String REQ_DIVISION = "NA"; 			// 요청구분
	private  String DELIMITER = " "; 
	
    
	// 매일 자정 15분 에 업무구분코드  정보를 업데이트 한다.
    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
    	
    	if(logger.isInfoEnabled()) logger.info("START RecvTranCdErrorLogSendSmsJob");

   		ApplicationContext appContext = null;
   		try {
   			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
   			service = (ItsmSchedulerService)appContext.getBean("itsmSchedulerService");
   			monitoringContext    = (MonitoringContext)appContext.getBean("monitoringContext");
   			
   		} catch (SchedulerException e) {
   			logger.error("applicationContext get module error",e);
   			return ;
   		}  
   		
   		
   		try{
   			
   			recvTranCdErrorLogSendSms();
   			
   			if(logger.isInfoEnabled()) logger.info("END RecvTranCdErrorLogSendSmsJob");
   		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("RecvTranCdErrorLogSendSmsJob error : ",e);
		}
			
   		
   	}
    
    
    //현재시간, 3분전 시간  TSEAILG3X  테이블서 에러 리스트 가져오기
    private void recvTranCdErrorLogSendSms() throws Exception {
    	
    	//현재시간
		String nowTime = "";
		//3분전 시간
		String bfTime = "";
		
    	Date date = new Date();
    	SimpleDateFormat dateF = new SimpleDateFormat("YYYYMMddHHmmss"); 
    	
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	nowTime = dateF.format(cal.getTime());
    	
    	cal.add(Calendar.MINUTE, -3);
    	bfTime = dateF.format(cal.getTime());
    	
    	//테이블명
    	String tableName = CommonUtil.getLogErrTable(nowTime.substring(0,8));
    	if(logger.isDebugEnabled()) logger.debug("현재시간 : " + nowTime  + " ,3분전시간 : " + bfTime);
    	
    	//제외 에러코드
    	String errorCd = "'S9100121', 'S9100123', 'S9100402', 'S9100603', 'S9100404', 'S9100405', 'S9100414'";
    	HashMap<String,HashMap> sendMap  = new HashMap<String,HashMap>();
    	
    	for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
      		DataSourceContextHolder.setDataSourceType(d);
    		
      		HashMap paramMap = new HashMap();    
      		paramMap.put("startDt",bfTime+"000"); 
      		paramMap.put("endDt"  ,nowTime+"000");
      		paramMap.put("tableName",tableName);
      		paramMap.put("ERRORCD",errorCd);
        	paramMap.put("schemaId", d.getSchema());
        	
      		
	    	//현재시간으로부터 3분동안 수신거래코드별 에러리스트 가져오기 
	    	List errorList = service.getRecvTranCdErrorLogList(paramMap);
	    	
	    	String sendMsg = "";
	    	
	    	if(logger.isInfoEnabled()) logger.info(d.getName() + ", 에러 리스트 사이즈 : " + errorList.size());
	   	 	
	    	if(errorList != null && errorList.size() > 0){
	    		
		    	for(int i=0;i<errorList.size();i++){
		    		
		    		String eaisvcname = "";   //서비스코드
	    			String logErrorCd = "";		//에러코드
	    			String errMsg = "";		//에러메세지
	    			String eaisevrinstncname =   "";	//인스턴스명
	    			String exOrgNm = ""; 		//확인필요
	    			String bizCode = "";		//업무코드
	    			
	    			String errorRecvTranCd = "";   //에러수신거래코드
		    		
		    		HashMap tmp = new HashMap(); 
		    		tmp = (HashMap)errorList.get(i);
		    		//수신코드거래의 건수 확인
		    		if(logger.isDebugEnabled()) logger.debug(d.getName() + " ,건수 : " + tmp.get("CNT"));
		    		
		    		if(Integer.parseInt(tmp.get("CNT").toString()) >= 40){
		    			
		    			errorRecvTranCd = tmp.get("TELGMRECVTRANCD").toString();
		    			logErrorCd = tmp.get("ERRCD").toString();				//에러코드
		    			eaisvcname = tmp.get("EAISVCNAME").toString();  	//서비스코드
		    			eaisevrinstncname =   tmp.get("EAISEVRINSTNCNAME").toString();	//인스턴스명
		    			errMsg = getErrorMsg(logErrorCd);		//에러메세지
		    			exOrgNm = "";
		    			//업무코드 서비스코드의 업무코드로 수정 20201020 
		    			bizCode = tmp.get("EAIBZWKDSTCD").toString();
		    			//bizCode = eaisvcname.substring(eaisvcname.length()-6,eaisvcname.length()-3);
		    			
			    	    //EaiSvccd + errorCd + 에러메세지 + LgingSysInstncID + exOrgNm
			    		sendMsg = eaisvcname + DELIMITER + logErrorCd + DELIMITER + errMsg +DELIMITER +  eaisevrinstncname + DELIMITER +  exOrgNm;
		    		    HashMap tMap = new HashMap();
		    		    tMap.put("errorRecvTranCd", errorRecvTranCd); //수신거래코드
		    		    tMap.put("errorCd", logErrorCd); //에러코드	
		    		    tMap.put("bizCode", bizCode);  //업무코드
		    		    tMap.put("sendMsg", sendMsg); //발송메세지
		    		    tMap.put("errorYms", nowTime.substring(0,8)); //장애발생년월일
		    		    sendMap.put(errorRecvTranCd, tMap);
		    		    
		    			}
	    			
	    			}
	    		}
    		}
    	
	    	
    	//각 서버별 문자발송 할 서비스MAP 문자발송
    	Iterator<String> it = sendMap.keySet().iterator();
    	String schemaId = "";
    	DataSourceType dt = DataSourceTypeManager.getDataSourceType("MONITORING");
		DataSourceContextHolder.setDataSourceType(dt);
		if(dt != null){
			schemaId =dt.getSchema();
		}
    	
		//마지막 발송시간 
		String lastSendTime = "";
		
		while( it.hasNext() ) {
			String key = it.next();  //에러수신거래코드
			HashMap temp = new HashMap();
			temp = sendMap.get(key);
			temp.put("schemaId", schemaId);
			
			HashMap sendYmd = service.getRecvTranCdErrorSendSmsInfo(temp);
			lastSendTime = (String)sendYmd.get("SENDMSGYMD");
			
			boolean isSendSms = false; //sms 발송가능 여부
			
			if(lastSendTime != null){

    			Date lastSendDate = dateF.parse(lastSendTime);
    			long lastSendTm = lastSendDate.getTime();
    			
    			date = dateF.parse(dateF.format(date));
    			long curDateTm = date.getTime();
    			
    			if(logger.isInfoEnabled()) logger.info("마지막문자발송 시간 : " + (curDateTm-lastSendTm)/60000 + " 분 경과");
    			
    			if((curDateTm-lastSendTm)/60000 > 60){ // 발송시간으로부터 60분이상 지났을경우 문자발송 가능
    				
    				isSendSms =  true;
    			}
    			
    		}else{
    			isSendSms =  true;
    		}
			
        		
			if(isSendSms){
				boolean status = sendSMS((String)temp.get("bizCode"), nowTime , (String)temp.get("sendMsg"));
				if(logger.isDebugEnabled()) logger.debug("문자발송 결과  :  " + status + " , 문자발송 업무코드:" + (String)temp.get("bizCode"));
				if(status){
					 temp.put("errorSendYms", nowTime); 
					 temp.put("errorYms", nowTime.substring(0,8));
					 temp.put("schemaId", schemaId);
		    		 //sms 이력테이블 isert 
		    		 service.insertErrorRecvTranCdSmsSendLog(temp);
				}
			}	
    	
		}
    	
		
	}


	public boolean sendSMS(String bizCode,String sendTime , String msg) {
		String[] info = null;
		String sms_ip = monitoringContext.getStringProperty(MonitoringContext.ITSMPERM_IP,"");
		String sms_port = monitoringContext.getStringProperty(MonitoringContext.ITSMPERM_PORT,"");
		
		String[] resultValue = {sms_ip, sms_port};
		info = resultValue;
		if(logger.isInfoEnabled()) logger.info("sms ip:"+info[0] + "  port:"+info[1]);
		
		System.setProperty("ItsmPermIP", 	info[0]); 
		System.setProperty("ItsmPermPORT", 	info[1]);
		
		//문자받는대상자 : EAI담당자(EAI) + ITSM담당자(SQE) + 업무코드(KFM) 
		
		boolean isSuccess = true;
		
		try{
			String[] sendGrp = {"EAI","SQE",bizCode};
			
			for(int i=0 ; i<sendGrp.length;i++){
				
				isSuccess = ItsmSmsSender.errorSendSMS(DIVISION,REQ_GRP_MODE,sendGrp[i],sendTime ,SEND_EMPNO,SEND_TYPE,APP_CODE,PROGRAM_NAME,REQ_DIVISION, msg);
			}
			
			

		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("sendSMS error : ",e);
			isSuccess = false;
			
		}
		return isSuccess;
		
	}
    
    
    
    public String getErrorMsg(String eaiErrorCd){
    	
    	if(eaiErrorCd.equals("S9OSA001")) return " SNA Adapter 호출 오류" ;
    	if(eaiErrorCd.equals("S9OSA002")) return " SNA-NR송신오류수신";
    	if(eaiErrorCd.equals("S9OSP003")) return " 가용소켓연결없음";
    	if(eaiErrorCd.equals("S9OHP002")) return " HTTP응답포맷오류";
    	if(eaiErrorCd.equals("S9OSP010")) return " SA타임아웃";
    	if(eaiErrorCd.equals("S9OSA010")) return " SA타임아웃";
    	if(eaiErrorCd.equals("S9OHP030")) return " 응답변환에러" ;
    	if(eaiErrorCd.equals("S9OSA888")) return " SNA G/W오류발생" ;
    	if(eaiErrorCd.equals("S9OSA020")) return " 변환에러";
    	if(eaiErrorCd.equals("S9OHP022")) return " 요청변환설정에러" ;
    	if(eaiErrorCd.equals("S9FBF001")) return " Outbound호출에러";
    	if(eaiErrorCd.equals("S9FBR001")) return " Outbound호출에러" ;
    	if(eaiErrorCd.equals("S9FBR003")) return " 어댑터초기화실패" ;
    	if(eaiErrorCd.equals("S9OSP020")) return " 변환중오류발생";
    	if(eaiErrorCd.equals("S9OSP030")) return " 응답메세지변환오류" ;
    	if(eaiErrorCd.equals("S9OCO000")) return " 송신전처리에러";
    	else return " 오류 발생 , 즉시 확인조치바람";
    	
    	
    }
    
    
    
    

	
}
