package com.eactive.eai.rms.onl.dashboard.dao;

import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
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.SpecifiedDataSourceExecutor;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.ibatis.sqlmap.client.event.RowHandler;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

@Repository("dashboardError")
@SuppressWarnings("unchecked")
public class DashboardErrorDaoImpl extends SqlMapClientTemplateDao implements DashboardErrorDAO {

	private int MAX_ROWS = 20;
	
    @Autowired
    private MonitoringContext monitoringContextImpl;
	
	private static final Logger logger = Logger.getLogger(DashboardErrorDaoImpl.class);
	
	private String getTimeOutList() throws Exception {

    	DataSourceType dt = DataSourceContextHolder.getDataSourceType();
    	String timeOutCodes = null;
    	
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", dt.getSchema());
         
		@SuppressWarnings("unchecked")
		List<HashMap<String, Object>> result = new SpecifiedDataSourceExecutor<List<HashMap<String, Object>>>(dt) {
            protected List<HashMap<String, Object>> doExecute() throws Exception {
                return template.queryForList("DashboardError.getTimeOutList", paramMap);
            }
        }.execute();
		try {
			if ( !result.isEmpty() || result.size() > 0 ) {
				for(HashMap<String, Object> tmp : result){
					timeOutCodes = "'" + tmp.get("Prpty2Val") + "'";
					timeOutCodes = timeOutCodes.replaceAll(",", "','");
				}
				
			} else {
				timeOutCodes = "'RECEAIOSA777','RECEAIOHP003','RECEAIOSP004','RECEAIOTC913','RECEAIOSA010','RECEAIOEP010','RECEAIOHP010','RECEAIOSP010','RECEAIOTP010'";
			}
			return timeOutCodes;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getTimeOutList error", e);
			throw e;
		}
	}
	
	private String getBizErrorList() throws Exception {

    	DataSourceType dt = DataSourceContextHolder.getDataSourceType();
    	String bizErrorCodes = null;
    	
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", dt.getSchema());
         
		@SuppressWarnings("unchecked")
		List<HashMap<String, Object>> result = new SpecifiedDataSourceExecutor<List<HashMap<String, Object>>>(dt) {
            protected List<HashMap<String, Object>> doExecute() throws Exception {
                return template.queryForList("DashboardError.getBizErrorList", paramMap);
            }
        }.execute();
		try {
			if ( !result.isEmpty() || result.size() > 0 ) {
				for(HashMap<String, Object> tmp : result){
					bizErrorCodes = "'" + tmp.get("Prpty2Val") + "'";
					bizErrorCodes = bizErrorCodes.replaceAll(",", "','");
				}
			} else {
				bizErrorCodes = "'RECEAICEU104','RECEAICKE301','RECEAIIRP040','RECEAIOEP020','RECEAIOEP030','RECEAIOHP020','RECEAIOHP022','RECEAIOHP030','RECEAIOMP002','RECEAIOMP006','RECEAIOSA020','RECEAIOSP020','RECEAIOSP030','RECEAIOTP002','RECEAIOTP006','RECEAICBE001','RECEAICBE010','RECEAICBX001','RECEAICME001','RECEAICMK001','RECEAIFBR002','RECEAIIRA001','RECEAIIRP050','RECEAIIRP060','RECEAIIRP062'";
			}
			return bizErrorCodes;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getBizErrorList error", e);
			throw e;
		}
	}

