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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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.google.gson.Gson;

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



/**
 * @author  : yk
 * @version : $Revision: 1.1 $
 */
@Controller
public class DailyStatisticController extends BaseController  {
	
    @Autowired
    @Qualifier("dailyStatisticService")
    private DailyStatisticService service ;
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/dailyStatisticMan.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/dailyStatisticMan.json",params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String, Object> 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("ZSG","TOTALCNT5");
		keyMap.put("ASG","TOTALCNT6");
		keyMap.put("ISG","TOTALCNT7");
		
		
		String onlySum = (String)paramMap.get("onlySum");
		
		
		if("Y".equals(onlySum)){ // 합계만 보기 
			HashMap<String, Object> procCountMap;
			HashMap<String, Object> sumMap = new HashMap<String, Object>();
			HashMap<String, Object> avgMap = new HashMap<String, Object>();
			for(DataSourceType d : DataSourceTypeManager.getOnlineDataSourceTypes() ) {
				if(d.getName() != null){
					DataSourceContextHolder.setDataSourceType(d);
					paramMap.put("schemaId", d.getSchema());
					if(logger.isInfoEnabled()) logger.info("=================DataSourceTypeManager d : "+d);
					
					if("GSG".equals(d.getName())){
						procCountMap = service.selectTotalProcCountByTranType(paramMap);
					}else{
						procCountMap = service.selectTotalProcCount(paramMap);
					}
					
					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")));
						if("GSG".equals(d.getName())){
							sumMap.put("TOTALCNT4", String.valueOf(procCountMap.get("SUMTOTAL2")));
							avgMap.put("TOTALCNT4", String.valueOf(procCountMap.get("AVGTOTAL2")));
						}
					}
					
				}
			}
			
			//일괄 합계 평균 취약점소스 수정 2020.08.24
			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);
			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")));
			}
			
			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 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));
			
			resultList.add(sumMap);
			resultList.add(avgMap);
			
		}else{
			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();  
						String gCount = "0";
						prow = serverTotalMap.get((String)row.get("BASEYMD"));
						if("GSG".equals(d.getName())){
							gCount = row.get("NOMALNOITM2").toString();
						}
						if(prow != null) {
							row = prow;
						}
						row.put(keyMap.get(d.getName()), totalCnt);
						if("GSG".equals(d.getName())){
							row.put("TOTALCNT4", gCount);
						}
						
						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));
			}
		}
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	
	@RequestMapping(value= "/onl/statistics/statisticinfo/dailyStatisticMan.excel",params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		HashMap<String,Object> resultMap = new HashMap<String,Object>();

		String headersStr = (String) paramMap.get("headersStr"); 
		headersStr = headersStr+"ADPTRINSTICODE";
		paramMap.put("headersStr", headersStr);
		
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
    	HashMap<String, Object> list = service.selectListToExcel(paramMap);
    	
    	String jsonStr = gson.toJson(list.get("list"));
    	HashMap<String, String>[] list2 = gson.fromJson(jsonStr, HashMap[].class);
    	
		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String)paramMap.get("headerTitle"), String[].class);
		
		HashMap<String, Object>[] lmerge = null; 
		String merge = (String)paramMap.get("merge");
		if (merge !=null){
			lmerge = gson.fromJson(merge, HashMap[].class);
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", list2);
    	resultMap.put("fileName", (String)paramMap.get("fileName"));
    	resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        return modelAndView;
	}	
}
