package com.eactive.eai.common.util;

import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.osd.OutsideVO;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.common.property.PropManager;
//import com.eactive.eai.common.server.EAIServerManager;

public class UCMsgSenderUtil {

    public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    
    public static final String UCINFO           = "UCInfo";
    public static final String FEP_RECEIVER     = "fep.receiver";  //FEP일괄전송 담당자 UC ID - ,로 분리
//    private static final String SUBJECT          = "subject";
//    private static final String URL              = "UC.url";
//    private static final String SENDER           = "UC.sender";
    public static final String CHECK_PERIOD     = "check.period";

    private UCMsgSenderUtil(){
    }

    public static void sendUcMsg( String contents, String recvid, String fileName ){
//		try{
//			
//			if ( recvid == null || recvid.trim().equals("") ) return;
//    		if ( recvid.startsWith("00") ){
//    			recvid = "98" + recvid.substring(2);
//    		}
//
//			Properties prop = PropManager.getInstance().getProperties(UCINFO);
//			String sysGb = "운영";
//			if ( EAIServerManager.getInstance().isDEAIServer() )
//				sysGb = "개발";
//			if ( EAIServerManager.getInstance().isTEAIServer() )
//				sysGb = "검증";
//			String subject = prop.getProperty(SUBJECT) + "<" +sysGb+ ">";
//			if ( fileName != null )
//				subject = subject + fileName;
//			
//			String Encoding = "UTF-8";
//			String ucUrl = prop.getProperty(URL);
//			String sender = prop.getProperty(SENDER);
//
//			URL url = new URL(ucUrl);
//			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//			urlConn.setRequestMethod("POST");
//			urlConn.setDoOutput(true);
//
//			OutputStream os = urlConn.getOutputStream();
//
//
//			BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(os));
//			bw1.write("CMD=MSG&Action=ALERT&SystemName=FEP 일괄전송["+sysGb+"]&SendName="+sender+"&RecvID="+recvid+"&Subject="+subject+"&Subject_Encode="+Encoding+"&Contents="+contents+"&Option=UM=POST,EN=BASE64H,SP=F,LT=20,TP=50,WD=600,HG=520,IT=N,IR=Y");
//
//			bw1.flush();
//			bw1.close();
//
//			BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
//			String str = "";
//			while((str = br.readLine()) != null){
//				logger.debug(str);
//			}
//			br.close();
//		}catch(Exception e){
//			logger.error(e.getMessage(), e);
//		}
    }
    
    public static void setUcMsg(BatchJobInfoVO info, String fileName, boolean success, String msg ){
    	
    	if ( info == null ) return;
    	if (!info.getRecvNotiUseYn().equals("1")){
    		return;
    	}
    	String procCode = fileName.substring(0, 5);
    	String instCode = fileName.substring(6, 10);
    	String procName = "";
    	String instName = "";
    	OutsideVO osd = OutsideManager.getInstance().getOutsideInfo(procCode, instCode);
    	if ( osd != null ){
    		procName = osd.getBatchName();
    		instName = osd.getOsdName();
    	}
    	String contents = "업무구분명 : " + procName + "<p>" ;
    	contents += "대외기관명 : " + instName + "<p>" ;
    	contents += "파일 구분자 : " + info.getJobTranDstcd() + "<p>" ;
    	contents += "파일    명 : " + fileName + "<p>" ;
    	contents += "파일  설명 : " + info.getMsgDstName() + "<p>" ;
    	if ( success ){
    		contents += "파일 수신에 성공하였습니다.";
        	String[] ids = info.getChrgIDs();
        	for (int inx = 0; inx < ids.length; inx++) {
        		String receiver = ids[inx];
        		if ( receiver == null || receiver.trim().equals("") ) return;
        		if ( info.getRecvUseYN().equals("1") )
        			sendUcMsg(contents, receiver, fileName);
    		}
    	}else{
    		contents += "파일 수신에 성공하였으나 계정계 전송에 실패 하였습니다.<p>";
    		contents += msg;
        	String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(",");
        	for (int inx = 0; inx < ids.length; inx++) {
        		String receiver = ids[inx];
        		if ( receiver == null || receiver.trim().equals("") ) return;
        		if ( info.getRecvUseYN().equals("1") )
        			sendUcMsg(contents, receiver, fileName);
    		}
    	}

    }
    
    public static void sendUCMsg(BatchDoc batchDoc){
    	String msg = "다음과 같은 원인으로 일괄전송 송/수신 작업이 실패 하였습니다. <p>";
    	msg += "이 쪽지는 시스템 상황에 따라 발송 되지 않을 수 있습니다. <p>";
    	if (batchDoc.getBatchMsg().getBody().getErrorMsg() != null )
    		msg += "<pre>" + batchDoc.getBatchMsg().getBody().getErrorMsg() + "</pre><p>";
    	
    	msg += "<pre>" + batchDoc + "</pre>";
    	String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(",");
    	for (int inx = 0; inx < ids.length; inx++) {
    		String receiver = ids[inx];
    		if ( receiver == null || receiver.trim().equals("") ) continue;
    		logger.debug("[sendUCMsg]receiver-->" + receiver);
    		logger.debug("[sendUCMsg]msg-->" + msg);
			sendUcMsg(msg, receiver, null);
		}
    	
    	String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
    	String bizCode  = batchDoc.getBatchMsg().getHeader().getBizCode();
    	BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd( procCode, bizCode );
    	String[] receivers = {};
    	if ( jvo != null ){
    		receivers = jvo.getChrgIDs();
    	}
    	for (int inx = 0; inx < receivers.length; inx++) {
    		String receiver = receivers[inx];
    		if ( receiver == null || receiver.trim().equals("") ) continue;
    		logger.debug("[sendUCMsg]receiver-->" + receiver);
    		logger.debug("[sendUCMsg]msg-->" + msg);
			sendUcMsg(msg, receiver, null);
		}
    }
    
    public static void sendUCMsg( String msg ){
    	String[] ids = PropManager.getInstance().getProperties(UCINFO).getProperty(FEP_RECEIVER).split(",");
    	for (int inx = 0; inx < ids.length; inx++) {
    		String receiver = ids[inx];
    		if ( receiver == null || receiver.trim().equals("") ) return;
    		logger.debug("[sendUCMsg]receiver-->" + receiver);
    		logger.debug("[sendUCMsg]msg-->" + msg);
			sendUcMsg(msg, receiver, null);
		}
    }
}