	public Vector<String[]> getLogList(String owner, String logTime, String nodeIndex,
			String errorType, String commDiv) throws Exception {

		String timeOutError = getTimeOutList();
		String bizError = getBizErrorList();
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("logTablename",    CommonUtil.getLogErrTable(CommonUtil.getToday("")) );
        paramMap.put("logTablename2",   CommonUtil.getLogTable(Calendar.getInstance(), true));

        paramMap.put("rowno",    String.valueOf(MAX_ROWS));
        paramMap.put("logDate",    CommonUtil.getToday("yyyyMMdd"));
        paramMap.put("logTime",    logTime.replaceAll(":", ""));
        paramMap.put("commDiv",    commDiv);
        paramMap.put("nodeIndex",   nodeIndex);
		if (errorType != null && errorType.trim().length() > 1) {
	        paramMap.put("errorType",    errorType);
	        paramMap.put("timeOutList",  timeOutError);
	        paramMap.put("bizError",  bizError);
		}
        
		try {

			final Vector<String[]> vt = new Vector<String[]>();
	    	template.queryWithRowHandler("DashboardError.getLogList", paramMap,
	    			new RowHandler(){
	                    public void handleRow(Object valueObject) {

	            			HashMap<String, String> rowMap = (HashMap<String, String>)valueObject;

	            			String errorTypeTxt = "업무에러";
	            			if("TIMEOUT".equals(errorType)){
	            				errorTypeTxt = "타임아웃";
	            			}else if("CONNECTION".equals(errorType)){
	            				errorTypeTxt = "통신에러";
	            			}
	            			
	    					String[] row = new String[14];
	    					row[0] = rowMap.get("GUID");
	    					row[1] = rowMap.get("EAISvcName");
	    					row[2] = rowMap.get("BzwkDsticName");
	    					row[3] = rowMap.get("EAIErrCd");
	    					row[4] = chunkErrorMsg(rowMap.get("EAIErrCtnt"));
	    					row[5] = rowMap.get("EaiSevrInstncName");
	    					row[6] = rowMap.get("MsgDpstYMS");
	    					row[7] = errorTypeTxt;
	    					//row[7] = (timeOutError.indexOf(rowMap.get("EAIErrCd")) > 0) ? "타임아웃" : "에러";
	    					row[8] = rowMap.get("TrackAsisKey1Name");
	    					row[9] = rowMap.get("TrackAsisKey2Name");
	    					row[10] = rowMap.get("RsempName");
	    					row[11] = rowMap.get("RspblPsnCntpCtnt");
	    					row[12] = rowMap.get("GstatSysAdptrBzwkGroupName");
	    					row[13] = rowMap.get("PsvSysAdptrBzwkGroupName");
	    						    					
	    					if (vt.size() < MAX_ROWS) {
	    						vt.add(row);
	    					}
	        }});
			return vt;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getLogList error", e);
			throw e;
		}
	}

	public Vector<String[]> getLogListBranchTest(String owner, String logTime,
			String nodeIndex, String errorType, String commDiv)
			throws Exception {
		String timeOutError = getTimeOutList();
		String bizError = getBizErrorList();
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("logTablename",    CommonUtil.getLogErrTable(CommonUtil.getToday("")));
        paramMap.put("logTablename2",   CommonUtil.getLogTable(Calendar.getInstance(), true));

        paramMap.put("rowno",    String.valueOf(MAX_ROWS));
        paramMap.put("logDate",    CommonUtil.getToday("yyyyMMdd"));
        paramMap.put("logTime",    logTime.replaceAll(":", ""));
        paramMap.put("commDiv",    commDiv);
        paramMap.put("nodeIndex",   nodeIndex);
		if (errorType != null && errorType.trim().length() > 1) {
	        paramMap.put("errorType",    errorType);
	        paramMap.put("timeOutList",  timeOutError);
	        paramMap.put("bizError",  bizError);
		}
		try {
			final Vector<String[]> vt = new Vector<String[]>();
	    	template.queryWithRowHandler("DashboardError.getLogListBranchTest", paramMap,
	    			new RowHandler(){
	    		
	                    public void handleRow(Object valueObject) {

	            			HashMap<String, String> rowMap = (HashMap<String, String>)valueObject;
	            			
	            			String errorTypeTxt = "업무에러";
	            			if("TIMEOUT".equals(errorType)){
	            				errorTypeTxt = "타임아웃";
	            			}else if("CONNECTION".equals(errorType)){
	            				errorTypeTxt = "통신에러";
	            			}

	    					String[] row = new String[14];
	    					row[0] = rowMap.get("GUID");
	    					row[1] = rowMap.get("EAISvcName");
	    					row[2] = rowMap.get("BzwkDsticName");
	    					row[3] = rowMap.get("EAIErrCd");
	    					row[4] = chunkErrorMsg(rowMap.get("EAIErrCtnt"));
	    					row[5] = rowMap.get("EaiSevrInstncName");
	    					row[6] = rowMap.get("MsgDpstYMS");
	    					row[7] = errorTypeTxt;
	    					//row[7] = (timeOutError.indexOf(rowMap.get("EAIErrCd")) > 0) ? "타임아웃" : "에러";
	    					row[8] = rowMap.get("TrackAsisKey1Name");            //추적보조키1명
	    					row[9] = rowMap.get("TrackAsisKey2Name");            //추적보조키2명
	    					row[10] = rowMap.get("RsempName");                   //업무담당명
	    					row[11] = rowMap.get("RspblPsnCntpCtnt");            //담당자연락처내용
	    					row[12] = rowMap.get("GstatSysAdptrBzwkGroupName");  //기동시스템어댑터업무그룹명
	    					row[13] = rowMap.get("PsvSysAdptrBzwkGroupName");    //수동시스템어댑터업무그룹명
	    					if (vt.size() < MAX_ROWS) {
	    						vt.add(row);
	    					}
	        }});
			return vt;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getLogListBranchTest", e);
			throw e;
		}
	}

