package incheon.sgp.por.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import incheon.ags.ias.popupNtc.service.PopupNtcService;
import incheon.ags.por.service.PorExternalService;
import incheon.ags.por.service.PorMapService;
import incheon.ags.por.service.PorRtmsService;
import incheon.ags.por.util.PorConnectUtils;
import incheon.ags.por.vo.PorEstateResultVO;
import incheon.ags.por.vo.PorEstateVO;
import incheon.ags.por.vo.PorHousePriceResultVO;
import incheon.ags.por.vo.PorLandPriceResultVO;
import incheon.ags.por.vo.PorMapParameterVO;
import incheon.cmm.g2f.basemap.vo.G2FBasemapVO;
import incheon.com.cmm.context.RequestContext;
import incheon.com.cmm.popup.PopupNtcHelper;
import lombok.RequiredArgsConstructor;

/**
 * @ClassName : PorController.java
 * @Description : 공간정보포털 컨트롤러
 *
 * @author : 관리자
 * @since : 2025. 07. 17
 * @version : 1.0
 *
 *          <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일              수정자               수정내용
 *  -------------  ------------   ---------------------
 *   2023. 10. 10    관리자               최초 생성
 *   2024. 12. 19    관리자               패널 기반 플랫폼으로 전면 개편
 *   2025. 07. 17    관리자               공간정보포털로 전환
 *          </pre>
 *
 */
@Controller
@RequestMapping("/sgp/por")
@RequiredArgsConstructor
public class PorMapController {
    @Autowired private ObjectMapper objectMapper;

	private final PorExternalService porExternalService;
	private final PopupNtcService popupNtcService;
	private final PopupNtcHelper popupNtcHelper;
	
	private final String KRAS_KEY = "FSDM-56QX-9V23-M0I8";
	private final String KOREP_KEY = "7SL3-373L-9182-VUXU";
	private final String GDATA_KEY = "n1DnZ0jzoSYKWktPkc4JgdEZC1v+CllJvKt1z7e1BNcxVkZ0GMmGwzFFtT3ELU9FVo9FtQWNcxo5i9z5C7hRaw==";
	
	private String KRAS_URL = "http://101.9.253.211:8385/conn/estateGateway";
	private final String KOREP_URL = "http://10.188.226.157:8502/conn/KOREPS00011";
	private final String GDATA_URL = "https://apis.data.go.kr/1613000/BldRgstHubService/getBrExposPubuseAreaInfo";
	
	private final String KRAS_URL_IMAP = "https://imap.incheon.go.kr/icgisapi/getKras.jsp";
//	private final String KOREP_URL = "http://10.188.226.157:8502/conn/KOREPS00011";
	private final String KOREP_URL_IMAP = "https://imap.incheon.go.kr/icgisapi/getKorep.jsp";
	private final String CAIS_URL_IMAP = "https://imap.incheon.go.kr/icgisapi/getCais.jsp";
	private final String GDATA_URL_IMAP = "https://imap.incheon.go.kr/icgisapi/getGdata.jsp";
	
	private final PorRtmsService porRtmsService;
	private final PorMapService porMapService;
	
	private final PorConnectUtils porConnectUtils;
	
	private static final String SGP_SYS_CD = "SGP";
	
	@Value("${por.klis.api.mode}")
	private String mode;
	
	@Value("${por.cais.api.javapath}")
	private String javapath;
	
	@Value("${por.cais.api.certpath}")
	private String certpath;
	
	@Value("${por.cais.api.jarpath}")
	private String jarpath;
	
//	private final String URL;
	
	/**
     * 통합포탈 메인화면 진입페이지
     * @param model
     * @return JSP 페이지
     * @exception Exception
     */
    @GetMapping("/index.do")
    public String index(HttpServletRequest request, ModelMap model) throws Exception {
    	
    	// 팝업 공지 조회 (SSR) - 공통 헬퍼 사용
        List<Map<String, Object>> allPopups = popupNtcService.selectActivePopupNtcList(SGP_SYS_CD);
        List<Map<String, Object>> popupNtcList = popupNtcHelper.getVisiblePopupList(request, allPopups);
        model.addAttribute("popupNtcList", popupNtcList);
        
        return "sgp/por/index";
    }

		@GetMapping("/usehelp.do")
    public String useHelp(HttpServletRequest request, ModelMap model) throws Exception {
    	
        return "sgp/por/usehelp";
    }
    
    /**
     * 통합포탈 메인화면 진입페이지
     * @param model
     * @return JSP 페이지
     * @exception Exception
     */
    @GetMapping("/main/map.do")
    public String viewMap(ModelMap model) throws Exception {
    	
    	model.addAttribute("mode", mode);
    	
    	String userId = RequestContext.getCurrentUserId();
    	if(userId != null) {
    		model.addAttribute("isManager", true);
    	}else {
    		model.addAttribute("isManager", false);
    	}
    	
    	return "sgp/por/main/map";
    }
    
