package com.eactive.eai.rms.onl.statistics.management.reportdown;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.statistics.statisticinfo.daily.DailyStatisticService;
import com.eactive.eai.rms.onl.statistics.statisticinfo.transaction.TransactionStatisticService;

import edu.emory.mathcs.backport.java.util.Arrays;
import edu.emory.mathcs.backport.java.util.Collections;



/**
 * <pre>
 *     1. 기능 : 업무별 일별 거래현황 통계 화면의 컨트롤러 
 * </pre>
 */
@Controller
public class DownStatisticsManagementController extends BaseController  {
	private static final int TITLE_ROW = 3;				// 타이틀 다음 Data 시작 row
	private static final int MONTHLY_COL_CNT = 10;		// 월별 보고서 컬럼 갯수 (1)
	private static final int DAILY_COL_CNT = 9;			// 일별 보고서 컬럼 갯수 (2)
	private static final int SVRSYS_VAL = 3;		// 서버시스템 보고서 값 위치 (3)
    
	@Autowired
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;
	
    @Autowired
    @Qualifier("dailyStatisticService")
    private DailyStatisticService service ;
    
    @Autowired
    @Qualifier("transactionStatisticService")
    private TransactionStatisticService tpsService ;
    
    	@RequestMapping(value= "/onl/statistics/management/downStatisticsMan.view")
	private String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/onl/statistics/management/downStatisticsMan.file",params = "cmd=UPLOAD_REPORT_DOWN")
	public void listDailyReportDown(HttpServletRequest request, HttpServletResponse response,
												@RequestParam HashMap paramMap) throws Exception {
		String newFileName = "";
		String fileName = "";
		String type = (String)paramMap.get("type");
		String filePath = monitoringContext.getStringProperty(MonitoringContext.MONTHLY_REPORT_DOWN_PATH,"/fsapp/eai/download/");
		
		String dateInfo = (String)paramMap.get("searchStart");
		List<HashMap<String,Object>> list = new ArrayList();
		File f = new File(filePath);
		if(f.listFiles() != null){
			for(File info : f.listFiles()){
				if(info.isFile()){
					if("1".equals(type) && info.getName().startsWith("1_")){
						fileName = info.getName();
						newFileName = "금월 인프라 서버 EAI 데이터 처리 현황 "+ dateInfo.substring(2, 4) +"년 "+dateInfo.substring(4, 6)+"월 EAI.xlsx";
						list = monthReport(paramMap);
					}else if ("2".equals(type) && info.getName().startsWith("2_")){ //일별 거래량 통계
						fileName = info.getName();
						list = dailyReport(paramMap);
						newFileName = "인프라 서버 EAI 일자별 데이터 처리 현황 "+ dateInfo.substring(2, 4) +"년 "+dateInfo.substring(4, 6)+"월 EAI.xlsx";
					}else if ("3".equals(type) && info.getName().startsWith("3_")){
						fileName = info.getName();
						newFileName = "EAI 서버 시스템 - "+ dateInfo.substring(0, 2) +"년"+dateInfo.substring(4, 6)+"월 EAI.xlsx";
						list = svrSystem(paramMap);
					}
				}
			}
			FileInputStream fileIn = null;
			FileOutputStream fileOu = null;
			OutputStream os = null;
			BufferedInputStream bis = null;
			try{
				//양식불러오기
				fileIn = new FileInputStream(new File(filePath+fileName));
				XSSFWorkbook wb = new XSSFWorkbook(fileIn);
				//첫번째 시트
				XSSFSheet sheet = wb.getSheetAt(0);
				if("1".equals(type)){
					for(int i=0; i<list.size(); i++){
						Row row = sheet.getRow(TITLE_ROW+i);
						HashMap map = list.get(i);
						List dataList = new ArrayList();
						dataList.add(dateInfo.substring(0,4)+"."+dateInfo.substring(4, 6));//날짜 (2020.09)
						dataList.add(map.get("BASEYMD"));
						dataList.add(map.get("TOTALCNT"));
						dataList.add(map.get("TOTALCNT1"));
						dataList.add(map.get("TOTALCNT2"));
						dataList.add(map.get("TOTALCNT3"));
						dataList.add(map.get("TOTALCNT4"));
						dataList.add(map.get("TOTALCNT5"));
						dataList.add(map.get("TOTALCNT6"));
						dataList.add(map.get("TOTALCNT7"));
						for(int c=0; c<MONTHLY_COL_CNT; c++){//colum for문
							String val=(String)dataList.get(c);
							if("".equals(val) || val==null || "null".equals(val)){
								val="0";
							}
							if(c>1){
								row.getCell(c).setCellValue(numFormat(val));
							}else{
								row.getCell(c).setCellValue(val);
							}
						}
					}
				}else if("2".equals(type)){
					for(int i=0; i<list.size(); i++){
						Row row = sheet.getRow(TITLE_ROW+i);
						HashMap map = list.get(i);
						List dataList = new ArrayList();
						String baseYMD=(String)map.get("BASEYMD");
						
						dataList.add(baseYMD.substring(0,4)+"-"+baseYMD.substring(4,6)+"-"+baseYMD.substring(6,8));
						dataList.add(map.get("TOTALCNT"));
						dataList.add(map.get("TOTALCNT1"));
						dataList.add(map.get("TOTALCNT2"));
						dataList.add(map.get("TOTALCNT3"));
						dataList.add(map.get("TOTALCNT4"));
						dataList.add(map.get("TOTALCNT5"));
						dataList.add(map.get("TOTALCNT6"));
						dataList.add(map.get("TOTALCNT7"));
						for(int c=0; c<DAILY_COL_CNT; c++){//colum for문
							String val=(String)dataList.get(c);
							if("".equals(val) || val==null || "null".equals(val)){
								val="0";
							}
							if(c==0){
								row.getCell(c).setCellValue(val);
							}else{
								row.getCell(c).setCellValue(numFormat(val));
							}
						}
					}
				}else if ("3".equals(type)){
					HashMap map = list.get(0);
					List dataList = new ArrayList();
					dataList.add(map.get("onlineDate"));
					dataList.add(map.get("onlineTranCnt"));
					dataList.add(map.get("BapDate"));
					dataList.add(map.get("BapTranCnt"));//일괄 송신 _ 데이터는 송수신 합계카운트
					dataList.add("");	//일괄 수신
					dataList.add(map.get("TPS_GSG"));	//tps 공동
					dataList.add(map.get("TPS_NSG"));	//tps 내부
					dataList.add(map.get("TPS_DSG")); 	//tps 대외
					dataList.add(map.get("TPS_TOTAL")); //tps 합계
					dataList.add(""); //cpu사용률
					dataList.add(""); //cpu사용률
					for(int i=0; i<dataList.size(); i++){
						Row row = sheet.getRow(TITLE_ROW+i);
						String val=dataList.get(i).toString();
						if("".equals(val) || val==null || "null".equals(val)){
							val="0";
						}
						row.getCell(SVRSYS_VAL).setCellValue(val);
						row.getCell(0).setCellValue((String)map.get("DATE"));
					}
				}
				fileOu = new FileOutputStream(filePath+newFileName);
				wb.write(fileOu);
				fileOu.flush();
				
				//화면으로 파일전송
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Transfer-Encoding", "binary:");
				response.setHeader("Content-Disposition", "attachment; filename=\""+  new String(newFileName.getBytes(),"8859_1") +"\"");
				
				os = response.getOutputStream();
				bis = new BufferedInputStream(new FileInputStream(filePath+newFileName)); 
				int readCnt = 0;
				byte[] buffer = new byte[2048];
				
				while( (readCnt = bis.read(buffer)) != -1) {
					os.write(buffer, 0, readCnt);
					os.flush();
				}
				
			}catch (Exception e) {
				logger.error("Excel Write Error : "+e);
				throw e;
			}finally {
				File ff = new File(filePath+newFileName);
				if(ff.exists()) ff.delete();
				
				if(fileIn != null) fileIn.close();
				if(fileOu != null) fileOu.close();
				if(bis != null) bis.close();
				if(os != null) os.close();
			}
		}
    }
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/onl/statistics/management/downStatisticsMan.json",params = "cmd=LIST_INIT")
	public ModelAndView listMonthlyReportDown(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String filePath = monitoringContext.getStringProperty(MonitoringContext.MONTHLY_REPORT_DOWN_PATH,"/fsapp/eai/download/");
		if(logger.isInfoEnabled()) logger.info("filePath : " + filePath);
		File f = new File(filePath);
		HashMap fnMap = new HashMap();	//타입별로 파일명 담을 맵
		if(f.listFiles() != null){
			for(File info : f.listFiles()){
				if(info.isFile()){
					if(info.getName().startsWith("1_")){
						fnMap.put("MONTHLY", info.getName());
					}else if(info.getName().startsWith("2_")){
						fnMap.put("DAILY", info.getName());
					}else if(info.getName().startsWith("3_")){
						fnMap.put("SVRSYS", info.getName());
					}
				}
			}
		}
		Map resultMap = new HashMap();
		resultMap.put("fnMap", fnMap);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",fnMap);		
		return modelAndView;    
    }
	