	private String chunkErrorMsg(String errMsg) {
		errMsg = errMsg.replace("[에러코드:", "");
		errMsg = errMsg.replace("][EAI 서비스코드:", "");
		errMsg = errMsg.substring(errMsg.indexOf("]")+1);
//		return CommonUtil.getByteSub(errMsg.getBytes(), 0, MAX_ERRORMSG_SIZE);
		return errMsg;
	}
	
	public HashMap<String, Object> getDSGTelno(String owner, String adt) throws Exception {
		HashMap<String, String> SSparam = new HashMap<String, String>();
		SSparam.put("schemaId", owner);
		SSparam.put("AdptrBzwkGroupName", adt);
     	return (HashMap<String, Object>)template.queryForObject("DashboardError.getOSIDTelno", SSparam);
    }
	
	
	public int getMobileMonitorLogListCount(String owner,String logTime, String nowTime)
			throws Exception {
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("logTablename",    CommonUtil.getLogErrTable(CommonUtil.getToday("")) );
        paramMap.put("logTablename2",   CommonUtil.getLogTable(Calendar.getInstance(), true));
        paramMap.put("logTime",    logTime);
        paramMap.put("nowTime",    nowTime);
		
        return (Integer)template.queryForObject("DashboardError.getMobileMonitorLogListCount", paramMap);
	}
	
	public Vector<String[]> getMobileMonitorLogList(String owner,String logDate,String errorType,String commDiv)
			throws Exception {
		
		String timeOutError = getTimeOutList();
		String bizError = getBizErrorList();
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("logTablename",    CommonUtil.getLogErrTable(CommonUtil.getToday("")) );
        paramMap.put("logTablename2",   CommonUtil.getLogTable(Calendar.getInstance(), true));
        paramMap.put("rowno",    String.valueOf(MAX_ROWS));
        paramMap.put("logDate",    logDate.substring(0,8));
        paramMap.put("logDate2",    logDate);
        paramMap.put("commDiv",    commDiv);
		if (errorType != null && errorType.trim().length() > 1) {
	        paramMap.put("errorType",    errorType);
	        paramMap.put("timeOutList",  timeOutError);
	        paramMap.put("bizError",  bizError);
		}
		
		try {
			final Vector<String[]> vt = new Vector<String[]>();
	    	template.queryWithRowHandler("DashboardError.getMobileMonitorLogList", paramMap,
	    			new RowHandler(){
	                    public void handleRow(Object valueObject) {

	            			HashMap<String, String> rowMap = (HashMap<String, String>)valueObject;
	    					String[] row = new String[15];
	    					row[0] = rowMap.get("GUID");
	    					row[1] = rowMap.get("EAISVCNAME");
	    					row[2] = rowMap.get("BZWKDSTICNAME");
	    					row[3] = rowMap.get("EAIERRCD");
	    					row[4] = rowMap.get("EAIERRCTNT");
	    					row[5] = rowMap.get("LGINGSYSID");
	    					row[6] = rowMap.get("MSGDPSTYMS");
	    					row[7] = rowMap.get("LOGPRCSSSERNO");
	    					row[8] = rowMap.get("GSTATSYSADPTRBZWKGROUPNAME");            
	    					row[9] = rowMap.get("PSVSYSADPTRBZWKGROUPNAME");           
	    					row[10] = rowMap.get("DOM");                   
	    					row[11] = rowMap.get("EAIBZWKDSTCD");           
	    					row[12] = rowMap.get("EAISVCDESC");  
	    					row[13] = rowMap.get("EAIGROUPCODSTCD");    
	    					
	    					String errorTypeTxt = "업무에러";
	            			if("TIMEOUT".equals(errorType)){
	            				errorTypeTxt = "타임아웃";
	            			}else if("CONNECTION".equals(errorType)){
	            				errorTypeTxt = "통신에러";
	            			}
	            			
	            			row[14] = errorTypeTxt;
	    					
	    					if (vt.size() < MAX_ROWS) {
	    						vt.add(row);
	    					}
	        }});
			return vt;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getMobileMonitorLogList", e);
			throw e;
		}
	}
	