    /**
     * 인천지도포털 -> 주소취득(이후 바뀔수 있음)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/addr.do")
    @ResponseBody
    public Map<String, Object> addr(
    		@ModelAttribute("lon") String lon
    		, @ModelAttribute("lat") String lat
    		) throws Exception {
    	
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	
    	paramMap.put("path", "https://imap.incheon.go.kr/icgisapi/getAddr.jsp");
    	paramMap.put("query", "type=pnubyxy&x=" + lon + "&y=" + lat + "&pnu=");
    	paramMap.put("method", "GET");
    	
    	Map<String, String> propertiesMap = new HashMap<String, String>();
    	propertiesMap.put("Content-Type", "application/json");
    	
    	paramMap.put("requestProperties", propertiesMap);
    	
    	Map<String, Object> resultMap = porExternalService.connectUrl(paramMap);
    	
    	JSONParser parse = new JSONParser();
		JSONArray obj = (JSONArray) parse.parse(resultMap.get("data").toString());
		resultMap.put("data", obj);
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 주소취득(이후 바뀔수 있음)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/addrInfo.do")
    @ResponseBody
    public Map<String, Object> addrInfo(
    		@ModelAttribute("pnu") String pnu
    		) throws Exception {
		/*
		// 각 구별 조회 IP
		// 중구 (28110)
		this.URL = "http://101.1.4.22:8385/conn/estateGateway";
		// 동구 (28140)
		this.URL = "http://101.2.7.14:8385/conn/estateGateway";
		// 미추홀구 (28177)
		this.URL = "http://101.3.1.129:8385/conn/estateGateway";
		// 연수구 (28185)
		this.URL = "http://101.4.4.20:8385/conn/estateGateway";
		// 남동구 (28200)
		this.URL = "http://101.5.3.33:8385/conn/estateGateway";
		// 부평구 (28237)
		this.URL = "http://101.6.5.20:8385/conn/estateGateway";
		// 계양구 (28245)
		this.URL = "http://101.7.1.50:8385/conn/estateGateway";
		// 서구 (28260)
		this.URL = "http://101.8.27.6:8385/conn/estateGateway";
		// 강화군 (28710)
		this.URL = "http://101.9.253.211:8385/conn/estateGateway";
		// 옹진군 (28720)
		this.URL = "http://101.10.7.30:8385/conn/estateGateway";
		*/
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	
//    	paramMap.put("path", this.URL);
    	// paramMap.put("query", "type=pnubyxy&x=" + lon + "&y=" + lat + "&pnu=");
    	
    	Map<String, String> propertiesMap = new HashMap<String, String>();
    	propertiesMap.put("Content-Type", "application/json");
    	
    	paramMap.put("requestProperties", propertiesMap);
    	
