package com.eactive.eai.rms.onl.manage.sna.luinfo;

import java.util.HashMap;
import java.util.Iterator;
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.adapter.wca.cfg.LUInfoDataEx;
import com.eactive.eai.adapter.wca.command.UpdateLUInfoEx;
import com.eactive.eai.adapter.wca.util.SNAAgentUtil;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.spring.BaseController;
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.manage.sna.lugroup.LuGroupService;
import com.google.gson.Gson;

@Controller
public class LuInfoController extends BaseController{
	
	@Autowired
	@Qualifier("luInfoService")
	private LuInfoService service; 
	
	@Autowired
	@Qualifier("luGroupService")
	private LuGroupService groupService; 
	
    @Autowired
    @Qualifier("comboService")
    private ComboService comboService; 

	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.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/admin/sna/luInfoMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HashMap paramMap = new HashMap();
//		List groupList = comboService
//				.selectListComboForTable("TSEAIAD13", "SNAADPTRSEVRNAME", "SNAADPTRSEVRIPNAME", "");
		List adapterList = groupService.selectSnaAdapterList();
		List luGroupShortNameList = groupService.selectLuGroupShortNameList();
		List luGroupList = groupService.selectLuGroupList(paramMap);

		List<ComboVo> listUseYn = comboService.getFromCode("YN_NUM");
		List<ComboVo> listLogLevel = comboService.getFromCode("SNA_LOG_LEVEL");
		List<ComboVo> listSndRcvDstCd = comboService.getFromCode("SNA_SNDRCV_DSTCD");

		Map resultMap = new HashMap();
//		resultMap.put("groupRows", groupList);
		resultMap.put("adapterRows", adapterList);
		resultMap.put("luGroupShortNameRows", luGroupShortNameList);
		resultMap.put("luGroupList", luGroupList);

		resultMap.put("useYnRows", listUseYn);
		resultMap.put("logLevelRows", listLogLevel);
		resultMap.put("sndRcvDstCdRows", listSndRcvDstCd);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=LIST_CHANGE_COMBO")
	public ModelAndView initCombo2( HttpServletRequest request,
	       HttpServletResponse response,String adptrGstatSevrName , String adptrGroupName) throws Exception {
	  HashMap paramMap = new HashMap();
	  paramMap.put("adptrGstatSevrName", adptrGstatSevrName);
	  paramMap.put("adptrGroupName", adptrGroupName);
	  List luGroupList  = groupService.selectLuGroupList(paramMap);
	   
	  Map resultMap = new HashMap();
      resultMap.put("luGroupList" , luGroupList);
			
	  ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
	  return modelAndView;            
	} 	
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		HashMap map = service.selectList( pageVo.getStartNum(), pageVo.getEndNum(),paramMap);
			
		pageVo.setTotalCount((Integer)map.get("totalCount"));
		
