package com.eactive.eai.batch.job.jobModule;

import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.CommonKeys;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.message.EAIBatchMsgManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.UCMsgSenderUtil;
import com.eactive.eai.common.util.UUIDGenerator;

public class ReSendReqSend {
	
	protected static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static BatchDoc insertJobToQueue(BatchDoc batchDoc){
    	
    	SchedulerMessageManager manager = SchedulerMessageManager.getInstance();
    	SchedulerMessageVO scheduleInfo = null;
    	
    	try {
    		scheduleInfo = manager.getReqSendSchedule( batchDoc.getBatchMsg().getHeader().getScheduleCode());
    		
    		
			//String strEndTime = scheduleInfo.getEndTime();
			String strReStartTime = DatetimeUtil.getNextTime((scheduleInfo.getRecvRetrySecs()/60)).substring(0, 4);
			
			//int  endTime = Integer.parseInt(strEndTime);
    		//int  reStartTime = Integer.parseInt(strReStartTime);

    		long endDateTime = Long.parseLong(batchDoc.getBatchMsg().getHeader().getScheduleETime());          //전송 종료 시각
    		long startDateTime = Long.parseLong(DatetimeUtil.getCurrentDate() +strReStartTime+"00" + "000");
    		
//System.out.println("ReSendReqSend ] endDateTime / startDateTime - ["+endDateTime +"/"+ startDateTime +"]");    		
    		
    		
    		int  rerytCount = scheduleInfo.getRecvRetryCnt();
    		int  failCount = scheduleInfo.getRecvFailCnt();
        	
			if (endDateTime > startDateTime &&  (rerytCount ==0 || failCount < rerytCount)){	//종료시간안에 있어야 재송신하기 위한 작업큐에 등록한다.)
    	
				//BATCH작업 요청메시지ID 및 스케쥴 송수신 시각 설정
	    		//요구송신의 재처리의 경우 UUID는 새로 생성해야 한다.
    			String uuid = UUIDGenerator.getUUID();

	    		//scheduleInfo.setUUID           (uuid);//로깅을 위해 새로운 uuid 할당한다.  2009.9.22 sub_uuid만 변경한다.
    			scheduleInfo.setUUID(batchDoc.getBatchMsg().getHeader().getUUID());
	    		scheduleInfo.setSubUUID        (uuid);
	    		scheduleInfo.setFilePath       (batchDoc.getBatchMsg().getHeader().getFilePath());
	    		scheduleInfo.setFileName       (batchDoc.getBatchMsg().getHeader().getFileName());
	    		scheduleInfo.setRenamedFileName(batchDoc.getBatchMsg().getHeader().getRenamedFileName());
	    		scheduleInfo.setInstitutionName(batchDoc.getBatchMsg().getHeader().getInstitutionName());
	    		scheduleInfo.setProcessName(batchDoc.getBatchMsg().getHeader().getProcessName());
	    		scheduleInfo.setHdrInfoName(batchDoc.getBatchMsg().getHeader().getHdrInfoName());
	    		
	    		
	    		scheduleInfo.setStartTime(""+startDateTime);
	    		scheduleInfo.setEndTime(""+endDateTime);
    	

				BatchDoc newBatchDoc =  EAIBatchMsgManager.createBatchMsg(true);         	
				newBatchDoc.getBatchMsg().getHeader().setBatchStartTime(CalendarUtil.getCurrentTimeNoDash());
				newBatchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
	    		
				//JOB QUEUE 테이블에 등록
	    		int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(scheduleInfo);
	    		logger.info("[요구송신 재처리를 위한 전처리  단계 수행] ==> 배치 JOB QUEUE 테이블 INSERT 건수: "+ resultCnt);
	
	    		//DB로그를 위해서 조회정보를 batchDoc에 세팅
	    		//newBatchDoc.getEAIBatchMessage().getHeader().setUUID(uuid);
	    		newBatchDoc.getBatchMsg().getHeader().setUUID(scheduleInfo.getUUID());
	    		newBatchDoc.getBatchMsg().getBody().setSubUUID(uuid);

	    		newBatchDoc.getBatchMsg().getHeader().setScheduleSTime(scheduleInfo.getStartTime());        //전송 시작 시각
	    		newBatchDoc.getBatchMsg().getHeader().setScheduleETime(scheduleInfo.getEndTime());
	    		newBatchDoc.getBatchMsg().getHeader().setLayerCode(CommonKeys.LAYER_SCHEDULER);
	    		newBatchDoc.getBatchMsg().getHeader().setBizCode(batchDoc.getBatchMsg().getHeader().getBizCode());
	    		newBatchDoc.getBatchMsg().getHeader().setBlockSize(batchDoc.getBatchMsg().getHeader().getBlockSize());
	    		newBatchDoc.getBatchMsg().getHeader().setFileName(batchDoc.getBatchMsg().getHeader().getFileName());
	    		newBatchDoc.getBatchMsg().getHeader().setScheduleCode(batchDoc.getBatchMsg().getHeader().getScheduleCode());
	    		newBatchDoc.getBatchMsg().getHeader().setProcessType(batchDoc.getBatchMsg().getHeader().getProcessType());
	    		newBatchDoc.getBatchMsg().getHeader().setInstitutionCode(batchDoc.getBatchMsg().getHeader().getInstitutionCode());
	    		newBatchDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID());
	    		newBatchDoc.getBatchMsg().getHeader().setUserName(batchDoc.getBatchMsg().getHeader().getUserName());
	    		newBatchDoc.getBatchMsg().getHeader().setSystemConnCode(batchDoc.getBatchMsg().getHeader().getSystemConnCode());
	    		newBatchDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP());
	    		newBatchDoc.getBatchMsg().getHeader().setRuleCode(batchDoc.getBatchMsg().getHeader().getRuleCode());
	    		newBatchDoc.getBatchMsg().getHeader().setProcessCode(batchDoc.getBatchMsg().getHeader().getProcessCode());
	    		
	    		newBatchDoc.getBatchMsg().getBody().setWLIServerName(batchDoc.getBatchMsg().getBody().getWLIServerName());
	    		newBatchDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_QUEUE);
	    		newBatchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
	    		newBatchDoc.getBatchMsg().getBody().setErrorCode(0);
	    		newBatchDoc.getBatchMsg().getBody().setErrorMsg("");
	    		newBatchDoc.getBatchMsg().getBody().setRetryCount(scheduleInfo.getRecvFailCnt());

