package com.eactive.eai.rms.onl.manage.control.control;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
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.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.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.login.SessionManager;
import com.google.gson.Gson;

@Controller
public class ControlManController extends OnlBaseAnnotationController {

	private static final String RELOAD_RESTRICT_INFO_COMMAND = "com.eactive.eai.agent.restrict.ReloadRestrictInfoCommand";
	private static final String ERROR_RESULT_STATUS = "<font color='#ff0000'>에러</font>";

	@Autowired
	private ControlManService service;

	@RequestMapping(value = "/onl/admin/control/controlMan.view")
	public String viewList() {
		return "/onl/admin/control/controlMan";
	}

	@RequestMapping(value = "/onl/admin/control/controlMan.view", params = "cmd=POPUP")
	public String popupView() {
		return "/onl/admin/control/controlManPopup";
	}

	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request, ControlManUISearch uiSearch) {
		Map<String, Object> map = service.selectList(uiSearch);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("rows", map.get("list"));
		return new ModelAndView("jsonView", resultMap);
	}

	// 통제 등록
	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=INSERT")
	public String insert(HttpServletRequest request, HttpServletResponse response, ControlManUIDetail uiDetail)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		service.insert(uiDetail, userId);
		CommonCommand command = new CommonCommand(RELOAD_RESTRICT_INFO_COMMAND);
		agentUtilService.broadcast(command);
		return null;
	}

	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=DELETE")
	public String delete(HttpServletRequest request, HttpServletResponse response, ControlManUIDetail uiDetail)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		service.delete(uiDetail, userId);
		CommonCommand command = new CommonCommand(RELOAD_RESTRICT_INFO_COMMAND);
		agentUtilService.broadcast(command);
		return null;
	}

	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView selectListInitCombo(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView("jsonView", service.selectListInitCombo());
	}
	
/*
	@RequestMapping(value= "/onl/admin/control/controlMan.json",params = "cmd=INITIALIZES")
	public ModelAndView initializes(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.restrict.RemoveRestrictInfoCommand");
		HashMap returnMap =  agentUtilService.broadcast(command);
		HashMap map = new HashMap();
		map.put("message", CommonUtil.getMapString(returnMap, true));

		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;

	}
*/
	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=INSERT_CONTROL_ALL")
	public String insertControlAll(HttpServletRequest request, HttpServletResponse response, ControlManUIDetail uiDetail)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		service.insertAll(uiDetail, userId);
		CommonCommand command = new CommonCommand(RELOAD_RESTRICT_INFO_COMMAND);
		agentUtilService.broadcast(command);
		return null;
	}
	
	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=DELETE_CONTROL_ALL")
	public String deleteControlAll(HttpServletRequest request, HttpServletResponse response, ControlManUIDetail uiDetail)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		service.deleteAll(uiDetail, userId);
		CommonCommand command = new CommonCommand(RELOAD_RESTRICT_INFO_COMMAND);
		agentUtilService.broadcast(command);
		return null;
	}
	
	// 서비스코드업로드
	@RequestMapping(value = "/onl/admin/control/controlMan.json", params = "cmd=TRANSACTION_SERVICE")
	public ModelAndView insertServiceName(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> map, @RequestParam String serviceNames) throws Exception {
	
		String userId = SessionManager.getUserId(request);
		String flag = (String) map.get("flag");
	
		List<ControlManUI> list = new ArrayList<>();
	
		int totalCnt = 0;
		HashSet<String> set = new HashSet<>();
		for (String eaiSvcName : serviceNames.split("\\n")) {
			if ("".equals(eaiSvcName))
				continue;
	
			boolean notInSetYet = set.add(eaiSvcName);
			ControlManUI resultRow = new ControlManUI();
			if (notInSetYet) {
				// 서비스코드 검증
				processRestrict(map, userId, flag, eaiSvcName, resultRow);
			} else {
				resultRow.setStatus(ERROR_RESULT_STATUS);
				resultRow.setResult("<font color='#0000ff'>서비스코드가 중복되었습니다</font>");
			}
			totalCnt++;
			resultRow.setEaisvcname(eaiSvcName);
			resultRow.setSeq(totalCnt);
	
			list.add(resultRow);
		}
	
		CommonCommand command = new CommonCommand(RELOAD_RESTRICT_INFO_COMMAND);
		agentUtilService.broadcast(command);
	
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("rows", list);
		resultMap.put("totalCnt", totalCnt);
	
		return new ModelAndView("jsonView", resultMap);
	}
	
	private void processRestrict(Map<String, Object> map, String userId, String flag, String eaiSvcName,
			ControlManUI resultRow) {
		boolean eaiSvcExist = service.existEaiSvcName(eaiSvcName);
		logger.info("통제해제 서비스코드  : " + eaiSvcName + " , insertMap : " + map.toString());
		if (eaiSvcExist) {
			map.put("eaiCtrlName", eaiSvcName);
	
			if ("I".equals(flag)) {
				try {
					service.insertServiceType(eaiSvcName, userId);
					resultRow.setStatus("통제");
					resultRow.setResult("정상처리");
				} catch (RuntimeException e) {
					resultRow.setStatus(ERROR_RESULT_STATUS);
					resultRow.setResult("<font color='#0000ff'>" + e.getMessage() + "</font>");
				}
			} else {
				try {
					service.delete(eaiSvcName, userId);
					resultRow.setStatus("해제");
					resultRow.setResult("정상처리");
				} catch (RuntimeException e) {
					resultRow.setStatus(ERROR_RESULT_STATUS);
					resultRow.setResult("<font color='#0000ff'>" + e.getMessage() + "</font>");
				}
			}
		} else {
			resultRow.setStatus(ERROR_RESULT_STATUS);
			resultRow.setResult("<font color='#0000ff'>인터페이스 ID를 확인해주세요</font>");
		}
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/onl/admin/control/controlMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap, ControlManUISearch uiSearch) {
		HashMap<String, Object> resultMap = new HashMap<>();
		Gson gson = new Gson();
		Map<String, List<?>> list = service.selectListToExcel(uiSearch);
		String jsonStr = gson.toJson(list.get("list"));
		HashMap<String, Object>[] dataList = 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);
	
		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", dataList);
		resultMap.put("fileName", paramMap.get("fileName"));
		return new ModelAndView("excelView", resultMap);
	}

}