	public List<HashMap<String,Object>> monthReport(HashMap paramMap) throws Exception {
		HashMap bussMap = new HashMap(); 
		bussMap.putAll(paramMap);
		bussMap.put("bussinessDay", "Y");
		String dateInfo = (String)paramMap.get("searchStart");
		String bDayParam = (String)paramMap.get("bussinessDays");
		if(!"".equals(bDayParam) && null!=bDayParam){
			String bussinessDay[] = bDayParam.split(",");
			List holiday = new ArrayList();
			for(int i=0; i<bussinessDay.length; i++){
				String dayStr = bussinessDay[i];
				int day = Integer.parseInt(dayStr);
				if(day<10){
					dayStr="0"+dayStr;
				}
				String holidayStr = dateInfo.substring(0,6)+dayStr;
				holiday.add(holidayStr);
			}
			bussMap.put("holiday", holiday);
		}
		
		//HashMap<String,HashMap> serverTotalMap = new HashMap<String,HashMap>();
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		
		HashMap<String,String> keyMap = new HashMap<String,String>();
		keyMap.put("NSG","TOTALCNT1");
		keyMap.put("DSG","TOTALCNT2");
		keyMap.put("GSG","TOTALCNT3");
		keyMap.put("ASG","TOTALCNT5");
		keyMap.put("ZSG","TOTALCNT6");
		keyMap.put("ISG","TOTALCNT7");
		
		HashMap<String, Object> procCountMap;
		HashMap<String, Object> bProcCountMap;	//영업일 파라미터 추가
		HashMap<String, Object> sumMap = new HashMap<String, Object>();
		HashMap<String, Object> avgMap = new HashMap<String, Object>();
		HashMap<String, Object> bSumMap = new HashMap<String, Object>();
		HashMap<String, Object> bAvgMap = new HashMap<String, Object>();
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			if(d.getName() != null){
				DataSourceContextHolder.setDataSourceType(d);
				paramMap.put("schemaId", d.getSchema());
				bussMap.put("schemaId", d.getSchema());
				if(logger.isInfoEnabled()) logger.info("=================DataSourceTypeManager d : "+d);
				
				if("GSG".equals(d.getName())){
					procCountMap = service.selectTotalProcCountByTranType(paramMap);
					bProcCountMap = service.selectTotalProcCountByTranType(bussMap);
				}else{
					procCountMap = service.selectTotalProcCount(paramMap);
					bProcCountMap = service.selectTotalProcCount(bussMap);
				}
				
				if(procCountMap != null){
					sumMap.put(keyMap.get(d.getName()), String.valueOf(procCountMap.get("SUMTOTAL")));
					avgMap.put(keyMap.get(d.getName()), String.valueOf(procCountMap.get("AVGTOTAL")));
					bSumMap.put(keyMap.get(d.getName()), String.valueOf(bProcCountMap.get("SUMTOTAL")));
					bAvgMap.put(keyMap.get(d.getName()), String.valueOf(bProcCountMap.get("AVGTOTAL")));
					if("GSG".equals(d.getName())){
						sumMap.put("TOTALCNT4", String.valueOf(procCountMap.get("SUMTOTAL2")));
						avgMap.put("TOTALCNT4", String.valueOf(procCountMap.get("AVGTOTAL2")));
						bSumMap.put("TOTALCNT4", String.valueOf(bProcCountMap.get("SUMTOTAL2")));
						bAvgMap.put("TOTALCNT4", String.valueOf(bProcCountMap.get("AVGTOTAL2")));
					}
				}
			}
		}
		
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("ISG");
		DataSourceContextHolder.setDataSourceType(dt);
		String schemaId = "";
		String inst = "";
		
