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

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.onl.dashboard.service.Dashboard2RepositoryService;


public class ItsmDashboardDBTransReportJob implements Job{
	private static final Logger logger = Logger.getLogger(ItsmDashboardDBTransReportJob.class);
    
    
    @Autowired
    @Qualifier("dashboard2RepositoryService")
    private static Dashboard2RepositoryService dashboard2Repository;
    
	private static DashboardTargetService dashboardTargetService;
    
	// 매일 자정 15분 에 업무구분코드  정보를 업데이트 한다.
    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
    	
    	if(logger.isInfoEnabled()) logger.info("START ItsmDashboardDBTransReportJob");
       // JobKey jobKey = context.getJobDetail().getKey();

   		ApplicationContext appContext = null;
   		try {
   			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
   			dashboard2Repository = (Dashboard2RepositoryService)appContext.getBean("dashboard2RepositoryService");
   			dashboardTargetService = (DashboardTargetService)appContext.getBean("DashboardTargetService");
   			
   		} catch (SchedulerException e) {
   			logger.error("applicationContext get module error",e);
   			return ;
   		}  
   		
   		try {
   			//금일 부터 전전일까지 거래건수 메모리 SAVE
   			setMemDayTranTotal();
   			
   			//금일 시간대별 거래건수 메모리 SAVE
   			setMemHourTranTotal();
   			
   			//peakday 가져오기
   			setPeakdayCnt();
   			
   			if(logger.isInfoEnabled()) logger.info("END ItsmDashboardTransReportJob");
   		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("ItsmDashboardDBTransReportJob error : ",e);
		}
   		
	}
  
    
    public static void  setMemDayTranTotal() throws Exception{
    	
    	String today = CommonUtil.getToday("yyyyMMdd");
    	String preday = getdelDate(today);
		
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes()){
			DataSourceContextHolder.setDataSourceType(d);
			List  daysTotalList = dashboardTargetService.getProcCountDayWithSR02(preday,today,d.getSchema());
			
			//메모리 저장
			dashboard2Repository.setItsmDashDayTranList(d.getName(), daysTotalList);
		}
		
		//일괄전송 건수
		DataSourceType bap = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAP);
		DataSourceContextHolder.setDataSourceType(bap);
		List  daysIsgTotalList = dashboardTargetService.getProcCountDateWithBJ08(preday,today,bap.getSchema());
		dashboard2Repository.setItsmDashDayTranList(bap.getName(), daysIsgTotalList);

		//배치 처리건수
		DataSourceType bat = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAT);
		DataSourceContextHolder.setDataSourceType(bat);
		List  daysBatchTotalList = dashboardTargetService.getProcCountDateWithES01(preday,today,bat.getSchema());
		dashboard2Repository.setItsmDashDayTranList(bat.getName(), daysBatchTotalList);
    	
    }
        
    
    public static void  setMemHourTranTotal() throws Exception{
    	
		String bfTime = "";
		String afTime = "";
		
    	Date date = new Date();
    	SimpleDateFormat dateF = new SimpleDateFormat("YYYYMMddHH"); 
    	
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	
    	cal.add(Calendar.HOUR, -10);
    	bfTime = dateF.format(cal.getTime());
    	
    	cal.setTime(date);
    	cal.add(Calendar.HOUR, 3);
    	afTime = dateF.format(cal.getTime());
    	
    	
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes()){
			DataSourceContextHolder.setDataSourceType(d);
			List  returnList = new ArrayList();
			
			HashMap param = new HashMap();
			param.put("schemaId", d.getSchema());
			param.put("startDt", bfTime.substring(0,8));
			param.put("startHh", bfTime.substring(8,10));
			param.put("endDt", afTime.substring(0,8));
			param.put("endHh", afTime.substring(8,10));
			param.put("compare", (bfTime.substring(0,8).equals(afTime.substring(0,8))?"Y":"N"));
			List  hourTotalList = dashboardTargetService.getHourProcCountWithSR02(param);
			
			returnList = getReturnHourList(hourTotalList);
			
			//메모리 저장
			dashboard2Repository.setItsmDashHourTranList(d.getName(), returnList);
		}
		
		//일괄전송 시간별 건수 추가
		//일괄전송 건수
		DataSourceType bap = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAP);
		DataSourceContextHolder.setDataSourceType(bap);
		HashMap bapParam = new HashMap();
		bapParam.put("schemaId", bap.getSchema());
		bapParam.put("startDt", bfTime);
		bapParam.put("endDt", afTime);
		List  hoursIsgTotalList = dashboardTargetService.getProcCountHourWithBJ08(bapParam);
		List  returnIsgList = getReturnHourList(hoursIsgTotalList);
		dashboard2Repository.setItsmDashHourTranList(bap.getName(), returnIsgList);
		
		//배치 시간별 건수 추가
		DataSourceType bat = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAT);
		DataSourceContextHolder.setDataSourceType(bat);
		HashMap batParam = new HashMap();
		batParam.put("schemaId", bat.getSchema());
		batParam.put("startDt", bfTime);
		batParam.put("endDt", afTime);
		List  hoursBatchTotalList = dashboardTargetService.getProcCountHourWithES01(batParam);
		List  returnBatchList = getReturnHourList(hoursBatchTotalList);
		dashboard2Repository.setItsmDashHourTranList(bat.getName(), returnBatchList);
    	
    }
    
    public static List getReturnHourList(List hourTotalList) throws Exception{
    	
    	List  returnList = new ArrayList();
    	HashMap returnMap = new HashMap();
    	
    	Date date = new Date();
    	SimpleDateFormat dateF = new SimpleDateFormat("YYYYMMddHH"); 
    	Calendar cal = Calendar.getInstance();
    	
    	String setTime = "";
    	cal.setTime(date);
    	cal.add(Calendar.HOUR, -11);
    	setTime= dateF.format(cal.getTime());
    	
    	int cnt = 13; //현재시간기준으로 -9시간  +3시간 표시 
		for(int i=0; i <= cnt ; i++){
			cal.add(Calendar.HOUR, 1);
	    	setTime= dateF.format(cal.getTime());
	    	
	    	boolean isTrue = false;
	    	
	    	returnMap = new HashMap();
	    	for(int k=0; k<hourTotalList.size() ; k++){
				HashMap tmp = (HashMap)hourTotalList.get(k);
				String compareHH = (String)tmp.get("BASEYMD") + (String)tmp.get("BASEHH");
				if(setTime.equals(compareHH)){
					returnMap.putAll(tmp);
					isTrue = true;
				}
	    	}
	    	if(!isTrue){
	    		returnMap.put("BASEYMD", setTime.subSequence(0, 8));
	    		returnMap.put("BASEHH", setTime.subSequence(8, 10));
	    		returnMap.put("TOTCOUNT", "0");
	    	}
	    	returnList.add(returnMap);
		}
		
		return returnList;
    	
    }
    
    
    public static void  setPeakdayCnt() throws Exception{
    	
    	DataSourceType ds = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
		DataSourceContextHolder.setDataSourceType(ds);
		
		String key    = MonitoringContext.RMS_PEAK_TRADE ;
		
		String peakVal = dashboardTargetService.getGroupPeakdayCnt(key);
		HashMap<String, String> peakdataMap;

		if (StringUtils.isNotBlank(peakVal)) {
			String[] peakData = peakVal.split(";");
			for (int i = 0; i < peakData.length; i++) {
				peakdataMap = new HashMap<>();
				String[] peakStr = peakData[i].split(",");
				peakdataMap.put("group", peakStr[0]);
				if (peakStr.length > 2) {
					peakdataMap.put("peakDay", peakStr[1]);
					peakdataMap.put("procnt", peakStr[2]);
				}
				dashboard2Repository.setItsmDashPeakdayInfo(peakStr[0], peakdataMap);
			}
		}
    }
    
 
    public static String getdelDate(String date) throws Exception {
  		String datePattern = "yyyyMMdd";
  		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(datePattern);
  		LocalDate localDate = LocalDate.parse(date,dtf).minusDays(2);

  		String addDateTime = localDate.format(dtf);
  		
  		return addDateTime;
  	}

  public static String getAddDate(String date) throws Exception 
	{
		String datePattern = "yyyyMMdd";
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(datePattern);
		LocalDate localDate = LocalDate.parse(date,dtf).plusDays(1);

		String addDateTime = localDate.format(dtf);
		
		return addDateTime;
	}
		
	
}
