package com.eactive.eai.rms.onl.transaction.trackingchart;

import java.util.HashMap;
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.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
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.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutManService;
import com.eactive.eai.rms.onl.manage.rule.layout.ui.LayoutUI;
import com.eactive.eai.rms.onl.manage.rule.layout.ui.LayoutUISearch;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformManService;
import com.google.gson.Gson;

/**
 * <pre>
 *     1. 기능 : 거래흐름도
 * </pre>
 *
 * @author : music75
 * @version : $Revision: 1.26.2.5 $
 * @since : rts 1.0
 */
@SuppressWarnings("unchecked")
@Controller
public class TrackingChartController extends OnlBaseAnnotationController {

	@Autowired
	private TrackingChartService service;

	@Autowired
	private LayoutManService layoutservice;

	@Autowired
	private TransformManService transformManService;

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

	@Autowired
	private LayoutManService layoutManService;

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.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/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request, String searchName) throws Exception {

		HashMap map = service.selectCodeGroupList(searchName);

		Map resultMap = new HashMap();
		resultMap.put("rows", map.get("list"));

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

	}

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_POP")
	private ModelAndView selectPopList(HttpServletRequest request, HttpServletResponse response, JsonPageVo pageVo,
			@RequestParam HashMap<String, Object> paramMap) throws Exception {

		HashMap map = service
				.selectPopList(pageVo.getStartNum(), pageVo.getEndNum(), (String) paramMap.get("eaiSvcName"));

		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;

	}

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request, HttpServletResponse response, String key)
			throws Exception {

		HashMap<String, Object> map = service.selectDetail(key);

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

		return modelAndView;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_CHK_CNT")
	public ModelAndView selectCntList(HttpServletRequest request, HttpServletResponse response, String transformData,
			String eaiSvcName) throws Exception {
		List mList = service.selectCntList(transformData, eaiSvcName);

		HashMap map = new HashMap();
		map.put("layout", mList);

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

		return modelAndView;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_ADAPTER_COMBO")
	public ModelAndView selectAdapterCombo(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) throws Exception {

		HashMap<String, Object> map = service.selectAdapterCombo(paramMap);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;
	}

	@PostMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_FIELD")
	public ResponseEntity<Map<String, Object>> selectDetailLauout(String loutName) {
		Map<String, Object> layoutDetailMap = layoutManService.selectDetail(loutName);
		return ResponseEntity.ok(layoutDetailMap);
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_TRANSFORM_ITEM")
	public ModelAndView transformItem(HttpServletRequest request, HttpServletResponse response, String cnvsnName,
			String loutName) throws Exception {
		List list = transformManService.selectTransformItems(cnvsnName, loutName);

		HashMap map = new HashMap();
		map.put("rows", list);

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

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_LAYOUT_ITEM")
	public ModelAndView listLayoutItem(HttpServletRequest request, HttpServletResponse response, String loutName)
			throws Exception {

		List list = transformManService.selectLayoutItems(loutName);
		HashMap map = new HashMap();
		map.put("rows", list);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=INSERT")
	private String insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String transformData) throws Exception {

		List forRld = service.insert(map, transformData);

		// 인터페이스에 대해서만 동기화
		reloadSync(map);

		for (int i = 0; i < forRld.size(); i++) {
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",
					forRld.get(i));
			agentUtilService.broadcast(command);
		}
		return null;

	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=UPDATE")
	private String update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String transformData) throws Exception {

		HashMap syncCnvsn = service.update(map, transformData);
		List forRmv = (List) syncCnvsn.get("forRmv");
		List forRld = (List) syncCnvsn.get("forRld");

		reloadSync(map);
		for (int i = 0; i < forRmv.size(); i++) {
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",
					forRmv.get(i));
			agentUtilService.broadcast(command);
		}
		for (int i = 0; i < forRld.size(); i++) {
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",
					forRld.get(i));
			agentUtilService.broadcast(command);
		}
		return null;

	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=DELETE")
	private String delete(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String eaiSvcName, String transformData) throws Exception {

		Gson gson = new Gson();
		HashMap[] list = gson.fromJson(transformData, HashMap[].class);

		HashMap retMap = service.delete(eaiSvcName, transformData);

		Boolean forSync = (Boolean) retMap.get("forSync");
		List syncEaiSvcName = (List) retMap.get("syncEaiSvcName");

		deleteSync(map);
		// transform 삭제 동기화
		if (forSync == true) {
			for (int i = 0; i < list.length; i++) {
				String cnvsnName = (String) list[i].get("cnvsnName");

				CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",
						cnvsnName);
				agentUtilService.broadcast(command);
			}
			for (int i = 0, n = syncEaiSvcName.size(); i < n; i++) {
				HashMap paramMap = new HashMap();
				paramMap.put("eaiSvcName", syncEaiSvcName.get(i));
				reloadSync(paramMap);

			}
		}
		return null;

	}

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_DETAIL_COMBO")
	public ModelAndView selectDetailCombo(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String userId = SessionManager.getUserId(request);
		HashMap<String, Object> map = service.selectDetailCombo(userId);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_LAYOUT")
	public ResponseEntity<GridResponse<LayoutUI>> selectList(Pageable pageable, LayoutUISearch layoutUISearch) {

		Page<LayoutUI> layoutUis = layoutservice.selectList(pageable, layoutUISearch);

		return ResponseEntity.ok(new GridResponse<>(layoutUis));

	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_LAYOUT_INIT_COMBO")
	private ModelAndView selectList(HttpServletRequest request) throws Exception {
		List<ComboVo> listInoutTypeCd = comboService.getFromCode("INOUT_TYPE");// EAI서버구분코드
		Map resultMap = new HashMap();
		resultMap.put("inoutTypeRows", listInoutTypeCd);

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

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response, String eaiSvcName)
			throws Exception {

		List<ComboVo> listFunction = comboService.getFromFunction();
		List listTransform = transformManService.selectTransformForEaiSvcNameCombo(eaiSvcName);

		Map resultMap = new HashMap();

		resultMap.put("functionRows", listFunction);
		resultMap.put("transformRows", listTransform);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=MAPPING")
	private String mapping(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String gridData, String cnvsnName, String eaiSvcName)
			throws Exception {

		service.insertMapping(map, gridData, cnvsnName);

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",
				cnvsnName);
		agentUtilService.broadcast(command);

		return null;
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=UNMAPPING")
	private String unmapping(HttpServletRequest request, HttpServletResponse response, String cnvsnName,
			String eaiSvcName) throws Exception {

		service.deleteMapping(cnvsnName);

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",
				cnvsnName);
		agentUtilService.broadcast(command);

		return null;

	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=CLONE")
	private String clone(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map, String transformData) throws Exception {

		service.clone(map, transformData);

		// 인터페이스에 대해서만 동기화
		reloadSync(map);

		return null;

	}

	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */

	public void reloadSync(HashMap<String, Object> param) throws Exception {
		logger.debug("--------------------------------------------------------------------------");
		logger.info("- 동기화 처리 -------------------------------------------------------------");
		StringBuffer result = new StringBuffer();

		// 기존 정보 조회 및 확인
		logger.debug("eaiSvcName : [" + param.get("eaiSvcName") + "]");

//		result.append("-[내부표준메세지 초기화]-------------------");
//		//HS04,HS05 내부표준전문
//		String key = (String)param.get("bzwkSvcKeyName");
//		if (key != null && !"".equals(key)){
//			CommonCommand cmdHS = new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand",key);
//			agentUtilService.broadcast(cmdHS);
//		}
		result.append("---------------------------------------");

		result.append("-[IF메세지 초기화]------------------------");
		// HE01 EAI 메시지 공통부
		String key = (String) param.get("eaiSvcName");
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand", key);
		;
		agentUtilService.broadcast(cmdHE01);
		result.append("---------------------------------------");

		result.append("-[필드추출정보 초기화]---------------------");
		// 메모리 정보 Reload
		key = (String) param.get("eaiSvcName");
		CommonCommand cmdFR03 = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand", key);
		;
		agentUtilService.broadcast(cmdFR03);
		logger.debug("--------------------------------------------------------------------------");
		logger.info(result.toString());

		/*
		 * result.append("-[매핑정보 초기화]---------------------"); //메모리 정보 Reload key =
		 * (String)param.get("cnvsnName"); CommonCommand cmdTR = new
		 * CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",key)
		 * ; agentUtilService.broadcast(cmdTR); logger.debug(
		 * "--------------------------------------------------------------------------")
		 * ; logger.info(result.toString());
		 */
	}

	public void deleteSync(HashMap<String, Object> param) throws Exception {
		logger.debug("--------------------------------------------------------------------------");
		logger.info("- 동기화 처리 -------------------------------------------------------------");
		StringBuffer result = new StringBuffer();

		// 기존 정보 조회 및 확인
		logger.debug("eaiSvcName : [" + param.get("eaiSvcName") + "]");

		result.append("-[내부표준메세지 초기화]-------------------");
		// HS04,HS05 내부표준전문
		String key = (String) param.get("bzwkSvcKeyName");
		if (key != null && !"".equals(key)) {
			CommonCommand cmdHS = new CommonCommand("com.eactive.eai.agent.stdmessage.RemoveSTDMessageCommand", key);
			agentUtilService.broadcast(cmdHS);
		}
		result.append("---------------------------------------");

		result.append("-[IF메세지 초기화]------------------------");
		// HE01 EAI 메시지 공통부
		key = (String) param.get("eaiSvcName");
		CommonCommand cmdHE01 = new CommonCommand("com.eactive.eai.agent.eaimessage.RemoveEAIMessageCommand", key);
		;
		agentUtilService.broadcast(cmdHE01);
		result.append("---------------------------------------");

		result.append("-[필드추출정보 초기화]---------------------");
		// 메모리 정보 Reload
		key = (String) param.get("eaiSvcName");
		CommonCommand cmdFR03 = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand", key);
		;
		agentUtilService.broadcast(cmdFR03);
		logger.debug("--------------------------------------------------------------------------");
		logger.info(result.toString());

		/*
		 * result.append("-[매핑추출정보 초기화]---------------------"); //메모리 정보 Reload key =
		 * (String)param.get("cnvsnName"); CommonCommand cmdTR = new
		 * CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",key)
		 * ;; agentUtilService.broadcast(cmdTR); logger.debug(
		 * "--------------------------------------------------------------------------")
		 * ; logger.info(result.toString());
		 */
	}

	@RequestMapping(value = "/onl/transaction/tracking/dbTrackingChartMan.json", params = "cmd=CHK_IF")
	private String checkInterface(HttpServletRequest request, HttpServletResponse response, String eaiSvcName)
			throws Exception {

		String chk = service.checkInterface(eaiSvcName);

		return chk;

	}

}
