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

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.SessionGroupDataEx;
import com.eactive.eai.adapter.wca.command.DeleteSessionGroupEx;
import com.eactive.eai.adapter.wca.command.InsertSessionGroupEx;
import com.eactive.eai.adapter.wca.command.UpdateSessionGroupEx;
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.vo.JsonPageVo;
import com.google.gson.Gson;

/**
 * <pre>
 *     1. 기능 : 관리자 SNA관리 LU그룹관리 화면의 컨트롤러
 * </pre>
 * 
 * @author : seo
 * @version :
 * @since :
 */
@Controller
public class LuGroupController extends BaseController {

	@Autowired
	@Qualifier("luGroupService")
	private LuGroupService service;

	@Autowired
	@Qualifier("comboService")
	private ComboService comboService;

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.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/luGroupMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// List groupList = service.selectSnaGroupList();
//	   List groupList  = comboService.selectListComboForTable("TSEAIAD13", "SNAADPTRSEVRNAME","SNAADPTRSEVRIPNAME", "");
		List adapterList = service.selectSnaAdapterList();// YN

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

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

		resultMap.put("useYnRows", listUseYn);
		resultMap.put("autoCnvsnYnRows", listAutoCnvsnYn);
		resultMap.put("logLevelRows", listLogLevel);

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.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(), (String) paramMap.get("searchAdptrGstatSevrName"),
						(String) paramMap.get("searchAdptrGroupName"));

		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/luGroupMan.json", params = "cmd=DETAIL")
	private ModelAndView selectDetail(HttpServletRequest request, HttpServletResponse response,
			String adptrGstatSevrName, String adptrGroupName, String luGroupName) throws Exception {

		HashMap map = service.selectDetail(adptrGstatSevrName, adptrGroupName, luGroupName);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);

		return modelAndView;
	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.json", params = "cmd=INSERT")
	private ModelAndView insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		String message = "";
		int luGroupCnt = 0;

		luGroupCnt = service.selectLuGroupCnt(map);

		if (luGroupCnt == 0) {
			service.insert(map);

			SessionGroupDataEx data = setParameter(map);
			message = updateApply("INSERT", data);
		} else {
			message = "이미 존재하는 LU그룹명 입니다";
		}

		Map resultMap = new HashMap();
		resultMap.put("message", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.json", params = "cmd=UPDATE")
	private ModelAndView update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {
		String message = "";

		service.update(map);

		SessionGroupDataEx data = setParameter(map);
		message = updateApply("UPDATE", data);

		Map resultMap = new HashMap();
		resultMap.put("message", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.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 = "";

		String[] adptrGstatSevrNameArr = ((String) map.get("adptrGstatSevrName")).split(",");
		String[] adptrGroupNameArr = ((String) map.get("adptrGroupName")).split(",");
		String[] luGroupNameArr = ((String) map.get("luGroupName")).split(",");

		int idx = 0;
		for (String adptrGstatSevrName : adptrGstatSevrNameArr) {
			paramMap.put("adptrGstatSevrName", adptrGstatSevrName);
			paramMap.put("adptrGroupName", adptrGroupNameArr[idx]);
			paramMap.put("luGroupName", luGroupNameArr[idx]);

			service.delete(paramMap);
			idx++;

			SessionGroupDataEx data = setParameter(map);
			message = updateApply("DELETE", data);
		}

		if ("success".equals(message)) {
			message = "총" + idx + "건을 삭제하였습니다";
		}

		Map resultMap = new HashMap();
		resultMap.put("message", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.json", params = "cmd=DELETE")
	private ModelAndView delete(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {
		String message = "";
		service.delete(map);

		SessionGroupDataEx data = setParameter(map);
		message = updateApply("DELETE", data);

		Map resultMap = new HashMap();
		resultMap.put("message", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

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

		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.setPort((param.get("softlinkportno") != null ? param.get("softlinkportno").toString() : ""));
		data.setSessionCnt((param.get("wcasesscnt") != null ? param.get("wcasesscnt").toString() : ""));
		data.setTranTimeout((param.get("svctoutval") != null ? param.get("svctoutval").toString() : ""));
		data.setDummyOffset((param.get("dmymsgsituval") != null ? param.get("dmymsgsituval").toString() : ""));
		data.setHostSndRUSize((param.get("hostsndmsgruval") != null ? param.get("hostsndmsgruval").toString() : ""));
		data.setHostRcvRUSize((param.get("hostdpstruval") != null ? param.get("hostdpstruval").toString() : ""));

		data.setApplyID((param.get("uapplidname") != null ? param.get("uapplidname").toString() : ""));

		data.setBackupCvsMode((param.get("bkupautocnvsnyn") != null ? param.get("bkupautocnvsnyn").toString() : ""));
		data
				.setBackupCvsVal(
						(param.get("bkupcnvsnbaseobstclrt") != null ? param.get("bkupcnvsnbaseobstclrt").toString()
								: ""));
		data
				.setBackupNodeName(
						(param.get("bkupadptrgstatsevrname") != null ? param.get("bkupadptrgstatsevrname").toString()
								: ""));
		data.setBackupPort((param.get("bkupsoftlinkportno") != null ? param.get("bkupsoftlinkportno").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;
	}

	/**
	 * 1. 기능 : 실시간 적용 2. 처리 개요 : 3. 주의사항
	 *
	 * @param sCommand 추가,삭제, 수정 명령어 구분자
	 * @param data     SessionGroupData
	 **/
	private String updateApply(String sCommand, SessionGroupDataEx data) throws Exception {
		HashMap result = new HashMap();
		String msg = "success";

		try {
			Command command = null;
			if (sCommand.equals("INSERT"))
				command = new InsertSessionGroupEx();
			if (sCommand.equals("UPDATE"))
				command = new UpdateSessionGroupEx();
			if (sCommand.equals("DELETE"))
				command = new DeleteSessionGroupEx();

			command.setArgs(data);
			agentUtilService.broadcast(command);

			// 홍팀장 요청사항 : 20091028
			SNAAgentUtil.notifySoftlinkNode(data.getNodeName(), data.getAdapterGroupName(), data.getGroupName());
		} catch (Exception e) {
			// e.printStackTrace();
			msg = "시스템 적용 실패하였습니다. ";
		}
		if (result.size() > 0) { // 에러가 있을 경우
			msg = "시스템 적용 실패하였습니다.   <Br> " + makeErrorString(result);
			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();
	}

	@RequestMapping(value = "/onl/admin/sna/luGroupMan.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;
	}

}
