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 ErrorLogMsgSendSmsJob implements Job{

	/**
	 * Logger
	 */
	private static final Logger logger = Logger.getLogger(ErrorLogMsgSendSmsJob.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 = "ErrorLogMsgSendSms";// 프로그램명
	private  String REQ_DIVISION = "NA"; 			// 요청구분
	
    
	// 매일 자정 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{
   			
   			errorLogSendSms();
   			
   			if(logger.isInfoEnabled()) logger.info("END ErrorLogMsgSendSmsJob");
   		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("ErrorLogMsgSendSmsJob error : ",e);
		}
			
   		
   	}
    
    
    //현재시간, 3분전 시간  TSEAILG3X  테이블서 에러 리스트 가져오기
    private void errorLogSendSms() throws Exception {
    	
    	int errCount = 0;
    	
    	errCount = Integer.parseInt(monitoringContext.getStringProperty(MonitoringContext.SMS_ERROR_COUNT));
    	
    	//현재시간
		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);
    	
    	//제외 에러코드
    	// TODO : fix hardcoding
    	String errorCd = "'S9100121', 'S9100123', 'S9100402', 'S9100603', 'S9100404', 'S9100405', 'S9100414'";
    	HashMap<String,String> sendMap  = new HashMap<String,String>();
    	
    	
    	for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
      		DataSourceContextHolder.setDataSourceType(d);
      		int totErrorCnt = 0;
    		
      		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);
	    	
	    	if(errorList != null && errorList.size() > 0){
	    		for(int i=0;i<errorList.size();i++){
		    		HashMap tmp = new HashMap(); 
		    		tmp = (HashMap)errorList.get(i);
		    		totErrorCnt += Integer.parseInt(tmp.get("CNT").toString());
		    	}	
	    	}
	    	
	    	if(logger.isInfoEnabled()) logger.info(d.getName() + " 건수 : " + totErrorCnt);
	    	
	    	//101건이상 SMS문자발송  각 시스템별이라 변경가능..
	    	if(totErrorCnt >= errCount ){
	    		String sendMsg = "["+d.getText()+ "]" + "EAI에서 3분 동안 "+totErrorCnt+"건 장애발생,상황도표출 대상아님";
	    		
	    		sendMap.put(d.getName(),sendMsg);
	    		
	    	}
    	
    	}
    	
    	boolean status = false;
    	
    	String schemaId = "";
    	DataSourceType dt = DataSourceTypeManager.getDataSourceType("MONITORING");
		DataSourceContextHolder.setDataSourceType(dt);
		if(dt != null){
			schemaId =dt.getSchema();
		}
		 
		//각 서버별 문자발송 할 서비스MAP 문자발송
    	Iterator<String> it = sendMap.keySet().iterator(); 
    	String sendTime = CommonUtil.getToday("YYYYMMddHHmmss");
    	
    	while( it.hasNext() ) {
			String systemId = it.next();  //내부/대외/공동/DMZ/오픈뱅킹
			HashMap paramMap = new HashMap();
			String msg = sendMap.get(systemId);
			paramMap.put("schemaId", schemaId);
			paramMap.put("errorYms", nowTime.substring(0,8)); //장애발생년월일
			paramMap.put("eaiSevrDstCd", systemId);
			
			//최근 문자발송이력 조회
			String lastSendTime = "";
			HashMap sendYmd = service.getErrorSmsSendYmd(paramMap);
    		lastSendTime = (String)sendYmd.get("SENDMSGYMD");
    		
    		if(lastSendTime != null){
    			
    			Date lastSendDate = dateF.parse(lastSendTime);
    			long lastSendTm = lastSendDate.getTime();
    			
    			date = dateF.parse(dateF.format(date));
    			long curDateTm = date.getTime();
    			
    			if(logger.isDebugEnabled()) logger.debug("문자발송 경과시간 : " + (curDateTm-lastSendTm)/60000);
    			
    			if((curDateTm-lastSendTm)/60000 >= 60){ // 발송시간으로부터 60분이상 지났을경우 문자발송 가능
    				status = sendSMS(sendTime , msg);
    			}

    			
    		}else{ //발송이력없음 문자바로 발송
    			status = sendSMS(sendTime , msg);
    		}
        		
    			
			if(status){
				 HashMap temp = new HashMap();
				 temp.put("errorSendYms", sendTime); 
				 temp.put("errorYms", nowTime.substring(0,8));
				 temp.put("eaiSevrDstCd", systemId);
				 temp.put("sendMsg", msg);
				 temp.put("schemaId", schemaId);
	    		 //sms 이력테이블 isert 
	    		 service.insertErrorSmsSendLog(temp);
    		
	    	}
			
    	}
		 
		
		
	}
    
    public boolean sendSMS(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]);
		
		if(logger.isInfoEnabled()) logger.info("ip:"+info[0] + "  port:"+info[1]);
		System.setProperty("ItsmPermIP", 	info[0]); 
		System.setProperty("ItsmPermPORT", 	info[1]);
		
		//문자받는대상자 : EAI담당자(EAI) + ITSM담당자(SQE) 
		
		boolean isSuccess = true;
		
		try{
			String[] sendGrp = {"EAI","SQE"};
			
			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 eaiErrcd){
    	
    	if(eaiErrcd.equals("S9OSA001")) return " SNA Adapter 호출 오류" ;
    	if(eaiErrcd.equals("S9OSA002")) return " SNA-NR송신오류수신";
    	if(eaiErrcd.equals("S9OSP003")) return " 가용소켓연결없음";
    	if(eaiErrcd.equals("S9OHP002")) return " HTTP응답포맷오류";
    	if(eaiErrcd.equals("S9OSP010")) return " SA타임아웃";
    	if(eaiErrcd.equals("S9OSA010")) return " SA타임아웃";
    	if(eaiErrcd.equals("S9OHP030")) return " 응답변환에러" ;
    	if(eaiErrcd.equals("S9OSA888")) return " SNA G/W오류발생" ;
    	if(eaiErrcd.equals("S9OSA020")) return " 변환에러";
    	if(eaiErrcd.equals("S9OHP022")) return " 요청변환설정에러" ;
    	if(eaiErrcd.equals("S9FBF001")) return " Outbound호출에러";
    	if(eaiErrcd.equals("S9FBR001")) return " Outbound호출에러" ;
    	if(eaiErrcd.equals("S9FBR003")) return " 어댑터초기화실패" ;
    	if(eaiErrcd.equals("S9OSP020")) return " 변환중오류발생";
    	if(eaiErrcd.equals("S9OSP030")) return " 응답메세지변환오류" ;
    	if(eaiErrcd.equals("S9OCO000")) return " 송신전처리에러";
    	else return " 오류 발생 , 즉시 확인조치바람";
    	
    	
    }
    
    
    
    

	
}