	    		//요구송신 재처리에  대한 최초 DB로그. StartLog 호출.
	    		LogUtil.setStartLog (newBatchDoc);
			}else {
				if (scheduleInfo != null) {// 20250910 obl
					String msg = "[요구송신 재처리를 위한 전처리  단계 수행]  "+ scheduleInfo.getScheduleCode() +" | "+ scheduleInfo.getProcessCode() +" | "+ scheduleInfo.getInstitutionCode() +" | "+ scheduleInfo.getBizCode() +" | "+ scheduleInfo.getStartTime() +" | "+ scheduleInfo.getEndTime() +"  ==> 종료시간이 되었거나 재시도 회수를 초과하여 JOB QUEUE에 등록하지 않음. (미완료 작업건수/재시도 횟수: "+ scheduleInfo.getRecvFailCnt() +"/"+scheduleInfo.getRecvRetryCnt()+") - endTime/reStartTime" +"["+endDateTime  +"/"+ startDateTime +"]\n" + batchDoc.getBatchMsg().getBody().getErrorMsg() ; 
					batchDoc.getBatchMsg().getBody().setErrorMsg(msg);
					logger.warn(msg);
				}else {
					batchDoc.getBatchMsg().getBody().setErrorMsg("[요구송신 재처리를 위한 전처리  단계 수행] scheduleInfo is null");
					logger.warn("[요구송신 재처리를 위한 전처리  단계 수행] scheduleInfo is null");
				}
				UCMsgSenderUtil.sendUCMsg(batchDoc);
			}
			
    		return batchDoc;
	
    	}catch (Exception ex) {
    		String errMsg = "요구 송신 재처리를 위해 Queue에 데이터 insert시 오류가 발생했습니다. -  ["+batchDoc.getBatchMsg().getHeader().getProcessCode()+"/"+scheduleInfo.getScheduleCode()+"]\n" + batchDoc.getBatchMsg().getBody().getErrorMsg();
            batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
    		UCMsgSenderUtil.sendUCMsg(batchDoc);
            logger.error( ex.getMessage(), ex);
            
            return batchDoc;
        }
    }
}
