package com.eactive.eai.rms.onl.manage.adapter.socketport;

import java.text.SimpleDateFormat;
import java.util.Date;
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.data.domain.Pageable;
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.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.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
public class SocketPortController extends OnlBaseAnnotationController {

	private SocketPortManService service;

	private ComboService comboService;

	@Autowired
	public SocketPortController(SocketPortManService service, ComboService comboService) {
		this.service = service;
		this.comboService = comboService;
	}

	@GetMapping(value = "/onl/admin/adapter/socketPortMan.view")
	public String viewList() {
		return "/onl/admin/adapter/socketPortMan";
	}

	@GetMapping(value = "/onl/admin/adapter/socketPortMan.view", params = "cmd=DETAIL")
	public String viewDetail() {
		return "/onl/admin/adapter/socketPortManDetail";
	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=LIST_INIT_COMBO")
	public ResponseEntity<Map<String, Object>> searchInitCombo(HttpServletRequest request,
			HttpServletResponse response) {

		List<ComboVo> listInoutTypeCd = comboService.getFromCode("PORT_SVERTYPE");// EAI서버구분코드
		List<ComboVo> listUseYnType = comboService.getFromCode("USE_YN_TYPE");
		List<ComboVo> listOrderType = comboService.getFromCode("PORT_ORDERBY");

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("inoutTypeRows", listInoutTypeCd);
		resultMap.put("useYnTypeRows", listUseYnType);
		resultMap.put("orderTypeRows", listOrderType);

		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=LIST")
	public ModelAndView selectList(HttpServletRequest request, JsonPageVo pageVo,
			@RequestParam HashMap<String, Object> paramMap, String searchOrderType, String searchAdptrPort,
			String searchEaiSevrDstCd, String searchAdptrBzwkNameDesc, String searchAdptrBzwkName, Pageable pageable)
			throws Exception {

		HashMap map = service
				.selectList(pageVo.getStartNum(), pageVo.getEndNum(), paramMap, searchAdptrBzwkName,
						searchAdptrBzwkName, searchAdptrBzwkName, searchAdptrBzwkName, searchAdptrBzwkName, pageable);

		Map resultMap = new HashMap();
		if (!"".equals((String) paramMap.get("searchUseYn"))) {
			resultMap.put("total", 1); // 전체 페이지수
			resultMap.put("page", 1); // 현재 페이지수
		} else {
			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;

	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=DETAIL")
	public ModelAndView selectDetail(HttpServletRequest request, HttpServletResponse response, String eaiSevrDstCd,
			String recvTestPort) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("eaiSevrDstCd", eaiSevrDstCd);
		paramMap.put("recvTestPort", recvTestPort);
		HashMap map = service.selectDetail(paramMap);

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

		return modelAndView;
	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=DETAIL_INIT_PORT")
	public ModelAndView selectInitPort(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> paramMap) throws Exception {

		HashMap map = service.selectUnusedPort(paramMap);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);

		return modelAndView;
	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=INSERT")
	public ModelAndView insert(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		String message = "success";
		String userId = SessionManager.getUserId(request);
		SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		map.put("sendPortLastYmd", dateF.format(new Date()));
		map.put("recvPortLastYmd", dateF.format(new Date()));
		map.put("sendLastAdmUserId", userId);
		map.put("recvLastAdmUserId", userId);

		int portdupChk = 0;

		portdupChk = service.selectPortdupChk(map);

		if (portdupChk == 0) {
			service.insert(map);
		} else {
			message = "이미 존재하는 포트번호입니다";
		}

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

	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=UPDATE")
	public ModelAndView update(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {

		String message = "success";

		String userId = SessionManager.getUserId(request);
		SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		map.put("sendPortLastYmd", dateF.format(new Date()));
		map.put("recvPortLastYmd", dateF.format(new Date()));
		map.put("sendLastAdmUserId", userId);
		map.put("recvLastAdmUserId", userId);

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

	}

	// EAI 결재 승인
	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=DELETE_LIST")
	public ModelAndView deleteList(HttpServletRequest request, HttpServletResponse response, String gridData)
			throws Exception {
		String message = "success";

		Gson gson = new Gson();
		@SuppressWarnings("unchecked")

		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);

		try {
			service.deleteList(list);
		} catch (Exception e) {
			logger.debug("delete port error" + e.getMessage());
			message = "error";
		}

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

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.json", params = "cmd=DELETE")
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response,
			@RequestParam HashMap<String, Object> map) throws Exception {
		String message = "success";
		service.delete(map);
		Map resultMap = new HashMap();
		resultMap.put("message", message);
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}

	@PostMapping(value = "/onl/admin/adapter/socketPortMan.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);
		headersStr = headersStr.replace(",RECVPORTUSEYN", "");
		headersStr = headersStr.replace(",SENDPORTUSEYN", "");
		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;
	}

}