    	Map<String, Object> resultMap = porExternalService.connectUrl(paramMap);
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 토지정보 취득
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/toji.do")
    @ResponseBody
    public Map<String, Object> toji(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		) throws Exception {
    	
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	Map<String, Object> resultMap;
    	
    	// pnu 가공
    	String admSectCd = pnu.substring(0, 5);
        String landLocCd = pnu.substring(5, 10);
        String ledgGbn = pnu.substring(10, 11);
        String bobn = pnu.substring(11, 15);
        String bubn = pnu.substring(15, 19);
        
        // 구별 URL 셋팅
        setKrasUrl(admSectCd);
        
        if(type != null) {
        	// KRAS 연동
        	if(type.equals("kras000030")) {
		        paramMap.put("path", this.KRAS_URL);
		        String query = "conn_sys_id=" + this.KRAS_KEY + "&conn_svc_id=KRAS000030" + "&adm_sect_cd=" + admSectCd + 
			        "&land_loc_cd=" + landLocCd + "&ledg_gbn=" + ledgGbn + "&bobn=" + bobn + "&bubn=" + bubn + 
			        "&map_gbn=1" + "&bldgkindcd=0";
		    	paramMap.put("query", query);
		    	paramMap.put("method", "POST");
		    	Map<String, String> propertiesMap = new HashMap<String, String>();
		    	propertiesMap.put("Content-Type", "application/json");
		    	
		    	paramMap.put("requestProperties", propertiesMap);
		    	resultMap = porExternalService.connectUrl(paramMap);
		    	
		    	String strText = (String) resultMap.get("data");
				
		    	XmlMapper xmlMapper = new XmlMapper();

		    	JsonNode node = xmlMapper.readTree(strText.getBytes());
		    	String json = objectMapper.writeValueAsString(node);
		    	
		    	if(json.contains("&quot;")) {
		    		json = json.replaceAll("&quot;", "\"");
		    	}
		    	
		    	JSONParser parse = new JSONParser();
		    	JSONObject data = (JSONObject) parse.parse(json.toString());

		    	resultMap.put("kras000030", data);
		    	
        	}else if(type.equals("kras000002")) {
        		paramMap.put("path", this.KRAS_URL);
 		        String query = "conn_sys_id=" + this.KRAS_KEY + "&conn_svc_id=KRAS000002" + "&adm_sect_cd=" + admSectCd + 
 			        "&land_loc_cd=" + landLocCd + "&ledg_gbn=" + ledgGbn + "&bobn=" + bobn + "&bubn=" + bubn;
 		    	paramMap.put("query", query);
 		    	paramMap.put("method", "POST");
 		    	Map<String, String> propertiesMap = new HashMap<String, String>();
 		    	propertiesMap.put("Content-Type", "application/json");
 		    	
 		    	paramMap.put("requestProperties", propertiesMap);
 		    	resultMap = porExternalService.connectUrl(paramMap);
 		    	
 		    	String strText = (String) resultMap.get("data");
				
		    	XmlMapper xmlMapper = new XmlMapper();

		    	JsonNode node = xmlMapper.readTree(strText.getBytes());
		    	String json = objectMapper.writeValueAsString(node);
		    	
		    	if(json.contains("&quot;")) {
		    		json = json.replaceAll("&quot;", "\"");
		    	}
		    	
		    	JSONParser parse = new JSONParser();
		    	JSONObject data = (JSONObject) parse.parse(json.toString());

		    	resultMap.put("kras000002", data);
		    	
        	}else if(type.equals("kras000028")) {
	       		paramMap.put("path", this.KRAS_URL);
		        String query = "conn_sys_id=" + this.KRAS_KEY + "&conn_svc_id=KRAS000028" + "&adm_sect_cd=" + admSectCd + 
			        "&land_loc_cd=" + landLocCd + "&ledg_gbn=" + ledgGbn + "&bobn=" + bobn + "&bubn=" + bubn;
		    	paramMap.put("query", query);
		    	paramMap.put("method", "POST");
		    	Map<String, String> propertiesMap = new HashMap<String, String>();
		    	propertiesMap.put("Content-Type", "application/json");
		    	
		    	paramMap.put("requestProperties", propertiesMap);
		    	resultMap = porExternalService.connectUrl(paramMap);
		    	
		    	String strText = (String) resultMap.get("data");
				
		    	XmlMapper xmlMapper = new XmlMapper();

		    	JsonNode node = xmlMapper.readTree(strText.getBytes());
		    	String json = objectMapper.writeValueAsString(node);
		    	
		    	if(json.contains("&quot;")) {
		    		json = json.replaceAll("&quot;", "\"");
		    	}
		    	
		    	JSONParser parse = new JSONParser();
		    	JSONObject data = (JSONObject) parse.parse(json.toString());

		    	resultMap.put("kras000028", data);
		    	
	       	}else if(type.equals("kras000026")) {
	       		paramMap.put("path", this.KRAS_URL);
		        String query = "conn_sys_id=" + this.KRAS_KEY + "&conn_svc_id=KRAS000026" + "&adm_sect_cd=" + admSectCd + 
			        "&land_loc_cd=" + landLocCd + "&ledg_gbn=" + ledgGbn + "&bobn=" + bobn + "&bubn=" + bubn +
			        "&iss_read_gbn=1" + "&fee=0" + "&iss_cnt=1" + "&map_width=355" + "&map_height=355" + 
			        "&legend_width=10" + "&legend_height=10" + "&iss_scale=1200";
		    	paramMap.put("query", query);
		    	paramMap.put("method", "POST");
		    	Map<String, String> propertiesMap = new HashMap<String, String>();
		    	propertiesMap.put("Content-Type", "application/json");
		    	
		    	paramMap.put("requestProperties", propertiesMap);
		    	resultMap = porExternalService.connectUrl(paramMap);
		    	
		    	String strText = (String) resultMap.get("data");
				
		    	XmlMapper xmlMapper = new XmlMapper();

		    	JsonNode node = xmlMapper.readTree(strText.getBytes());
		    	String json = objectMapper.writeValueAsString(node);
		    	
		    	if(json.contains("&quot;")) {
		    		json = json.replaceAll("&quot;", "\"");
		    	}
		    	
		    	JSONParser parse = new JSONParser();
		    	JSONObject data = (JSONObject) parse.parse(json.toString());

		    	resultMap.put("kras000026", data);
	       	}
        	// 공시지가(KOREP)
	       	else if(type.equals("korep")) {
	       		paramMap.put("path", this.KOREP_URL);
	       		String query = "conn_sys_id=" + this.KOREP_KEY + "&conn_svc_id=KOREPS00011" + "&adm_sect_cd=" + admSectCd + 
			        "&land_loc_cd=" + landLocCd + "&ledg_gbn=" + ledgGbn + "&bobn=" + bobn + "&bubn=" + bubn;
	       		paramMap.put("query", query);
	       		paramMap.put("method", "POST");
	       		Map<String, String> propertiesMap = new HashMap<String, String>();
	        	propertiesMap.put("Content-Type", "application/json");
	        	
	        	paramMap.put("requestProperties", propertiesMap);
		    	resultMap = porExternalService.connectUrl(paramMap);
		    	
		    	String xmlText = (String) resultMap.get("data");
		    	
		    	xmlText = unescapeHtml(xmlText);
	    		if(xmlText.substring(0, 1).contains("\"")) {
	    			xmlText = xmlText.replaceFirst("\"", "");
	    		}
	    		xmlText = xmlText.replaceAll("\"$", "");
	    		
	    		
	    		XmlMapper xmlMapper = new XmlMapper();

		    	JsonNode node = xmlMapper.readTree(xmlText.getBytes());
		    	String json = objectMapper.writeValueAsString(node);
		    	
		    	if(json.contains("&quot;")) {
		    		json = json.replaceAll("&quot;", "'");
		    	}
		    	
		    	JSONParser parse = new JSONParser();
		    	JSONObject data = (JSONObject) parse.parse(json.toString());
		    	
	    		resultMap.put("korep", data);
		    	
		    	
	       	}
	       	else {
	       		resultMap = new HashMap<String, Object>();
	       	}
        }else {
        	resultMap = new HashMap<String, Object>();
        }
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 토지정보 취득(시연용)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/toji_temp.do")
    @ResponseBody
    public Map<String, Object> tojiTemp(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		, ModelMap model
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	System.out.println("pnu : " + pnu);
    	System.out.println("@@@@ run toji_panel");
    	
    	// KRAS 연동
    	if(("kras000002").equals(type)) {
			paramMap.put("url", this.KRAS_URL_IMAP);
			paramMap.put("param", "?fn=getListKras000002&pnu=" + pnu);
			JSONObject kras000002 = porConnectUtils.kras(paramMap);
			resultMap.put("kras000002", kras000002);
    	}else if(("kras000026").equals(type)) {
    		paramMap.put("url", this.KRAS_URL_IMAP);
    		paramMap.put("param", "?fn=getListKras000026&pnu=" + pnu);
    		JSONObject kras000026 = porConnectUtils.kras(paramMap);
    		resultMap.put("kras000026", kras000026);
    	}else if(("kras000028").equals(type)) {
    		paramMap.put("url", this.KRAS_URL_IMAP);
    		paramMap.put("param", "?fn=getListKras000028&pnu=" + pnu);
    		JSONObject kras000028 = porConnectUtils.kras(paramMap);
    		resultMap.put("kras000028", kras000028);
    	}else if(("kras000030").equals(type)) {
    		paramMap.put("url", this.KRAS_URL_IMAP);
    		paramMap.put("param", "?fn=getListKras000030&pnu=" + pnu);
    		JSONObject kras000030 = porConnectUtils.kras(paramMap);
    		resultMap.put("kras000030", kras000030);
    	}
    	
		System.out.println("@@@@ close toji_panel");
		
		return resultMap;
    }
    
    /**
     * 인천지도포털 -> 토지정보 취득 (실 서버 접속전까지 임시로 데이터 조회)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/toji_test.do")
    @ResponseBody
    public Map<String, Object> tojiDispose(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	// pnu 가공
		/*String admSectCd = pnu.substring(0, 5);
		String landLocCd = pnu.substring(5, 10);
		String ledgGbn = pnu.substring(10, 11);
		String bobn = pnu.substring(11, 15);
		String bubn = pnu.substring(15, 19);*/
    	
		// KRAS 연동
		JSONParser parse = new JSONParser();
		
		String kras000030Text = porExternalService.kras000030();
		JSONObject kras000030 = (JSONObject) parse.parse(kras000030Text);
		resultMap.put("kras000030", kras000030);
		
		String kras000002Text = porExternalService.kras000002();
		JSONObject kras000002 = (JSONObject) parse.parse(kras000002Text);
		resultMap.put("kras000002", kras000002);
		
		String kras000028Text = porExternalService.kras000028();
		JSONObject kras000028 = (JSONObject) parse.parse(kras000028Text);
		resultMap.put("kras000028", kras000028);
		
		String kras000026Text = porExternalService.kras000026();
		JSONObject kras000026 = (JSONObject) parse.parse(kras000026Text);
		resultMap.put("kras000026", kras000026);
		// 공시지가(KOREP)
		/*else if(type.equals("korep")) {
			text = porExternalService.korep();
			resultMap.put("data", text);
		}*/
    		
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> CAIS 데이터 추출 (JAR를 통한 서비스...caiscall.jar 필요함)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/cais.do")
    @ResponseBody
    public Map<String, Object> cais(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("code") String code
    		, @ModelAttribute("seq") String seq
    		, @ModelAttribute("clsfcd") String clsfcd
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	// 감리대비용으로 작업중 꼬임
		String codeName = "";
		if(("4002").equals(code) || ("4003").equals(code)) {
			codeName = "cais0203";
		}else {
			codeName = "cais" + code;
		}
		
    	try {
	    	List<String> args = new ArrayList<String>();
	    	args.add("java");
	    	args.add("-classpath");
	    	// args.add("d:/cert");
	    	args.add(certpath);
	    	
	    	args.add("-jar");
	    	args.add(certpath + "/caiscall.jar");
	    	
	    	if(code != null) {
	    		String text = "";
	    		if(("4001").equals(code)) {
    				String san = pnu.substring(10, 11);
    				args.add(code);
    				args.add(pnu.substring(0, 5));
    				args.add(pnu.substring(5, 10));
    				args.add(san.equals("1") ? "0" : "1");
    				args.add(pnu.substring(11, 15));
    				args.add(pnu.substring(15, 19));
    			}else {
    				args.add(code);
    				args.add(seq);
    				args.add(clsfcd);
    			}
	    	}
	    	
	    	ProcessBuilder builder = new ProcessBuilder(args);
	    	builder.directory(new File(certpath));
	    	Process process = builder.start();
	    	BufferedReader stdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
	    	
	    	String str = "";
	    	StringBuilder result = new StringBuilder();
	    	
	    	while( (str = stdOut.readLine()) != null ) {
	    		 result.append(str);
	    	}
	    	
	    	stdOut.close();
	    	process.getErrorStream().close();
	    	process.getInputStream().close();
	    	process.getOutputStream().close();
    		
	    	if(("").equals(result.toString())){
	    		JSONObject obj = new JSONObject();
	    		JSONObject rsltCntt = new JSONObject();
	    		rsltCntt.put("rsltCntt", "FAIL");
	    		obj.put("header", rsltCntt);
	    		obj.put("command", String.join(" ", args));
	    		resultMap.put(codeName, obj);
	    	}else {
	    		
	    		String text = result.toString();
	    		if(text != null && text.indexOf("{") > -1) {
	    			text = text.substring(text.indexOf("{"));
	    		}else {
	    			JSONObject obj = new JSONObject();
	        		JSONObject rsltCntt = new JSONObject();
	        		rsltCntt.put("rsltCntt", text);
	        		obj.put("header", rsltCntt);
	        		resultMap.put(codeName, obj);
	        		obj.put("command", String.join(" ", args));
	        		return resultMap;
	    		}
	    		
	    		JSONParser parse = new JSONParser();
	    		JSONObject obj = (JSONObject) parse.parse(text);
	    		JSONObject body = (JSONObject) obj.get("body");
	    		JSONArray list = (JSONArray) body.get("LIST");
	    		for(int i = 0; i < list.size(); i++) {
	    			JSONObject temp = (JSONObject) list.get(i);
	    			temp.put("etcRcdMatr", "");
	    		}
	    		// ???? as-is에서 있는 형태 그대로임...
	    		resultMap.put(codeName, obj);
	    	}
	    	
			/*
			 * args.forEach(arg -> { System.out.println(arg); });
			 */
    	}catch(Exception e) {
    		JSONObject obj = new JSONObject();
    		JSONObject rsltCntt = new JSONObject();
    		rsltCntt.put("rsltCntt", e.getLocalizedMessage());
    		obj.put("header", rsltCntt);
    		resultMap.put(codeName, obj);
    	}
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> CAIS 데이터 추출 (JAR를 통한 서비스...caiscall.jar 필요함)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/cais_temp.do")
    @ResponseBody
    public Map<String, Object> caisTemp(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("code") String code
    		, @ModelAttribute("seq") String seq
    		, @ModelAttribute("clsfcd") String clsfcd
    		, @ModelAttribute("dongNm") String dongNm
    		, @ModelAttribute("pageNo") String pageNo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	if(code != null) {
    		if(code.indexOf("4001") >= 0) {
    			paramMap.put("url", this.CAIS_URL_IMAP);
    			paramMap.put("param", "?code=" + code + "&pnu=" + pnu);
    			JSONObject cais4001 = porConnectUtils.kras(paramMap);
    			resultMap.put("cais4001", cais4001);
    		}else if(code.indexOf("4002") >= 0) {
    			paramMap.put("url", this.CAIS_URL_IMAP);
    			paramMap.put("param", "?code=" + code + "&clsfcd=" + clsfcd + "&seq=" + seq);
    			JSONObject cais4002 = porConnectUtils.kras(paramMap);
    			resultMap.put("cais0203", cais4002);
    		}else if(code.indexOf("4003") >= 0) {
    			paramMap.put("url", this.CAIS_URL_IMAP);
    			paramMap.put("param", "?code=" + code + "&clsfcd=" + clsfcd + "&seq=" + seq);
    			JSONObject cais4003 = porConnectUtils.kras(paramMap);
    			resultMap.put("cais0203", cais4003);
    		}else if(code.indexOf("4004") >= 0) {
    			paramMap.put("url", this.CAIS_URL_IMAP);
    			paramMap.put("param", "?code=" + code + "&clsfcd=" + clsfcd + "&seq=" + seq);
    			JSONObject cais4004 = porConnectUtils.kras(paramMap);
    			resultMap.put("cais4004", cais4004);
    		}else if(code.indexOf("expos") >= 0) {
    			paramMap.put("url", this.GDATA_URL_IMAP);
    			paramMap.put("param", "?type=" + code + "&pnu=" + pnu + "&dongNm=" + dongNm + "&pageNo=" + pageNo);
    			JSONObject cais4004 = porConnectUtils.kras(paramMap);
    			resultMap.put("cais4004", cais4004);
    		}
    	}
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> GDATA 데이터 추출 (전유부)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/Gdata.do")
    @ResponseBody
    public Map<String, Object> Gdata(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		, @ModelAttribute("dongNm") String dongNm
    		, @ModelAttribute("pageNo") String pageNo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	if(type != null) {
    		if(("expos").equals(type)) {
    			paramMap.put("url", this.GDATA_URL);
    			String param = "";
    			param += "?serviceKey=" + URLEncoder.encode(GDATA_KEY, "UTF-8");
    			param += "&numOfRows=100";
    			param += "&_type=json";
    			param += "&pageNo=" + pageNo;
    			param += "&sigunguCd=" + pnu.substring(0, 5);
    			param += "&bjdongCd=" + pnu.substring(5, 10);
    			param += "&bun=" + pnu.substring(11, 15);
    			param += "&ji=" + pnu.substring(15, 19);
    			if(!("").equals(dongNm)) {
    				param += "&dongNm=" + URLEncoder.encode(dongNm, "UTF-8");
    			}
    			paramMap.put("param", param);
    			JSONObject Gdata = new JSONObject();
    			try {
    				Gdata = porConnectUtils.ssl(paramMap);
    			}catch(Exception e) {
    				resultMap.put("Gdata", Gdata);
    				resultMap.put("errorMessage", e.getLocalizedMessage());
    			}
    			resultMap.put("Gdata", Gdata);
    		}
    	}
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> GDATA 데이터 추출 (전유부)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/Gdata_temp.do")
    @ResponseBody
    public Map<String, Object> GdataTemp(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		, @ModelAttribute("dongNm") String dongNm
    		, @ModelAttribute("pageNo") String pageNo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	if(type != null) {
    		if(type.indexOf("expos") >= 0) {
    			paramMap.put("url", this.GDATA_URL_IMAP);
    			paramMap.put("param", "?type=" + type + "&pnu=" + pnu + "&dongNm=" + dongNm + "&pageNo=" + pageNo);
    			JSONObject Gdata = porConnectUtils.kras(paramMap);
    			resultMap.put("Gdata", Gdata);
    		}
    	}
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> KOREP 데이터 추출 (공시지가)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/korep.do")
    @ResponseBody
    public Map<String, Object> korep(
    		@ModelAttribute("pnu") String pnu
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	if(pnu != null) {
			paramMap.put("url", this.KOREP_URL);
			paramMap.put("param", "?pnu=" + pnu);
			String korep = porConnectUtils.korep(paramMap);
			resultMap.put("korep", korep);
    	}
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> KOREP 데이터 추출 (공시지가)
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/korep_temp.do")
    @ResponseBody
    public Map<String, Object> korepTemp(
    		@ModelAttribute("pnu") String pnu
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	if(pnu != null) {
    		paramMap.put("url", this.KOREP_URL_IMAP);
    		paramMap.put("param", "?pnu=" + pnu);
    		String korep = porConnectUtils.korep(paramMap);
    		
    		korep = unescapeHtml(korep);
    		if(korep.substring(0, 1).contains("\"")) {
    			korep = korep.replaceFirst("\"", "");
    		}
    		korep = korep.replaceAll("\"$", "");
    		
    		
	    	XmlMapper xmlMapper = new XmlMapper();

	    	JsonNode node = xmlMapper.readTree(korep.getBytes());
	    	String json = objectMapper.writeValueAsString(node);
	    	
	    	if(json.contains("&quot;")) {
	    		json = json.replaceAll("&quot;", "'");
	    	}
	    	
	    	JSONParser parse = new JSONParser();
	    	JSONObject data = (JSONObject) parse.parse(json.toString());
	    	
    		resultMap.put("korep", data);
    	}
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 실거래가 취득
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/estate.do")
    @ResponseBody
    public Map<String, Object> estate(
    		@ModelAttribute PorEstateVO vo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
		String buildType = vo.getBuldType();
		
		vo.setBuldType("all");
		if(("shouse").equals(vo.getBuldType())) {
			vo.setBldgNm("단독/다가구주택");
		}
//		vo.setPnu("2817710400106010001");
		System.out.println(vo);
		
		List<PorEstateResultVO> result = null;
		if(("1").equals(vo.getEstateType())) {
			result = porRtmsService.selectRtmsTradeList(vo);
		}else if(("2").equals(vo.getEstateType())) {
			result = porRtmsService.selectRtmsCharterList(vo);
		}else if(("3").equals(vo.getEstateType())) {
			result = porRtmsService.selectRtmsRentalList(vo);
	    }else if(("4").equals(vo.getEstateType())) {
	    	result = porRtmsService.selectRtmsPresaleList(vo);
	    }
		
		resultMap.put("data", result);
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 주택가격정보 취득
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/info/ahpd.do")
    @ResponseBody
    public Map<String, Object> ahdp(
    		@ModelAttribute PorMapParameterVO vo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	String pnu = vo.getPnu();
    	
    	List<PorHousePriceResultVO> result = porMapService.selectHousePriceList(pnu);
    	
    	resultMap.put("data", result);
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 주택가격정보 취득
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/info/landPrice.do")
    @ResponseBody
    public Map<String, Object> landprice(
    		@ModelAttribute PorMapParameterVO vo
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	String pnu = vo.getPnu();
    	
    	List<PorLandPriceResultVO> result = porMapService.selectLandPriceList(pnu);
    	
    	resultMap.put("data", result);
    	
    	return resultMap;
    }
    
    /**
     * 인천지도포털 -> 과거지도리스트 취득
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/past.do")
    @ResponseBody
    public Map<String, Object> past(
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	List<G2FBasemapVO> result = porMapService.selectPastMapList();
    	
    	resultMap.put("data", result);
    	
    	return resultMap;
    }
    
    /**
     * 지도팝업 띄우기
     * @param model
     * @return JSP 페이지
     * @exception Exception
     */
    @GetMapping("/info/loadMap.do")
    public String loadMap(@ModelAttribute("lon") String lon
    		, @ModelAttribute("lat") String lat
    		, ModelMap model) throws Exception {
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	
    	model.addAttribute("lon", lon);
    	model.addAttribute("lat", lat);
    	
    	return "sgp/por/info/loadMap";
    }

    
    
    /**
     * 인천지도포털 -> 토지정보 팝업
     * @param model
     * @return jsonData
     * @exception Exception
     */
    @GetMapping("/map/toji_popup.do")
    public String tojiPopup(
    		@ModelAttribute("pnu") String pnu
    		, ModelMap model
    		) throws Exception {
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
    	model.addAttribute("mode", mode);
    	System.out.println("mode : " + mode);
    	
    	// KRAS 연동
		/*if(("kras000002").equals(type)) {
			paramMap.put("url", this.KRAS_URL_IMAP);
			paramMap.put("param", "?fn=getListKras000002&pnu=" + pnu);
			JSONObject kras000002 = porConnectUtils.kras(paramMap);
			resultMap.put("kras000002", kras000002);
		}else if(("kras000026").equals(type)) {
			paramMap.put("url", this.KRAS_URL_IMAP);
			paramMap.put("param", "?fn=getListKras000026&pnu=" + pnu);
			JSONObject kras000026 = porConnectUtils.kras(paramMap);
			resultMap.put("kras000026", kras000026);
		}else if(("kras000028").equals(type)) {
			paramMap.put("url", this.KRAS_URL_IMAP);
			paramMap.put("param", "?fn=getListKras000028&pnu=" + pnu);
			JSONObject kras000028 = porConnectUtils.kras(paramMap);
			resultMap.put("kras000028", kras000028);
		}else if(("kras000030").equals(type)) {
			paramMap.put("url", this.KRAS_URL_IMAP);
			paramMap.put("param", "?fn=getListKras000030&pnu=" + pnu);
			JSONObject kras000030 = porConnectUtils.kras(paramMap);
			resultMap.put("kras000030", kras000030);
		}*/
    	
		return "sgp/por/popups/tojiPopup";
    }
    
    
    private void setKrasUrl(String pnu) {
    	if(("28110").equals(pnu)) {
	    	// 중구 (28110)
			this.KRAS_URL = "http://101.1.4.22:8385/conn/estateGateway";
    	}else if(("28140").equals(pnu)) {
			// 동구 (28140)
			this.KRAS_URL = "http://101.2.7.14:8385/conn/estateGateway";
    	}else if(("28177").equals(pnu)) {
			// 미추홀구 (28177)
			this.KRAS_URL = "http://101.3.1.129:8385/conn/estateGateway";
    	}else if(("28185").equals(pnu)) {
			// 연수구 (28185)
			this.KRAS_URL = "http://101.4.4.20:8385/conn/estateGateway";
    	}else if(("28200").equals(pnu)) {
			// 남동구 (28200)
			this.KRAS_URL = "http://101.5.3.33:8385/conn/estateGateway";
    	}else if(("28237").equals(pnu)) {
			// 부평구 (28237)
			this.KRAS_URL = "http://101.6.5.20:8385/conn/estateGateway";
    	}else if(("28245").equals(pnu)) {
			// 계양구 (28245)
			this.KRAS_URL = "http://101.7.1.50:8385/conn/estateGateway";
    	}else if(("28260").equals(pnu)) {
			// 서구 (28260)
			this.KRAS_URL = "http://101.8.27.6:8385/conn/estateGateway";
    	}else if(("28710").equals(pnu)) {
			// 강화군 (28710)
			this.KRAS_URL = "http://101.9.253.211:8385/conn/estateGateway";
    	}else if(("28720").equals(pnu)) {
			// 옹진군 (28720)
			this.KRAS_URL = "http://101.10.7.30:8385/conn/estateGateway";
    	}
    }
    
    private String unescapeHtml(String str) {
    	if(str == null) {
    		return "";
    	}
    	
    	str = str.replaceAll("\\\\", "");
    	str = str.replaceAll("&amp;", "&");
    	str = str.replaceAll("&lt;", "<");
    	str = str.replaceAll("&gt;", ">");
    	str = str.replaceAll("&quot;", "\"");
    	str = str.replaceAll("&#039;", "'");
    	str = str.replaceAll("&#39;", "'");
    	
    	return str;
    }
    
    
    
    /**
     * gdata 테스트용 페이지 호출
     * @param model
     * @return JSP 페이지
     * @exception Exception
     */
    @GetMapping("/gdataSample.do")
    public String gdataSample(HttpServletRequest request, ModelMap model) throws Exception {
    	
        return "sgp/por/gdataSample";
    }
    
    /**
     * gdata 테스트용 페이지 호출
     * @param model
     * @return JSP 페이지
     * @exception Exception
     */
    @GetMapping("/gdataTest.do")
    @ResponseBody
    public Map<String, Object> gdataTest(
    		@ModelAttribute("pnu") String pnu
    		, @ModelAttribute("type") String type
    		, @ModelAttribute("dongNm") String dongNm
    		, @ModelAttribute("pageNo") String pageNo
    		
    		, @ModelAttribute("method") String method
    		, @ModelAttribute("accept") String accept
    		, @ModelAttribute("contentType") String contentType
    		, @ModelAttribute("protocol") String protocol
    		, ModelMap model) throws Exception {
    	Map<String, String> paramMap = new HashMap<String, String>();
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	
		paramMap.put("url", this.GDATA_URL);
		String param = "";
		param += "?serviceKey=" + URLEncoder.encode(GDATA_KEY, "UTF-8");
		param += "&numOfRows=100";
		param += "&_type=json";
		param += "&pageNo=" + pageNo;
		param += "&sigunguCd=" + pnu.substring(0, 5);
		param += "&bjdongCd=" + pnu.substring(5, 10);
		param += "&bun=" + pnu.substring(11, 15);
		param += "&ji=" + pnu.substring(15, 19);
		if(!("").equals(dongNm)) {
			param += "&dongNm=" + URLEncoder.encode(dongNm, "UTF-8");
		}
		paramMap.put("param", param);
		
		paramMap.put("method", method);
		paramMap.put("accept", accept);
		paramMap.put("contentType", contentType);
		paramMap.put("protocol", protocol);
		JSONObject Gdata = new JSONObject();
		try {
			Gdata = porConnectUtils.sslTest(paramMap);
		}catch(Exception e) {
			resultMap.put("Gdata", Gdata);
			resultMap.put("errorMessage", e.getLocalizedMessage());
		}
		resultMap.put("Gdata", Gdata);
    	
    	return resultMap;
    }
    
}