		if(dt != null){
			schemaId =dt.getSchema();
			inst =dt.getName();
		}
		bussMap.put("schemaId",schemaId);
		paramMap.put("schemaId",schemaId);
		
		procCountMap = new HashMap<String, Object>();
		procCountMap = service.selectIsgTotalProcCount(paramMap);
		if(procCountMap != null){
			sumMap.put(keyMap.get(inst), String.valueOf(procCountMap.get("SUMTOTAL")));
			avgMap.put(keyMap.get(inst), String.valueOf(procCountMap.get("AVGTOTAL")));
		}
		bProcCountMap = new HashMap<String, Object>();
		bProcCountMap = service.selectIsgTotalProcCount(bussMap);
		if(procCountMap != null){
			bSumMap.put(keyMap.get(inst), String.valueOf(procCountMap.get("SUMTOTAL")));
			bAvgMap.put(keyMap.get(inst), String.valueOf(procCountMap.get("AVGTOTAL")));
		}
		
		int totalCnt = 0;
		for(Map.Entry<String, Object> entry : sumMap.entrySet()){
			if(entry.getKey().indexOf("TOTALCNT") > -1){
				if("".equals(entry.getValue()) || entry.getValue() == null || "null".equals(entry.getValue())) continue;
				int val = Integer.parseInt(entry.getValue().toString());
				totalCnt += val;
			}
		}
		sumMap.put("BASEYMD", "총합계");
		sumMap.put("TOTALCNT", Integer.toString(totalCnt));
		
