package com.eactive.eai.rms.onl.statistics.statisticinfo.transaction;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.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.common.vo.JsonPageVo;
import com.eactive.eai.rms.onl.dashboard.service.Dashboard2RepositoryService;


/**
 * @author  : yk
 * @version : $Revision: 1.1 $
 */
@Controller
public class TransactionStatisticController extends BaseController  {
	
    @Autowired
    @Qualifier("transactionStatisticService")
    private TransactionStatisticService service ;
    
    @Autowired
    @Qualifier("dashboard2RepositoryService")
    private Dashboard2RepositoryService dashboard2Repository;
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/transactionStatisticMan.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;
	}      
    

	@RequestMapping(value= "/onl/statistics/statisticinfo/transactionStatisticMan.json",params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String, Object> paramMap ) throws Exception {
		
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		//HashMap<String, Object> onlineProcMap = new HashMap<String,Object>();  //온라인 처리건수
		HashMap<String, Object> serverProcMap = new HashMap<String,Object>();  //서버별 처리건수
		
		String curMonth = (String)paramMap.get("searchDate");  //기준년월
		String preMonth = "";  //전월
		
		SimpleDateFormat dateF = new SimpleDateFormat("YYYYMM"); 
    	Calendar cal = Calendar.getInstance();
    	int year = Integer.parseInt(curMonth.substring(0,4));
    	int month = Integer.parseInt(curMonth.substring(4,6));
    	cal.set(year,month-1,0);
    	cal.add(month,-1);
    	preMonth = dateF.format(cal.getTime()).substring(0,4)+dateF.format(cal.getTime()).substring(4,6);
    	
    	paramMap.put("preMonth", preMonth);
    	paramMap.put("curMonth", curMonth);
    	
    	//온라인 날짜별 처리건수
//    	for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
//			if(d.getName() != null){
//				List<HashMap<String, Object>> peakList = new ArrayList<HashMap<String, Object>>();
//				DataSourceContextHolder.setDataSourceType(d);
//				paramMap.put("schemaId", d.getSchema());
//				if(logger.isInfoEnabled()) logger.info("=================DataSourceTypeManager d : "+d);
//				
//				peakList = service.selectPeakByService(paramMap);
//				
//				HashMap<String, Object> row = null;
//				HashMap<String, Object> prow = new HashMap<String, Object>();
//				
//				for(int idx=0; idx<peakList.size();idx++) {
//					row = (HashMap<String, Object>) peakList.get(idx);
//					prow.put((String)row.get("BASEYMD"), row.get("PRCSSNOITM").toString());
//				}
//				onlineProcMap.put(d.getName(), prow);
//			}
//    	}
    	
    	//서비스별 처리건수(TPS)
    	int preTotal = 0;
    	int curTotal = 0;
		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);
				
				list = service.selectTpsByService(paramMap);
				
				String fieldNm = "";
				
				HashMap<String, Object> row = null;
				HashMap<String, Object> prow = null;
				
				for(int idx=0; idx<list.size();idx++) {
					row = (HashMap<String, Object>) list.get(idx);
					
					String preProcMonth = (String)row.get("BASEYMD");
					
					if(preProcMonth.startsWith(preMonth)){ //이전달 데이터
						fieldNm = "PREMM";
					}else{
						fieldNm = "CURMM";
					}
					
					int procVal = Integer.parseInt(row.get("PRCSSNOITM").toString());
					prow = (HashMap<String, Object>) serverProcMap.get(d.getName());
					
					if(prow != null) {
						row = prow;
					}
					
					preProcMonth = " (" + preProcMonth.substring(0, 4) +"."+ preProcMonth.substring(4,6) +"."+ preProcMonth.substring(6, 8) + ")";
					
					if("PREMM".equals(fieldNm)){
						preTotal += procVal;
					}else{
						curTotal += procVal;
					}
					
					row.put("GUBUN", "최대 처리건수");
					row.put("SERVICE", d.getText());
					row.put(fieldNm,  Integer.toString(procVal)+ preProcMonth);
					
					serverProcMap.put(d.getName(),row);
				}
			}
		}
		
		for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
			DataSourceContextHolder.setDataSourceType(d);
			HashMap<String, Object> tmp = (HashMap<String, Object>) serverProcMap.get(d.getName());
			String preVal = null;
			String curVal = null;
			
			int curProcCnt = 0;
			int preProcCnt = 0;
			
			if(tmp != null){
				if(tmp.get("CURMM") != null){
					curVal = tmp.get("CURMM").toString();
					
					int idx2 = curVal.indexOf("(");
					curVal = curVal.substring(0,idx2).trim();
					curProcCnt = Integer.parseInt(curVal);
				}else if(tmp.get("PREMM") != null){
					preVal = tmp.get("PREMM").toString();
					
					int idx = preVal.indexOf("(");
					preVal = preVal.substring(0,idx).trim();
					preProcCnt = Integer.parseInt(preVal);
				}
				
				tmp.put("GRADIENT", Integer.toString(curProcCnt - preProcCnt));
			}else{
				tmp = new HashMap<String, Object>();
				tmp.put("SERVICE", d.getText());
			}
			
			//역대최고치 TPS 
			String val = dashboard2Repository.getPeakTps(d.getName());
			if(val != null){
				String [] data = val.split(",");
				if(data != null){
					if( data.length > 3) {
						String tpsVal =  data[3] + "(" +data[1]+ ") " ;
						tmp.put("MAXTPS", tpsVal);
					}
				}else{
					tmp.put("MAXTPS", "-");
				}
			}else{
				tmp.put("MAXTPS", "-");
			}
			
			resultList.add(tmp);
			
		}	
		
		serverProcMap.put("GUBUN", "최대 처리건수");
		serverProcMap.put("SERVICE", "합계");
		serverProcMap.put("PREMM", Integer.toString(preTotal));
		serverProcMap.put("CURMM", Integer.toString(curTotal));
		serverProcMap.put("GRADIENT", Integer.toString(curTotal - preTotal));
		resultList.add(serverProcMap);
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	
}
