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

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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.common.util.StringUtil;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.util.ControllerValidationHelper;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.c2rservice.C2rServiceSearch;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.google.gson.Gson;

@Controller
public class C2rServiceController extends OnlBaseAnnotationController {

	@Autowired
	private C2rServiceManService service;

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.view")
	public void viewList() {
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.view", params = "cmd=DETAIL")
	public String detailView() {
		return "/onl/admin/service/c2rServiceManDetail";
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<C2rServiceUI>> selectList(HttpServletRequest request, Pageable pageVo,
			C2rServiceSearch uiSearch) {
		Page<C2rServiceUI> page = service.selectList(pageVo, uiSearch);
		return ResponseEntity.ok(new GridResponse<C2rServiceUI>(page));
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=DETAIL")
	public ResponseEntity<?> selectDetail(HttpServletRequest request, HttpServletResponse response,
			String extnlInstiIdnfiName, String svcPrcssNo) {
		C2rServiceUI map = service.selectDetail(extnlInstiIdnfiName, svcPrcssNo);
		return ResponseEntity.ok(map);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=INSERT")
	public ResponseEntity<?> insert(HttpServletRequest request, HttpServletResponse response, @Valid C2rServiceUI uiVo,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.insert(uiVo);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.ReloadC2RServiceCommand",
				uiVo.getExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=UPDATE")
	public ResponseEntity<?> update(HttpServletRequest request, HttpServletResponse response, @Valid C2rServiceUI uiVo,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.update(uiVo);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.ReloadC2RServiceCommand",
				uiVo.getExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=DELETE")
	public ResponseEntity<?> delete(HttpServletRequest request, HttpServletResponse response,
			String extnlInstiIdnfiName, String svcPrcssNo) throws Exception {
		service.delete(extnlInstiIdnfiName, svcPrcssNo);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.RemoveC2RServiceCommand",
				extnlInstiIdnfiName + svcPrcssNo);
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView selectListInitCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, List<ComboVo>> map = service.selectListInitCombo(userId);
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=LIST_DETAIL_COMBO")
	public ModelAndView selectListDetailCombo(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String userId = SessionManager.getUserId(request);
		Map<String, List<?>> map = service.selectListDetailCombo(userId);
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=INITIALIZES")
	public ModelAndView initializes(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.ReloadC2RServiceCommand", "ALL");
		;
		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);
		HashMap<String, String> map = new HashMap<>();
		map.put("message", CommonUtil.getMapString(returnMap, true));
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=INITIALIZE")
	public ModelAndView initialize(HttpServletRequest request, HttpServletResponse response, String extnlInstiIdnfiName)
			throws Exception {

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.ReloadC2RServiceCommand",
				extnlInstiIdnfiName);
		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);
		HashMap<String, String> map = new HashMap<>();
		map.put("message", CommonUtil.getMapString(returnMap, true));
		return new ModelAndView("jsonView", map);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=CLONE")
	public ResponseEntity<?> clone(HttpServletRequest request, HttpServletResponse response, @Valid C2rServiceUI uiVo,
			BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return ControllerValidationHelper.checkValidation(bindingResult);
		}
		service.clone(uiVo);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.c2rservice.ReloadC2RServiceCommand",
				uiVo.getNewExtnlInstiIdnfiName());
		HashMap<String, Object> commandResult = agentUtilService.broadcast(command);
		return ResponseEntity.ok(commandResult);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap, C2rServiceSearch uiSearch) 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();
		Map<String, List<?>> list = service.selectListToExcel(uiSearch);

		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);
		return new ModelAndView("excelView", resultMap);
	}

	@RequestMapping(value = "/onl/admin/service/c2rServiceMan.json", params = "cmd=CLONETOPROD")
	public ModelAndView cloneToProd(HttpServletRequest request, @RequestParam HashMap<String, Object> paramMap)
			throws Exception {

		if (!SystemUtil.isDevServer()) {
			throw new Exception("only support dev server ");
		}

		HashMap<String, Object> resultMap = new HashMap<>();
		String userId = SessionManager.getUserId(request);
		String cmDate = StringUtil.getNullStr(paramMap.get("CmDate"));
		String cmTime = StringUtil.getNullStr(paramMap.get("CmTime"));
		String sysCode = StringUtil.getNullStr(paramMap.get("SysCode"));
		String listSvcName = StringUtil.getNullStr(paramMap.get("selectedList"));
		String serviceType = StringUtil.getNullStr(paramMap.get("serviceType"));

		try {
			service.extractC2R(userId, listSvcName, cmDate, cmTime, sysCode, serviceType);
			resultMap.put("message", "적용이 완료되었습니다.");
		} catch (BizException be) {
			throw new Exception(be.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception("CM대상 자원의 운영적용에 있어 에러가 발생했습니다.\n" + e.getMessage());
		}

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

}