		int totalCntB = 0;
		for(Map.Entry<String, Object> entry : bSumMap.entrySet()){
			if(entry.getKey().indexOf("TOTALCNT") > -1){
				if("".equals(entry.getValue()) || entry.getValue() == null || "null".equals(entry.getValue())) continue;
				int val = Integer.parseInt(entry.getValue().toString());
				totalCntB += val;
			}
		}
		bSumMap.put("BASEYMD", "영업일합계");
		bSumMap.put("TOTALCNT", Integer.toString(totalCntB));
		
		int totalCnt2 = 0;
		for(Map.Entry<String, Object> entry : avgMap.entrySet()){
			if(entry.getKey().indexOf("TOTALCNT") > -1){
				if("".equals(entry.getValue()) || entry.getValue() == null || "null".equals(entry.getValue())) continue;
				int val = Integer.parseInt(entry.getValue().toString());
				totalCnt2 += val;
			}
		}
		avgMap.put("BASEYMD", "일평균");
		avgMap.put("TOTALCNT", Integer.toString(totalCnt2));
		
		int totalCntB2 = 0;
		for(Map.Entry<String, Object> entry : bAvgMap.entrySet()){
			if(entry.getKey().indexOf("TOTALCNT") > -1){
				if("".equals(entry.getValue()) || entry.getValue() == null || "null".equals(entry.getValue())) continue;
				int val = Integer.parseInt(entry.getValue().toString());
				totalCntB2 += val;
			}
		}
		bAvgMap.put("BASEYMD", "영업일평균");
		bAvgMap.put("TOTALCNT", Integer.toString(totalCntB2));
		