	public Vector<String[]> getMobileMonitorBatchLogList(String owner,String logDate,String errorType) throws Exception {
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("errorType",    errorType);
        paramMap.put("logDate",    logDate.substring(0,8));
        
		try {
			final Vector<String[]> vt = new Vector<String[]>();
	    	template.queryWithRowHandler("DashboardError.getMobileMonitorBatchLogList", paramMap,
	    			new RowHandler(){
	                    public void handleRow(Object valueObject) {

	            			HashMap<String, String> rowMap = (HashMap<String, String>)valueObject;

	    					String[] row = new String[7];
	    					row[0] = rowMap.get("BJOBBZWKDSTCD");
	    					row[1] = rowMap.get("OSIDINSTIDSTCD");
	    					row[2] = rowMap.get("SNDRCVFILENAME");
	    					row[3] = rowMap.get("UAPPLCD");
	    					row[4] = rowMap.get("BJOBPTRNDSTCD");
	    					row[5] = rowMap.get("FILETRSMTSTARTHMS");
	    					row[6] = rowMap.get("EAIOBSTCLOCCURCAUSCTNT");
	    					if (vt.size() < MAX_ROWS) {
	    						vt.add(row);
	    					}
	        }});
			return vt;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getMobileMonitorBatchLogList", e);
			throw e;
		}
	}
	
	
	
	public Vector getDetailInfomation(String owner,String eaiGuid,String startConvCal,String endConvCal, String apCd)
			throws Exception {
		
        final HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("schemaId", owner);
        paramMap.put("logTablename",   CommonUtil.getLogTable(Calendar.getInstance(), true));
        paramMap.put("startDt",    startConvCal);
        paramMap.put("endDt", endConvCal);
        paramMap.put("eaiGuid", eaiGuid.substring(0, 33));
        paramMap.put("apCd", apCd);
        
        try {
			final Vector vt = new Vector();
	    	template.queryWithRowHandler("DashboardError.getDetailInfomation", paramMap,
	    			new RowHandler(){
	                    public void handleRow(Object valueObject) {

	            			HashMap<String, String> rowMap = (HashMap<String, String>)valueObject;
	            			
	            			vt.add(rowMap.get("EAIBZWKDSTCD"));
	            			vt.add(rowMap.get("ERRORCTNT"));
	            			vt.add(rowMap.get("ADPTRBZWKGROUPDESC"));
	            			vt.add(rowMap.get("OSIDINSTIBZWKRSEMPNAME"));
	            			vt.add(rowMap.get("OSIDINSTITELNO"));
	            			
	            			String appCode = rowMap.get("CODE");
	    					// 암호화 된 전문을 복호화 한다.
	    					String msgCtnt = rowMap.get("BZWKDATACTNT");
	    		
	    					String decrypt = "";
	    					if(msgCtnt != null){
	    						try{				
	    				     		String path = monitoringContextImpl.getStringProperty("SCP_PATH","/fsscp/pav/eai/agent0001/scpdb_agent_unix.ini");
	    				     		String key = monitoringContextImpl.getStringProperty("SCP_KEY","SEC");
//	    				     		decrypt = new ScpDbAgent().ScpDecB64( path, key, msgCtnt, "utf-8");
	    				     		decrypt = msgCtnt;
	    						}catch(Exception e){
	    							decrypt = msgCtnt;
	    							logger.info("ScpDbAgent decrypt error ", e);
	    						}
	    						
	    					}
	    					
	    					// 전문에서 기관코드 분리
	    					if("EBE".equalsIgnoreCase(appCode)){ 
	    						vt.add(decrypt.substring(69,72));
	    					}else if("ELB".equalsIgnoreCase(appCode)){
	    						vt.add(decrypt.substring(80,83));
	    					}else{
	    						vt.add("NULL");
	    					}
	    					vt.add(decrypt);
	    					vt.add(rowMap.get("EAISVCNAME"));
	    					vt.add(rowMap.get("EAISVCDESC"));            
	    					vt.add(rowMap.get("MSGDPSTYMS"));           
	    					vt.add(rowMap.get("EAIERRCTNT"));                   
	    					vt.add(rowMap.get("EAISEVRINSTNCNAME"));           
	        }});
			return vt;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error("getDetailInfomation", e);
			throw e;
		}
	}

}
