package com.eactive.eai.rms.onl.manage.serviceinfo.jmsqueuemonitor;

import java.math.BigDecimal;
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.apache.log4j.Logger;
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.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.eactive.eai.rms.onl.common.service.JmsQueueMonitorService;
import com.google.gson.Gson;

@Controller
public class JmsQueueMonitorManController extends OnlBaseAnnotationController {

    private static final Logger logger = Logger.getLogger(JmsQueueMonitorManController.class);
    private static final String prefix = "jms/";
    /**
     * JMS Queue 관리 서비스
     */
    @Autowired
    @Qualifier("jmsQueueMonitorManService")
    private JmsQueueMonitorManService service;
    
    @Autowired
    @Qualifier("jmsQueueMonitorService")
    private JmsQueueMonitorService  jmsMonitor;
    
    
    @RequestMapping(value= "/onl/admin/service/jmsQueueMonitorMan.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;
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/onl/admin/service/jmsQueueMonitorMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, JsonPageVo pageVo,
			@RequestParam HashMap<String, Object> param) throws Exception {
		/*
		 * 국민 EAIDS01_i01 우체국 fepSvr11
		 */
		if (param.get("searchBox") != null) {
			param.put("searchBox", "Svr" + param.get("searchBox"));
		}
		if (param.get("searchInst") != null) {
			param.put("searchInst", param.get("searchInst"));
		}
		HashMap mapOrg = service.selectList(pageVo.getStartNum(), pageVo.getEndNum(), param);
		HashMap map = new HashMap<>();
		List<HashMap<String, Object>> list = (List) mapOrg.get("list");
		List<HashMap<String, Object>> listNew = new ArrayList<>();
		for (HashMap<String, Object> m : list) {
			String queueName = (String) m.get("NONSYNCZTRANQUENAME");
			String instncname = (String) m.get("EAISEVRINSTNCNAME");
			if (param.get("searchDstic").equals("1")
					&& (m.get("SENDERRQUEUECOUNT") == null || m.get("RECEIVEERRQUEUECOUNT") == null)) {
				if (m.get("SENDQUEUECOUNT") != null
						&& 0 == new BigDecimal(m.get("SENDQUEUECOUNT").toString()).intValue()) {
					int count = getCount(queueName, instncname);
					if (count > 0) {
						m.put("SENDQUEUECOUNT", count);
					}
				} else if (m.get("RECEIVEQUEUECOUNT") != null
						&& 0 == new BigDecimal(m.get("RECEIVEQUEUECOUNT").toString()).intValue()) {
					int count = getCount(queueName, instncname);
					if (count > 0) {
						m.put("RECEIVEQUEUECOUNT", count);
					}
				} else if (m.get("SENDERRORQUEUECOUNT") != null
						&& 0 == new BigDecimal(m.get("SENDERRORQUEUECOUNT").toString()).intValue()) {
					int count = getCount(queueName, instncname);
					if (count > 0) {
						m.put("SENDERRORQUEUECOUNT", count);
					}

				} else if (m.get("RECEIVEERRORCOUNT") != null
						&& 0 == new BigDecimal(m.get("RECEIVEERRORCOUNT").toString()).intValue()) {
					int count = getCount(queueName, instncname);
					if (count > 0) {
						m.put("RECEIVEERRORCOUNT", count);
					}
				}
				listNew.add(m);
			} else {
				if (m.get("SENDERRQUEUECOUNT") != null || m.get("RECEIVEERRQUEUECOUNT") != null) {
					if (0 == new BigDecimal(m.get("SENDERRORQUEUECOUNT").toString()).intValue()) {
						int count = getCount(queueName, instncname);
						if (count > 0) {
							m.put("SENDERRORQUEUECOUNT", count);
						}
					} else if (0 == new BigDecimal(m.get("RECEIVEERRORCOUNT").toString()).intValue()) {
						int count = getCount(queueName, instncname);
						if (count > 0) {
							m.put("RECEIVEERRORCOUNT", count);
						}
					}
					listNew.add(m);
				}
			}
		}
		map.put("list", listNew);
		pageVo.setTotalCount((Integer) mapOrg.get("totalCount"));

		Map resultMap = new HashMap();
		resultMap.put("total", pageVo.getTotal()); // 전체 페이지수
		resultMap.put("page", pageVo.getPage()); // 현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());// 전체 레코드건수
		resultMap.put("rows", listNew);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	private int getCount(String queueName, String instncname) {
		if (queueName != null && queueName.trim().length() > 0) {
			if (queueName.startsWith(prefix)) {
				queueName = queueName.substring(prefix.length());
			}
			return getMessageCurrent(jmsMonitor.getArrayByInstQueueName(queueName, instncname));
		}
		return -1;
	}
	
	@RequestMapping(value= "/onl/admin/service/jmsQueueMonitorMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
        List boxCnt = new ArrayList<>();
        List instCnt = new ArrayList<>();
        for(int b = 1; b<=service.selectBoxCount(); b++){
//        	boxCnt.add("{CODE : "+b+" , NAME : "+b+"}");
        	String data = String.valueOf(b);
        	boxCnt.add(new HashMap(){{put("CODE",data);put("NAME",data);}});
        }
        for(int i = 1; i<=service.selectInstCount(); i++){
//        	instCnt.add("{CODE : "+i+" , NAME : "+i+"}");
        	String data = String.valueOf(i);
        	instCnt.add(new HashMap(){{put("CODE",data);put("NAME",data);}});
        }
		Map resultMap = new HashMap();
		resultMap.put("boxCnt", boxCnt);
		resultMap.put("instCnt", instCnt);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
    }
	@RequestMapping(value= "/onl/admin/service/jmsQueueMonitorMan.json",params = "cmd=DETAIL")
	private ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response,String nonSynczTranQueName , String sevrInstncName ) throws Exception {
		
		HashMap map = service.selectDetail(nonSynczTranQueName ,sevrInstncName);
		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
		
		return modelAndView;
	}
	
	
	  /**
	  * Message Current(배열의 6번째)값 을 정수로 변환해서 리턴한다.
	  * @param infos
	  * @return
	  */
	 private int getMessageCurrent( String [] infos ) {
	     int ret = 0 ;
	     try {
	         if( infos != null && infos.length > 5 ) {
	             ret = CommonUtil.getInt(infos[5]);
	         }
	     } catch ( Exception e ) {
	         //e.printStackTrace();
	    	 logger.error("Message Current error",e);
	     }
	     return ret ;
	 }
	@RequestMapping(value= "/onl/admin/service/jmsQueueMonitorMan.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>();
		if(paramMap.get("searchBox")!=null){
			paramMap.put("searchBox","Svr"+paramMap.get("searchBox"));
		}
		if(paramMap.get("searchInst")!=null){
			paramMap.put("searchInst",paramMap.get("searchInst"));
		}
		String headersStr = (String) paramMap.get("headersStr"); 
		headersStr = headersStr.substring(0, headersStr.length()-1);
		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;
	}	
}