		resultList.add(sumMap);
		resultList.add(bSumMap);
		resultList.add(avgMap);
		resultList.add(bAvgMap);
		
		return resultList;
	}
	
	public List dailyReport(HashMap paramMap) throws Exception {
		HashMap<String,HashMap> serverTotalMap = new HashMap<String,HashMap>();
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		
		HashMap<String,String> keyMap = new HashMap<String,String>();
		keyMap.put("NSG","TOTALCNT1");
		keyMap.put("DSG","TOTALCNT2");
		keyMap.put("GSG","TOTALCNT3");
		keyMap.put("ASG","TOTALCNT5");
		keyMap.put("ZSG","TOTALCNT6");
		keyMap.put("ISG","TOTALCNT7");
		
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			if(d.getName() != null){
				List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
				DataSourceContextHolder.setDataSourceType(d);
				paramMap.put("schemaId", d.getSchema());
				if(logger.isInfoEnabled()) logger.info("=================DataSourceTypeManager d : "+d);
				
				//공동망 개설 취급 거래구분 
				if("GSG".equals(d.getName())){
					list = service.selectListByTranType(paramMap);
				}else{
					list = service.selectList(paramMap);
				}
				
				HashMap<String, Object> row = null;
				HashMap<String, Object> prow = null;
				
				for(int idx=0; idx<list.size();idx++) {
					row = list.get(idx);
					String totalCnt = row.get("NOMALNOITM").toString();  
					prow = serverTotalMap.get((String)row.get("BASEYMD"));
					
					if(prow != null) {
						row.putAll(prow);
					}
					row.put(keyMap.get(d.getName()), totalCnt);
					
					if("GSG".equals(d.getName())){
						if(row.get("NOMALNOITM2") != null){
							row.put("TOTALCNT4", row.get("NOMALNOITM2").toString());
						}
					}
					
					serverTotalMap.put((String)row.get("BASEYMD"),row);
				}
			}
		}
		
		//일괄전송 거래건수 
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("ISG");
		DataSourceContextHolder.setDataSourceType(dt);
		String schemaId = "";
		String inst = "";
		
		if(dt != null){
			schemaId =dt.getSchema();
			inst =dt.getName();
		}
		
		paramMap.put("schemaId",schemaId);
		List  isgTotalList = service.selectIsgList(paramMap);
		HashMap<String, Object> row = null;
		HashMap<String, Object> prow = null;
		
		for(int idx=0; idx<isgTotalList.size();idx++) {
			row = (HashMap<String, Object>) isgTotalList.get(idx);
			String totalCnt = row.get("NOMALNOITM").toString();  
			prow = serverTotalMap.get((String)row.get("BASEYMD"));
			
			if(prow != null) {
				row = prow;
			}
			row.put(keyMap.get(inst), totalCnt);
			serverTotalMap.put((String)row.get("BASEYMD"),row);
		}
		
		for(String key : serverTotalMap.keySet()){
			HashMap<String, Object> tmp = serverTotalMap.get(key);
			int totalCnt = 0;
			for(Map.Entry<String, Object> entry : tmp.entrySet()){
				if(entry.getKey().indexOf("TOTALCNT") > -1){
					if("".equals(entry.getValue()) || entry.getValue() == null || "null".equals(entry.getValue())) continue;
					int val = Integer.parseInt(entry.getValue().toString());
					totalCnt += val;
				}
			}
			tmp.put("TOTALCNT", Integer.toString(totalCnt));
		}
		Object[] keys = serverTotalMap.keySet().toArray();
		Arrays.sort(keys);
		String key = "";
		for(int p=0; p<keys.length;p++) {
			key = (String)keys[p];
			resultList.add(serverTotalMap.get(key));
		}
		return resultList;
	}
	public List<HashMap<String,Object>> svrSystem(HashMap paramMap) throws Exception {
		HashMap<String,HashMap> serverTotalMap = new HashMap<String,HashMap>();
		HashMap<String,HashMap> serverTotalMapTPS = new HashMap<String,HashMap>();
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		HashMap returnMap = new HashMap();
		HashMap<String,String> keyMap = new HashMap<String,String>();
		keyMap.put("NSG","TOTALCNT1");
		keyMap.put("DSG","TOTALCNT2");
		keyMap.put("GSG","TOTALCNT3");
		keyMap.put("ASG","TOTALCNT5");
		keyMap.put("ZSG","TOTALCNT6");
		
		//String preMonth = "";  //전월
		String dateInfo = (String)paramMap.get("searchStart");  //기준년월
    	returnMap.put("DATE", dateInfo.substring(0,4)+"."+dateInfo.substring(4,6));
    	paramMap.put("preMonth", dateInfo.substring(0,6));
    	paramMap.put("curMonth", dateInfo.substring(0,6));

    	int tpsTotal = 0;
    	
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			if(d.getName() != null){
				List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
				List<HashMap<String, Object>> listTPSMax = new ArrayList<HashMap<String, Object>>();
				List<HashMap<String, Object>> listTPS = new ArrayList<HashMap<String, Object>>();
				DataSourceContextHolder.setDataSourceType(d);
				paramMap.put("schemaId", d.getSchema());
				if(logger.isInfoEnabled()) logger.info("=================DataSourceTypeManager d : "+d);
				
				//공동망 개설 취급 거래구분 
				if("GSG".equals(d.getName())){
					list = service.selectListByTranType(paramMap);
				}else{
					list = service.selectList(paramMap);
				}
				
				HashMap<String, Object> row = null;
				HashMap<String, Object> prow = null;

				for(int idx=0; idx<list.size();idx++) {
					row = list.get(idx);
					String totalCnt = row.get("NOMALNOITM").toString();  
					prow = serverTotalMap.get((String)row.get("BASEYMD"));
					
					if(prow != null) {
						row.putAll(prow);
					}
					row.put(keyMap.get(d.getName()), totalCnt);
					
					if("GSG".equals(d.getName())){
						if(row.get("NOMALNOITM2") != null){
							row.put("TOTALCNT4", row.get("NOMALNOITM2").toString());
						}
					}
					serverTotalMap.put((String)row.get("BASEYMD"),row);
				}
				
				row = new HashMap();
				prow= new HashMap();
				
				if("NSG".equals(d.getName()) || "DSG".equals(d.getName()) || "GSG".equals(d.getName())){
					listTPSMax = tpsService.selectTpsByService(paramMap);
					listTPS = tpsService.selectTPSAll(paramMap);
					
					if(! listTPSMax.isEmpty()){
						//TPS max 값
						HashMap<String, Object> tpsRow = (HashMap<String, Object>) listTPSMax.get(0);
						String maxDate = (String)tpsRow.get("BASEYMD");
						int procVal = Integer.parseInt(tpsRow.get("PRCSSNOITM").toString());
						tpsTotal = tpsTotal + procVal;
						maxDate = "(" + maxDate.substring(0, 4) +"."+ maxDate.substring(4,6) +"."+ maxDate.substring(6, 8) + ")";
						returnMap.put("TPS_"+d.getName(),  numFormat(procVal)+ maxDate);
						
						if(!listTPS.isEmpty()){
							//TPS 합계
							for(int idx=0; idx<listTPS.size();idx++) {
								row = listTPS.get(idx);
								String totalCnt = row.get("TPSNOITM").toString();  
								prow = serverTotalMap.get((String)row.get("BASEYMD"));
								
								if(prow != null) {
									row.putAll(prow);
								}
								row.put(keyMap.get(d.getName()), numFormat(totalCnt));
								serverTotalMapTPS.put((String)row.get("BASEYMD"),row);
							}
						}
					}else{
						returnMap.put("TPS_"+d.getName(),  " - ");
					}
				}
			}
		}
		returnMap.put("TPS_TOTAL", Integer.toString(tpsTotal));
		
		HashMap mm = new HashMap();
		
		if(!serverTotalMap.isEmpty()){
			for(String key : serverTotalMap.keySet()){
				HashMap<String, Object> tmp = serverTotalMap.get(key);
				int totalCnt = 0;
				for(Map.Entry<String, Object> entry : tmp.entrySet()){
					if(entry.getKey().indexOf("TOTALCNT") > -1){
						int val = Integer.parseInt(entry.getValue().toString());
						totalCnt += val;
					}
				}
				tmp.put("TOTALCNT", Integer.toString(totalCnt));
				mm.put(key, totalCnt);
			}
		}
		
		Collection c = mm.values();
		Object max = null;
		
		if(c.size() > 0){
			max = Collections.max(c);
			for(Object obj : mm.keySet()){
				if(mm.get(obj).equals(max)){
					String s = (String)obj;
					if(s.length()==8){
						s=s.substring(0,4)+"."+s.substring(4,6)+"."+s.substring(6,8);
					}
					returnMap.put("onlineDate"	 ,  s);
					returnMap.put("onlineTranCnt",  numFormat(max.toString()));
				}
			}
		}else{
			returnMap.put("onlineDate"	 ,  "-");
			returnMap.put("onlineTranCnt",  "0");
		}
		
		mm = new HashMap();
		
		if(!serverTotalMap.isEmpty()){
			for(String key : serverTotalMap.keySet()){
				HashMap<String, Object> tmp = serverTotalMap.get(key);
				int totalCnt = 0;
				for(Map.Entry<String, Object> entry : tmp.entrySet()){
					if(entry.getKey().indexOf("TOTALCNT") > -1){
						int val = Integer.parseInt(entry.getValue().toString());
						totalCnt += val;
					}
				}
				tmp.put("TOTALCNT", Integer.toString(totalCnt));
				mm.put(key, totalCnt);
			}
		}
		
		
		//일괄전송 거래건수 
		DataSourceType dt = DataSourceTypeManager.getDataSourceType("ISG");
		DataSourceContextHolder.setDataSourceType(dt);
		String schemaId = "";
		String inst = "";
		
		if(dt != null){
			schemaId =dt.getSchema();
			inst =dt.getName();
		}
		
		paramMap.put("schemaId",schemaId);
		List  isgTotalList = service.selectIsgList(paramMap);
		HashMap<String, Object> row = null;
		//HashMap<String, Object> prow = null;
		
		mm = new HashMap();
		if(isgTotalList.size() > 0){
			for(int idx=0; idx<isgTotalList.size();idx++) {
				row = (HashMap<String, Object>) isgTotalList.get(idx);
				mm.put(row.get("BASEYMD"), row.get("NOMALNOITM").toString());
			}
		}
		
		c = mm.values();
		
		if(c.size() > 0){
			max = Collections.max(c);
			for(Object obj : mm.keySet()){
				if(mm.get(obj).equals(max)){
					String s = (String)obj;
					if(s.length()==8){
						s=s.substring(0,4)+"."+s.substring(4,6)+"."+s.substring(6,8);
					}
					returnMap.put("BapDate"	 ,  s);
					returnMap.put("BapTranCnt",  numFormat(max.toString()));
				}
			}
		}else{
			returnMap.put("BapDate"	 ,  "-");
			returnMap.put("BapTranCnt",  "0");
		}
		
		resultList.add(returnMap);
		return resultList;
	}
	public static String numFormat(String num){
		DecimalFormat df = new DecimalFormat("#,###");
		return df.format(Integer.parseInt(num));
	}
	public static String numFormat(int num){
		DecimalFormat df = new DecimalFormat("#,###");
		return df.format(num);
	}
}
