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

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

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

import org.apache.log4j.Logger;
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.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.agent.bizkey.RemoveBizKeyCommand;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.StringUtil;
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.spring.LocaleMessage;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.exception.EMSRuntimeException;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutDao;
import com.eactive.eai.rms.onl.manage.rule.layout.ui.LayoutItemUI;
import com.eactive.eai.rms.onl.manage.rule.layout.ui.LayoutPopupUI;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.EaiMsgManService;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.ui.EAIReferenceMessageUI;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller

public class FieldExtractInfoController extends OnlBaseAnnotationController {

	private static final Logger logger = Logger.getLogger(FieldExtractInfoController.class);

	/** The service info service. */
	@Autowired
	@Qualifier("fieldExtractInfoService")
	private FieldExtractInfoService service;

	@Autowired
	private EaiMsgManService eaiMsgManService;

	@Autowired
	@Qualifier("layoutDao")
	private LayoutDao layoutDao;

	@Autowired
	@Qualifier("localeMessage")
	private LocaleMessage localeMessage;

	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping(value = "/onl/admin/service/fieldExtractInfoMan.view")
	public String view() {
		return "/onl/admin/service/fieldExtractInfoMan";
	}

	@GetMapping(value = "/onl/admin/service/fieldExtractInfoMan.view", params = "cmd=DETAIL")
	public String viewDetail() {
		return "/onl/admin/service/fieldExtractInfoManDetail";
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<FieldExtractInfoUI>> selectList(String searchEaiSvcName,
			@PageableDefault Pageable pageable) {
		Page<FieldExtractInfoUI> page = service.selectList(searchEaiSvcName, pageable);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=DETAIL")
	public ResponseEntity<Map<String, Object>> selectDetail(String eaiSvcName, String etractDstcd) {

		List<FieldExtractInfoUI> list = service.selectDetail(eaiSvcName, etractDstcd);
		List<EAIReferenceMessageUI> refList = eaiMsgManService.selectListRef(eaiSvcName, 1);

		HashMap<String, Object> map = new HashMap<>();
		map.put("detailList", list);
		map.put("refList", refList);
		return ResponseEntity.ok(map);
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=INSERT")
	public String insert(FieldExtractInfoUI fieldExtractInfoUI, String[] bzwkFldName) throws Exception {
		fieldExtractInfoUI.setBzwkFldNames(bzwkFldName);
		service.insert(fieldExtractInfoUI);
		CommonCommand command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",
				fieldExtractInfoUI.getEaiSvcName() + "," + fieldExtractInfoUI.getEtractDstcd());
		agentUtilService.broadcast(command);

		return null;

	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=UPDATE")
	public String update(FieldExtractInfoUI fieldExtractInfoUI, String[] bzwkFldName) throws Exception {

		fieldExtractInfoUI.setBzwkFldNames(bzwkFldName);

		service.update(fieldExtractInfoUI);

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",
				fieldExtractInfoUI.getEaiSvcName() + "," + fieldExtractInfoUI.getEtractDstcd());
		agentUtilService.broadcast(command);
		return null;

	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=DELETE")
	public String delete(String eaiSvcName, String etractDstcd) throws Exception {

		service.delete(eaiSvcName, etractDstcd);
		CommonCommand command = new CommonCommand(RemoveBizKeyCommand.class.getName(), eaiSvcName + "," + etractDstcd);

		agentUtilService.broadcast(command);

		return null;

	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=DELETE_LIST")
	public ModelAndView deleteMulti(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> map) throws Exception {
		String message = "";

		String[] eaiSvcNameArr = ((String) map.get("eaiSvcName")).split(",");
		String[] etractDstcdArr = ((String) map.get("etractDstcd")).split(",");

		int idx = 0;
		Vector<String> vec = new Vector<>();
		for (String eaiSvcName : eaiSvcNameArr) {
			service.delete(eaiSvcName, etractDstcdArr[idx]);
			vec.add(eaiSvcName + etractDstcdArr[idx]);
			idx++;
		}

		CommonCommand command = new CommonCommand(RemoveBizKeyCommand.class.getName(), vec);

		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);

		message = "총" + idx + "건을 삭제하였습니다";
		message += CommonUtil.getMapString(returnMap, true);

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

	}

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

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

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

		CommonCommand command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand", eaiSvcName);
		HashMap<String, Object> returnMap = agentUtilService.broadcast(command);

		HashMap<String, Object> map = new HashMap<>();
		map.put("message", CommonUtil.getMapString(returnMap, true));

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

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=LIST_INIT_COMBO")
	public ResponseEntity<Map<String, List<ComboVo>>> selectListInitCombo() {
		Map<String, List<ComboVo>> map = service.selectListInitCombo();
		return ResponseEntity.ok(map);
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=LIST_DETAIL_COMBO")
	public ResponseEntity<Map<String, List<ComboVo>>> selectListDetailCombo() {
		Map<String, List<ComboVo>> map = service.selectListDetailCombo();
		return ResponseEntity.ok(map);
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=DETAIL_LAYOUT")
	public ResponseEntity<GridResponse<LayoutPopupUI>> selectDetailLauout(String loutName) {
		Page<LayoutPopupUI> page = service.selectLayoutItems(loutName);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=LIST_REF")
	public ModelAndView selectRef(HttpServletRequest request, HttpServletResponse response, String eaiSvcName) {
		List<EAIReferenceMessageUI> refList = eaiMsgManService.selectListRef(eaiSvcName, 1);
		HashMap<String, Object> map = new HashMap<>();
		map.put("refList", refList);
		return new ModelAndView("jsonView", map);
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> paramMap) throws JsonProcessingException {
		Map<String, Object> resultMap = new HashMap<>();

		String[] headers = objectMapper.readValue((String) paramMap.get("header"), String[].class);
		String[] headerTitles = objectMapper.readValue((String) paramMap.get("headerTitle"), String[].class);

		Map<String, Object>[] datas = service.selectListToExcel((String) paramMap.get("searchEaiSvcName"));

		HashMap<String, Object>[] lmerge = null;
		String merge = (String) paramMap.get("merge");
		if (merge != null) {
			lmerge = objectMapper.readValue(merge, new TypeReference<HashMap<String, Object>[]>() {
			});
		}

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", datas);
		resultMap.put("fileName", paramMap.get("fileName"));
		resultMap.put("merge", lmerge);
		return new ModelAndView("excelView", resultMap);
	}

	@PostMapping(value = "/onl/admin/service/fieldExtractInfoMan.json", params = "cmd=CLONETOPROD")
	public ModelAndView cloneToProd(HttpServletRequest request, @RequestParam Map<String, Object> paramMap)
			throws Exception {
		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 listSvcName = StringUtil.getNullStr(paramMap.get("listSvcName"));

		try {
			boolean ret = service.migrationToProdBizKeyService(userId, listSvcName, cmDate, cmTime);
			if (!ret) {
				throw new EMSRuntimeException("CM대상 자원의 운영적용에 있어 에러가 발생했습니다.");
			}
			resultMap.put("message", "적용이 완료되었습니다.");
		} catch (BizException be) {
			throw new BizException(be.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new EMSRuntimeException(localeMessage.getString("errors.checklog"));
		}

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

}