//
///**
// *  ITSM 임계치 관리 컨트롤러
// */
//@Controller
//@RequestMapping("/admin/jms/jmsQueueMonitorMan.do")
//public class JmsQueueMonitorManController {
//
//    private static final Logger logger = Logger.getLogger(JmsQueueMonitorManController.class);
//    private static final String prefix = "jms/";
//
//    /**
//     * JMS Queue 관리 서비스
//     */
//    @Autowired
//    @Qualifier("jmsQueueMonitorManService")
//    private JmsQueueMonitorManService serviceBean;
//    
////    @Autowired
////    @Qualifier("eaiEngineJmsStatusService")
////    private EaiEngineJmsStatusService jmxBean;
//
//    @Autowired
//    @Qualifier("jmsQueueMonitorService")
//    private JmsQueueMonitorService  jmsMonitor;
//    
//    /**
//     * JMS Queue 관리 모델
//     * @param request
//     * @param cmd
//     * @return
//     * @throws Exception
//     */
//    @ModelAttribute("JmsQueueMonitorVo")
//    public Object setJmsQueueVo(HttpServletRequest request, String cmd)
//            throws Exception {
//        JmsQueueMonitorVo vo = new JmsQueueMonitorVo();
//        if ("LIST".equals(cmd)) {
//            vo.setBzwkDstcd(ServletRequestUtils.getStringParameter(request,
//                "searchText", ""));
//        } else if( "DETAIL".equals( cmd)     ) {
//            
//        }
//        return vo;
//    }
//
//    /**
//     * JMS Queue 관리 리스트 조회
//     * @param vo
//     * @param modelMap
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping(params = "cmd=LIST")
//    public View list(@ModelAttribute("JmsQueueMonitorVo") JmsQueueMonitorVo vo,
//            ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//
//        UserAccessLogger.log(request, "JMS Queue Monitor", "L", "cmd=LIST");
//
//        List<JmsQueueMonitorVo> list = null;
//        try {
//        	String bzwkDstcd = ServletRequestUtils.getStringParameter(request, "searchText", "");
////        	if( !"".equals(bzwkDstcd) ) {
////        		bzwkDstcd = StringUtils.rightPad(bzwkDstcd, 4," ");
////        	}
//        	vo.setBzwkDstcd(bzwkDstcd);
//
//        	if (vo.getQueBzwkCtnt() != null && vo.getQueBzwkCtnt().length() > 0) {
//            	vo.setQueBzwkCtnt("%" + vo.getQueBzwkCtnt() + "%");
//            }
//            else {
//            	vo.setQueBzwkCtnt("");
//            }
//        	
//        	list = serviceBean.findPageList(vo);
//            
//        	for(int v=0; v<list.size(); v++) {
//        		JmsQueueMonitorVo resVo = (JmsQueueMonitorVo)list.get(v);
//        		String sendQueueName         = resVo.getSendQueueName();
//        		String receiveQueueName      = resVo.getReceiveQueueName();
//        		String sendErrorQueueName    = resVo.getSendErrorQueueName();
//        		String receiveErrorQueueName = resVo.getReceiveErrorQueueName();
//        		if(sendQueueName !=null && sendQueueName.trim().length() > 0) {
//        			if (sendQueueName.startsWith(prefix)){
//        				sendQueueName = sendQueueName.substring(prefix.length());
//        			}
//                    int count = getMessageCurrent( jmsMonitor.getArrayByQueueName(sendQueueName) );
//        			resVo.setSendCount(count);        			
//        		}
//    	        
//        		if(receiveQueueName !=null && receiveQueueName.trim().length() > 0) {
//        			if (receiveQueueName.startsWith(prefix)){
//        				receiveQueueName = receiveQueueName.substring(prefix.length());
//        			}
//                    int count = getMessageCurrent( jmsMonitor.getArrayByQueueName(receiveQueueName) );
//        			resVo.setReceiveCount(count);        			
//        		}
//        		
//        		if(sendErrorQueueName !=null && sendErrorQueueName.trim().length() > 0) {
//        			if (sendErrorQueueName.startsWith(prefix)){
//        				sendErrorQueueName = sendErrorQueueName.substring(prefix.length());
//        			}
//                    int count = getMessageCurrent( jmsMonitor.getArrayByQueueName(sendErrorQueueName) );
//        			resVo.setSendErrorCount(count);        			
//        		}
//        		
//        		if(receiveErrorQueueName !=null && receiveErrorQueueName.trim().length() > 0) {
//        			if (receiveErrorQueueName.startsWith(prefix)){
//        				receiveErrorQueueName = receiveErrorQueueName.substring(prefix.length());
//        			}
//                    int count = getMessageCurrent( jmsMonitor.getArrayByQueueName(receiveErrorQueueName) );
//        			resVo.setReceiveErrorCount(count);        			
//        		}
//
//        		list.set(v, resVo);
//        	}
//	        
//        	modelMap.addAttribute("list", list);
//            modelMap.addAttribute("JmsQueueMonitorVo", vo);
//            return new JmsQueueMonitorView();
//        } catch (Exception e) {
//            logger.error( e );
//            e.printStackTrace();
//            ((HttpGauceResponse) response).addException(e);
//        }
//        return new EmptyGauceView();
//    }
//        
//    /**
//     * JMS Queue 관리 상세 조회
//     * @param vo
//     * @param modelMap
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping(params = "cmd=DETAIL")
//    public View detail(@ModelAttribute("JmsQueueMonitorVo") JmsQueueMonitorVo vo,
//            ModelMap modelMap, HttpServletRequest request,
//            HttpServletResponse response) {
//        UserAccessLogger.log(request, "JMS Queue Monitor", "V", "cmd=DETAIL");
//        
//        try {
//            JmsQueueMonitorVo detailVo = serviceBean.findDetail( vo );
//
//            if( logger.isDebugEnabled() ) {
//                logger.debug("JMS Queue Detail : returned=" + detailVo );
//            }
//            
//            modelMap.addAttribute("detail", detailVo);
//            
//            return new JmsQueueMonitorDetailView();
//        } catch ( Exception e ) {
//            logger.error(e);
//            ((HttpGauceResponse) response).addException(e);
//        }
//        
//        return new EmptyGauceView();        
//        
//    }
//
//    /**
//     * Message Current(배열의 6번째)값 을 정수로 변환해서 리턴한다.
//     * @param infos
//     * @return
//     */
//    private int getMessageCurrent( String [] infos ) {
//        int ret = 0 ;
//        try {
//            if( infos != null && infos.length > 5 ) {
//                ret = CommonUtil.getInt(infos[5]);
//            }
//        } catch ( Exception e ) {
//            e.printStackTrace();
//        }
//        return ret ;
//    }
//}
