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


import java.util.HashMap;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;

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.statistics.statisticinfo.osidinstistatistic.OsidInstiStatisticService;

public class OsidInstiStatisticJob implements Job{
    /**
    * Logger for this class
    */
	
    private static final Logger logger = Logger.getLogger(OsidInstiStatisticJob.class);
    
    
    @Autowired
    @Qualifier("osidInstiStatisticService")
    private OsidInstiStatisticService service ;
    
    
 // 매일 04:30
    @Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
    	
    	if(logger.isInfoEnabled()) logger.info("START OsidInstiStatisticJob");

   		ApplicationContext appContext = null;
   		try {
   			appContext = (ApplicationContext)context.getScheduler().getContext().get("applicationContext");
   		} catch (SchedulerException e) {
   			logger.error("applicationContext get module error",e);
   			return ;
   		}  
   		service = (OsidInstiStatisticService)appContext.getBean("osidInstiStatisticService");	
		
   		try {
   			if(logger.isInfoEnabled()) logger.info("대외기관/업무 업데이트... ");

			String schemaId = "";
	    	DataSourceType dt = DataSourceTypeManager.getDataSourceType("DSG");
			DataSourceContextHolder.setDataSourceType(dt);
			if(dt != null){
				schemaId =dt.getSchema();
			}
			List<HashMap<String, Object>> MO01CompanyBlackList = null;
			List<HashMap<String, Object>> MO02ApcodeBlackList = null;
			
			HashMap<String, Object> outParamMap = new HashMap<String, Object>();
		
			outParamMap.put("sqlValue","X");
			outParamMap.put("schemaId", schemaId);
			
			//블랙리스트를 뽑아내서 그 리스트를 MAP에 넣는 작업
			MO01CompanyBlackList = service.selectCompanyList(outParamMap);
			MO02ApcodeBlackList = service.selectApcodeList(outParamMap);
			
			HashMap<String,String> CompanyBlackListMap = new HashMap<String,String>();
			for ( HashMap<String, Object> tmpVo : MO01CompanyBlackList ) {
				CompanyBlackListMap.put((String) tmpVo.get("INSTINAME"), (String) tmpVo.get("INSTINAME"));
			}

			HashMap<String,String> ApCodeBlackListMap = new HashMap<String,String>();
			for ( HashMap<String, Object> tmpVo : MO02ApcodeBlackList ) {
				ApCodeBlackListMap.put(tmpVo.get("APCODE").toString().trim(), (String) tmpVo.get("APCODE"));
			}
			
			// 내부, 대외, 공동, DMZ ,오픈  아답터 정보를 가져와서, 기존 정보와 비교 후 신규 업무에 있어서 insert 하는 로직
			for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
				if(d.getName() != null){
					HashMap<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("schemaId", schemaId);
					
					String value =  d.getName();
					value = value.substring(0,1);
					
					List<HashMap<String, Object>> SelectAD01CompanyList = null;
					List<HashMap<String, Object>> SelectAD01APCodeList = null;
					List<HashMap<String, Object>> MO01CompanyList = null;
					List<HashMap<String, Object>> MO02ApcodeList = null;
		
					SelectAD01CompanyList = service.selectCronCompanyList(paramMap);
					SelectAD01APCodeList = service.selectCronApCodeList(paramMap);
					
					//대외기준 데이터소스 설정
					HashMap<String, Object> black_ParamMap = new HashMap<String, Object>();
					DataSourceType service_fixed = DataSourceTypeManager.getDataSourceType("DSG");
					String black_schemaId = "";
					if(service_fixed != null){
						black_schemaId = service_fixed.getSchema();
					}
					black_ParamMap.put("schemaId", black_schemaId);
					black_ParamMap.put("sqlValue", value);
					MO01CompanyList = service.selectCompanyList(black_ParamMap);
					MO02ApcodeList = service.selectApcodeList(black_ParamMap);
				
					// MO01 기존 자원을 읽어서 MAP에 넣기
					HashMap<String,String> CompanyListMap = new HashMap<String,String>();
					for ( HashMap tmpVo : MO01CompanyList ) {
						CompanyListMap.put((String) tmpVo.get("INSTINAME"), (String) tmpVo.get("INSTINAME"));
					}
	
					HashMap<String,String> ApCodeListMap = new HashMap<String,String>();
					for ( HashMap tmpVo : MO02ApcodeList ) {
						ApCodeListMap.put(tmpVo.get("APCODE").toString().trim(), (String) tmpVo.get("APCODE"));
					}
					
					//대외로 데이터소스 변경
			  		DataSourceContextHolder.setDataSourceType(service_fixed);
					
					for( HashMap vo : SelectAD01CompanyList ) {
						if (CompanyListMap.containsKey(vo.get("INSTINAME"))){
							//System.out.println("기등록 기관 :"+vo.get("INSTINAME"));
						}else if (CompanyBlackListMap.containsKey(vo.get("INSTINAME"))){
							//System.out.println("블랙리스트 등록 기관 :"+vo.get("INSTINAME"));
						}else {	
							HashMap map = new HashMap();
							map.put("instiName" , vo.get("INSTINAME"));
							map.put("sqlValue" , value);
							map.put("schemaId", black_schemaId);
							map.put("baseYmd",CommonUtil.getToday("yyyyMMdd"));
							if(logger.isInfoEnabled()) logger.info("신규 추가 기관 insert :"+map.toString());
							try{
								service.insertCompanyList(map);
							}catch(Exception e){
								logger.warn("신규 추가 기관 insert error " +" ,서버구분 : " + value +  " ["+vo.get("INSTINAME")+"]", e);
							}	
						} 
					}			
		
					for( HashMap vo : SelectAD01APCodeList ) {
						//System.out.println("AP 코드 VO ===>" + vo.get("APCODE").toString());
						if (ApCodeListMap.containsKey(vo.get("APCODE").toString().trim())){
							//System.out.println("기등록 AP코드 :"+ vo.get("APCODE")+" : "+vo.get("APCODENAME"));
						}else if (ApCodeBlackListMap.containsKey(vo.get("APCODE").toString().trim())){
							//System.out.println("블랙리스트 등록 AP코드 :"+vo.get("APCODE")+" : "+vo.get("APCODENAME"));
						}else {	
							if (vo.get("APCODENAME")== null){
								vo.put("APCODENAME","");
							}
							HashMap map = new HashMap(); 
							map.put("sqlValue" , value);
							map.put("apCodeName", vo.get("APCODENAME"));
							map.put("apCode", vo.get("APCODE"));
							map.put("schemaId", black_schemaId);
							map.put("baseYmd", CommonUtil.getToday("yyyyMMdd"));
							if(logger.isInfoEnabled()) logger.info("신규 추가 코드 insert :"+map.toString());
							try{
								service.insertApCodeList(map);
							}catch(Exception e){
								logger.warn("신규 추가 코드 insert error " + " ,서버구분 : " + value +  "["+vo.get("APCODE")+"]", e);
							}	
						} 
					}
				}
			}

		} catch (Exception e) {
			logger.error( e );
		}
    }
			
}