		Map resultMap = new HashMap();
		resultMap.put("total"  , pageVo.getTotal());  //전체 페이지수
		resultMap.put("page"   , pageVo.getPage());   //현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());//전체 레코드건수	
		resultMap.put("rows"   , map.get("list"));
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=DETAIL")
	private ModelAndView selectDetail(HttpServletRequest request,HttpServletResponse response,String adptrGstatSevrName,String adptrGroupName 
			,String luGroupName,String puName,String luName) throws Exception {
		
		HashMap map = service.selectDetail(adptrGstatSevrName,adptrGroupName,luGroupName,puName,luName);
		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
		
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=INSERT")
	private ModelAndView insert(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map  ) throws Exception {
		
		String message = "";
		
		String  ALPABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	    String  newLuName = "" ;
	    boolean isAlpabet = false;
		int    nFrom, nTo, len=0 ;
		
		String range1 = map.get("range1").toString();
		String range2 = map.get("range2").toString();
		
		String orgLuName = map.get("luName").toString();
		
		if( range1 == null ) range1 = "";
		else {
		    range1 = range1.toUpperCase();
		    range1 = range1.trim();
		}
		if( range2 == null ) range2 = "" ;
		else {
		    range2 = range2.toUpperCase();
		    range2 = range2.trim();
		}
		
		if( ! range1.equals("") && ! range2.equals("") ) {
		    // 알파벳이면
		    if( ( nFrom = ALPABET.indexOf(range1)) != -1) {
		        nTo = ALPABET.indexOf(range2);
		        isAlpabet = true ;
		    } else {
                nFrom = Integer.parseInt(range1);
                nTo   = Integer.parseInt(range2);
                len = range2.length();				        
		    }
		    
            for( int nIndex = nFrom ; nIndex <= nTo ; nIndex++ ) {
            	
                if( isAlpabet ) {
                    newLuName = orgLuName + ALPABET.substring(nIndex, nIndex+1);
                } else {
                    newLuName = orgLuName + CommonUtil.leftPadString(String.valueOf(nIndex), len, "0");
                }
                
                map.put("luName", newLuName);
                message = service.insertData(map);
               
                if("success".equals(message)){
                	LUInfoDataEx data = setParameter(map);
            		message = updateApply(data);
        		}
            }
           
		}else{
			map.put("luName", map.get("luName"));
			message = service.insertData(map);
			
			if("success".equals(message)){
				LUInfoDataEx data = setParameter(map);
				message = updateApply(data);
			}
		}
		
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=UPDATE")
	private ModelAndView update(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map  ) throws Exception {
		String message = "success";
		service.update(map);
		
		LUInfoDataEx data = setParameter(map);
		message = updateApply(data);
		
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=DELETE_LIST")
	private ModelAndView deleteMulti(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map ) throws Exception {
	//	HashMap paramMap = new HashMap();
		String message = "success";
		
		String[] adptrGstatSevrNameArr = ((String) map.get("adptrGstatSevrName")).split(",");
		String[] adptrGroupNameArr = ((String) map.get("adptrGroupName")).split(",");
		String[] luGroupNameArr = ((String) map.get("luGroupName")).split(",");
		String[] puNameArr = ((String) map.get("puName")).split(",");
		String[] luNameArr = ((String) map.get("luName")).split(",");
		
		int idx = 0;
		for(String adptrGstatSevrName : adptrGstatSevrNameArr){
			map.put("adptrGstatSevrName", adptrGstatSevrName);
			map.put("adptrGroupName", adptrGroupNameArr[idx]);
			map.put("luGroupName", luGroupNameArr[idx]);
			map.put("puName", puNameArr[idx]);
			map.put("luName", luNameArr[idx]);
			
			service.delete(map);
			idx++;
			
			LUInfoDataEx data = setParameter(map);
			message = updateApply(data);
			
		}
		
		if("success".equals(message)){
			message = "총"+idx+"건을 삭제하였습니다";
		}
		
		message = "총"+idx+"건을 삭제하였습니다";
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	
	@RequestMapping(value= "/onl/admin/sna/luInfoMan.json",params = "cmd=DELETE")
	private ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map) throws Exception {
		String message = "success";
		
		try{
			service.delete(map);
			
		}catch (Exception e){
			message = "삭제 중 에러가 발생했습니다";
			throw new Exception(message);
		}
		
		if("success".equals(message)){
			LUInfoDataEx data = setParameter(map);
			message = updateApply(data);
		}
		
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
	
	/**
	 * 1. 기능 : 실시간 적용 2. 처리 개요 : 3. 주의사항
	 * 
	 * @param data
	 *            LUInfoData
	 */
	private String updateApply(LUInfoDataEx data) throws Exception {
		
		HashMap result = new HashMap();
		String msg = "success";
		try {
			Command command = new UpdateLUInfoEx();
			command.setArgs(data);
			result = agentUtilService.broadcast(command);
			 //agentUtilService.broadcast(command);
							
            // 홍팀장 요청사항 : 20091028
            SNAAgentUtil.notifySoftlinkNode(data.getNodeName(), data.getAdapterGroupName(), data.getGroupName());
            
		} catch (Exception e) {
			//e.printStackTrace();
			msg = "시스템 적용 실패하였습니다. "  ;
			//throw new WebException("시스템 적용 실패하였습니다.");
		}

		String sErrorResult = makeErrorString(result);
		if (sErrorResult.length() > 0){
			msg = "시스템 적용 실패하였습니다.   <Br> " + sErrorResult ;
			throw new Exception(msg);
		}
			
		return msg;
	}

	private String makeErrorString(HashMap result) {
		StringBuffer sbResult = new StringBuffer();
		Iterator it = result.keySet().iterator();
		String sSvrName = null;
		String sResult = null;
		while (it.hasNext()) {
			sSvrName = (String) it.next();
			sResult = (String) result.get(sSvrName);
			if (sResult.equals("success"))
				continue;

			sbResult.append(sSvrName + " : " + sResult + "<br>");
		}
		return sbResult.toString();
	}

	private LUInfoDataEx setParameter(HashMap<String,Object> param)
	{
		// 1. 파라미터 설정
		LUInfoDataEx data = new LUInfoDataEx();

		data.setNodeName((param.get("adptrGstatSevrName")!=null?param.get("adptrGstatSevrName").toString():""));
		data.setAdapterGroupName((param.get("adptrGroupName")!=null?param.get("adptrGroupName").toString():""));
		data.setGroupName((param.get("luGroupName")!=null?param.get("luGroupName").toString():""));
		data.setPUName((param.get("puName")!=null?param.get("puName").toString():""));
		data.setLUName((param.get("luName")!=null?param.get("luName").toString():""));
		data.setTranMode((param.get("sndrcvdstcd")!=null?param.get("sndrcvdstcd").toString():""));
		data.setApplyID((param.get("uapplidname")!=null?param.get("uapplidname").toString():""));
		data.setBackupLUYN((param.get("bkupluyn")!=null?param.get("bkupluyn").toString():""));
		data.setLogYN((param.get("loguseyn")!=null?param.get("loguseyn").toString():""));
		data.setLogLevel((param.get("loglvelname")!=null?param.get("loglvelname").toString():""));
		data.setLogSize((param.get("maxlogfileval")!=null?param.get("maxlogfileval").toString():""));
		return data;
	}
	
	   @RequestMapping(value= "/onl/admin/sna/luInfoMan.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.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, Object>[] 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;
	    }	
	

}
