package itn.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.JsonObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import itn.com.uss.olh.hpc.service.HackIpService;
import itn.com.uss.olh.hpc.service.HackIpVO;
import itn.let.lett.service.LetterService;
import itn.let.lett.service.LetterVO;
import itn.let.mjo.pay.service.MjonPayVO;
import itn.let.schdlr.service.SchdlrManageService;
import itn.let.schdlr.service.SchedulerUtil;
import itn.let.uss.ion.cnt.service.CntManageVO;
import itn.let.uss.ion.cnt.service.EgovCntManageService;

@Controller
public class ContentController{

	@Resource(name = "egovCntManageService")
	private EgovCntManageService egovCntManageService;
	
	@Resource(name = "hackIpService")
	private HackIpService hackIpService;
	
	@Resource(name = "SchdlrManageService")
    private SchdlrManageService schdlrManageService;
	
	@Resource(name = "LetterService")
    private LetterService letterService;

	
	/*인사말*/
	@RequestMapping(value="/web/intro/intro.do")
    public String intro(@RequestParam Map<String, Object> commandMap, Model model) throws Exception {  
    	//selectNaviList(68, model);
    	return  "/web/intro/intro";
    }

	/* content*/
	@RequestMapping(value="/web/content.do")
    public String contentIntro(@RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
		if(commandMap.get("proFn")==null){
			return "blank";
		}
		cntManageVO.setProgrmFileNm((String)commandMap.get("proFn"));
		cntManageVO = egovCntManageService.selectContentVo(cntManageVO);
		if(cntManageVO==null){ //매뉴에 등록되지 않았으면 cnt_manage 에서라도 가져옴.(proFn 으로 무조건 content 가져옴)
			cntManageVO = new CntManageVO();
			cntManageVO.setProgrmFileNm((String)commandMap.get("proFn"));
			cntManageVO = egovCntManageService.selectContentByProFn(cntManageVO) ;
			if(cntManageVO == null){
				return "blank";
			}
			return "cnt/"+cntManageVO.getCntId() ;
		}
		
		if(cntManageVO.getMenuCours()!=null){ //매뉴구조
			cntManageVO.setMenuCours(cntManageVO.getMenuCours().replace("|" , " > "));
		}
		
		if(null != commandMap.get("proFn")) {
			cntManageVO.setMenuNo((String)commandMap.get("proFn"));
		}
		
		model.addAttribute("cntManageVO", cntManageVO);
		String sLocationUrl = "cnt/"+cntManageVO.getCntId();
		return sLocationUrl ;
    }
	
	/* 관리자 컨텐츠 content*/
	@RequestMapping(value="/web/adminContent.do")
    public String adminContent(@RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
    	//selectNaviList(68, model);
		String tempCntDtId = "" ;
		if(cntManageVO.getCntDtId() != null){  //관리자 미리보기 화면
			tempCntDtId = cntManageVO.getCntDtId();
			//cntManageVO = egovCntManageService.selectContentByCntDtId(cntManageVO);
			cntManageVO = egovCntManageService.selectCntDtDetail(cntManageVO);
			if(cntManageVO!=null){ 
				if(cntManageVO.getMenuCours()!=null){ //매뉴구조
					cntManageVO.setMenuCours(cntManageVO.getMenuCours().replace("|" , " > "));
				}	
			}
			
			if(cntManageVO.getCntCn().contains("bbsLoad")) {
				cntManageVO.setCntCn(cntManageVO.getCntCn().replace("id=\"bbsLoad\"" , ""));
			}
			model.addAttribute("cntManageVO", cntManageVO);
			
		}
		String sLocationUrl = "cntsource/ckeditorPriview";
		return sLocationUrl ;
    }
	
	/* 관리자 컨텐츠 content*/
	@RequestMapping(value="/{siteId}/web/adminContent.do")
    public String siteAdminContent(@PathVariable("siteId") String siteId, @RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
    	//selectNaviList(68, model);
		String tempCntDtId = "" ;
		if(cntManageVO.getCntDtId() != null){  //관리자 미리보기 화면
			tempCntDtId = cntManageVO.getCntDtId();
			//cntManageVO = egovCntManageService.selectContentByCntDtId(cntManageVO);
			cntManageVO = egovCntManageService.selectCntDtDetail(cntManageVO);
			if(cntManageVO!=null){ 
				if(cntManageVO.getMenuCours()!=null){ //매뉴구조
					cntManageVO.setMenuCours(cntManageVO.getMenuCours().replace("|" , " > "));
				}	
			}
			
			model.addAttribute("cntManageVO", cntManageVO);
			
		}
		String sLocationUrl = "cntsource/ckeditorPriview";
		return sLocationUrl ;
    }
	
	
	/* 컨텐츠 등록시 실제 파일로 테스트 해봄*/
	@RequestMapping(value="/web/contentTemp.do")
    public String contentTempWrite(@RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
		cntManageVO.setMenuCours("기관소개|인사말".replace("|" , " > "));
		model.addAttribute("cntManageVO", cntManageVO);
		return "cntsource/contentTemp";
    }
	
	
	/* 컨텐츠 에디터 미리보기 해봄*/
	@RequestMapping(value="/web/ckeditorPriview.do")
	public String ckeditorPriview(@RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
		model.addAttribute("cntManageVO", cntManageVO);
		String sLocationUrl = "cntsource/ckeditorPriview";
		return sLocationUrl ;
    }
	
	/* 컨텐츠 에디터 미리보기 해봄*/
	@RequestMapping(value="/{siteId}/web/ckeditorPriview.do")
	public String siteCkeditorPriview(@PathVariable("siteId") String siteId , @RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
		model.addAttribute("cntManageVO", cntManageVO);
		String sLocationUrl = "cntsource/siteIdCkeditorPriview";
		return sLocationUrl ;
    }
	
	/* siteId content*/
	@RequestMapping(value="/{siteId}/web/content.do")
    public String siteContentIntro(@PathVariable("siteId") String siteId ,@RequestParam Map<String, Object> commandMap, CntManageVO cntManageVO , HttpServletRequest request, Model model) throws Exception {  
		if(commandMap.get("proFn")==null){
			return "blank";
		}
		cntManageVO.setProgrmFileNm((String)commandMap.get("proFn"));
		cntManageVO.setSiteId(""); //수퍼 관리자 등록시 siteId 안들어감.
		cntManageVO = egovCntManageService.selectContentVo(cntManageVO);
		if(cntManageVO==null){ //매뉴에 등록되지 않았으면 cnt_manage 에서라도 가져옴.(proFn 으로 무조건 content 가져옴)
			cntManageVO = new CntManageVO();
			cntManageVO.setProgrmFileNm((String)commandMap.get("proFn"));
			cntManageVO = egovCntManageService.selectContentByProFn(cntManageVO) ;
			if(cntManageVO == null){
				return "blank";
			}
			return "cnt/"+cntManageVO.getCntId() ;
		}
		
		if(cntManageVO.getMenuCours()!=null){ //매뉴구조
			cntManageVO.setMenuCours(cntManageVO.getMenuCours().replace("|" , " > "));
		}
		
		model.addAttribute("cntManageVO", cntManageVO);
		model.addAttribute("siteId", siteId);
        String siteFolder = "site/"+siteId ;
        model.addAttribute("site_path", "/"+siteFolder);
		String sLocationUrl = "cnt/"+cntManageVO.getCntId();
		return sLocationUrl ;
    }
	
	/* siteId content*/
	@RequestMapping(value="/web/pop/infoPop.do")
    public String siteContentIntro(@ModelAttribute CntManageVO cntManageVO, HttpServletRequest request, Model model) throws Exception {  
		String test = cntManageVO.getPageType();
		
		model.addAttribute("pageType", test);
		 
 		return "/web/pop/infoListPop";
    }
	
	
	/**
     * 금융결제원 통합API포털 Callback URL
     * @param kisaVO
     * @param model
     * @return modelAndView
     * @throws Exception
     * /web/bank/bankingApiCallbackAjax.do
     */
	@RequestMapping(value = {"/web/bank/bankingApiCallbackAjax.do"})
	public ModelAndView updateKisaAjax(
			HttpServletRequest request
			, String code) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		modelAndView.addObject("code", code);
		return modelAndView;
	}	
	

	// 금융결제원 통합API포털 호출
	@RequestMapping(value="/web/bank/bankingRealNameApiAccessTokenAjax.do")
	public ModelAndView bankingRealNameApiAccessTokenAjax(@ModelAttribute("mjonPayVO") MjonPayVO mjonPayVO, 
			HttpServletRequest request) throws Exception {

		boolean isSuccess = true;
		String msg = "";
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String rspCode = "";			// 최종 return 될 코드 값 Ex) O0002
		String rspMessage = "";			// 최종 return 될 메시지 값 Ex) Access Token 거부		
		String accessToken = "";		// 토큰값
		String accountHolderName = "";	// 예금주명

		try {
			// Step 1. Get Token
			String client_id = "";
			String client_secret = "";
			String scope = "oob";
			String grant_type = "client_credentials";
			String bodyParams = "client_id=" + client_id + "&client_secret=" + client_secret + "&scope=" + scope + "&grant_type=" + grant_type;
			// Unirest.post
	        HttpResponse<String> response = Unirest.post("https://testapi.openbanking.or.kr/oauth/2.0/token")
	                .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
	                .header("cache-control", "no-cache")	                
	                .body(bodyParams)
	                .asString();
	        System.out.println("Step1 Web Response : " + response.getBody().toString());
	        
	        // Response Parshing
	        JSONParser jsonParser = new JSONParser();
	        JSONObject jsonObject = (JSONObject) jsonParser.parse(response.getBody().toString()); 
	        accessToken = jsonObject.get("access_token").toString();
			System.out.println("accessToken :: " + accessToken);			
			
			// Step 2. Real Name Check
			Date now = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String nowTime = sdf.format(now);
			SimpleDateFormat sdf2 = new SimpleDateFormat("ddHHmmss");
			String nowTime2 = sdf2.format(now);
			
			String bankCode = "";		// 은행코드
			switch(mjonPayVO.getBankNm()) {
	        case "국민은행" : 
	        	bankCode = "004"; 
	            break;
	        case "기업은행" : 
	        	bankCode = "003"; 
	            break;
	        case "농협은행" : 
	        	bankCode = "011"; 
	            break;
	        case "신한은행" : 
	        	bankCode = "088"; 
	            break;
	        case "우리은행" : 
	        	bankCode = "020"; 
	            break;
	        case "하나은행" : 
	        	bankCode = "081"; 
	            break;
	        case "카카오뱅크" : 
	        	bankCode = "090"; 
	            break;	            
		    }			
			
			String bank_tran_id = "이용기관코드" + nowTime2 + "Z";	// 은행거래번호 (이용기관코드 => Ex:M000000000U) + 일련번호)           
			String bank_code_std = bankCode;				// 은행코드
			String account_num = mjonPayVO.getAccountNum();		// 계좌번호
			String account_holder_info_type = " ";		// 생년월일 비교방식
			String account_holder_info = mjonPayVO.getBirthDate();		// 생년월일
			String tran_dtime = nowTime;
			
			JsonObject params = new JsonObject();
			params.addProperty("bank_tran_id", bank_tran_id);
			params.addProperty("bank_code_std", bank_code_std);
			params.addProperty("account_num", account_num);
			params.addProperty("account_holder_info_type", account_holder_info_type);
			params.addProperty("account_holder_info", account_holder_info);
			params.addProperty("tran_dtime", tran_dtime);
			
			// Unirest.post
	        HttpResponse<String> response2 = Unirest.post("https://testapi.openbanking.or.kr/v2.0/inquiry/real_name")
	                .header("content-type", "application/json; charset=UTF-8")
	                .header("cache-control", "no-cache")
	                .header("Authorization", "Bearer " + accessToken)
	                .body(params.toString())
	                .asString();
	        //System.out.println("Step1 Web Response : " + response2.getBody().toString());
	        
	        // Response Parshing
	        JSONParser jsonParser2 = new JSONParser();
	        JSONObject jsonObject2 = (JSONObject) jsonParser2.parse(response2.getBody().toString()); 
	        rspCode = jsonObject2.get("rsp_code").toString();
	        rspMessage = jsonObject2.get("rsp_message").toString();
	        accountHolderName = jsonObject2.get("account_holder_name").toString();
	        
	        
	        System.out.println("rspCode :: " + rspCode);
			System.out.println("rspMessage :: " + rspMessage);			
			
		} catch (UnirestException e) {
			isSuccess = false;
			msg = e.getMessage();
		}

		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("rspCode", rspCode);
		modelAndView.addObject("rspMessage", rspMessage);
		modelAndView.addObject("accountHolderName", accountHolderName);
		
		return modelAndView;		
	}			
	
	/**
     * Whois 국가코드 Check
     * @param kisaVO
     * @param model
     * @return modelAndView
     * @throws Exception
     * https://www.data.go.kr => itn0202 계정 인코딩된 서비스키 사용
     */	
	@RequestMapping(value="/web/whois/whoisIpCountryAjax.do")
	public ModelAndView whoisIpCountryAjax( 
			HttpServletRequest request) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		String response = "";
		String result = "";
		String whois = "";
		String rspCode = "";
		String countryCode = "";		// 국가코드
        StringBuilder sb = new StringBuilder();
        
		try {
		    String ipAddress = request.getHeader("X-Forwarded-For") == null ? request.getHeader("X-Forwarded-For") : request.getHeader("X-Forwarded-For").replaceAll("10.12.107.11", "").replaceAll(",", "").trim();
		    if (ipAddress == null) {
		    	ipAddress = request.getRemoteAddr();
		    }
			
		    //ipAddress = "219.240.88.15";	// 국내IP
		    //ipAddress = "102.216.212.0";	// 해외IP
		    //ipAddress = "58.236.220.240";
		    System.out.println("ipAddress :: " + ipAddress);
		    
		    // IP Check
		    if (StringUtils.isNotEmpty(ipAddress) && !ipAddress.equals("127.0.0.1") && !ipAddress.equals("0:0:0:0:0:0:0:1")) {

		    	StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/B551505/whois/ipas_country_code");
		    	// 인코딩된 서비스키
		        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=aEjBXkHxYU%2FVrzFOU22Zqujv8JEFJ0y2AmmxqkEv0O411NTNcpE2FbwvD7BxbG0sbepQbNp0%2FVj7HwbrrwV%2FOA%3D%3D"); 
		        urlBuilder.append("&" + URLEncoder.encode("query","UTF-8") + "=" + URLEncoder.encode(ipAddress, "UTF-8"));
		        urlBuilder.append("&" + URLEncoder.encode("answer","UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8"));
				
		        URL url = new URL(urlBuilder.toString());
		        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		        conn.setRequestMethod("GET");
		        conn.setRequestProperty("Content-type", "application/json");
		        //System.out.println("Response code: " + conn.getResponseCode());
		        BufferedReader rd;
		        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
		            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		        } else {
		            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		        }
		        String line;
		        while ((line = rd.readLine()) != null) {
		            sb.append(line);
		        }
		        rd.close();
		        conn.disconnect();
		        //System.out.println("Return: " + sb.toString());
		        
		        // 전달받은 데이터 파싱
		        JSONParser jsonParser = new JSONParser();
		        JSONObject jsonObject = (JSONObject) jsonParser.parse(sb.toString()); 
		        response = jsonObject.get("response").toString();
		        
		        JSONParser jsonParser2 = new JSONParser();
		        JSONObject jsonObject2 = (JSONObject) jsonParser2.parse(response.toString()); 
		        result = jsonObject2.get("result").toString();
		        
		        JSONParser jsonParser3 = new JSONParser();
		        JSONObject jsonObject3 = (JSONObject) jsonParser3.parse(result.toString()); 
		        rspCode = jsonObject3.get("result_code").toString();
		        
		        JSONParser jsonParser22 = new JSONParser();
		        JSONObject jsonObject22 = (JSONObject) jsonParser22.parse(response.toString()); 
		        whois = jsonObject22.get("whois").toString();
		        
		        JSONParser jsonParser33 = new JSONParser();
		        JSONObject jsonObject33 = (JSONObject) jsonParser33.parse(whois.toString()); 
		        countryCode = jsonObject33.get("countryCode").toString();		        
		        
		        System.out.println("rspCode :: " + rspCode);
		        System.out.println("countryCode :: " + countryCode);		    			        
		    }
		    else {
				isSuccess = false;
				msg = "ipNoCheck";		    	
		    }
		} catch (Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}

		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("rspCode", rspCode);
		modelAndView.addObject("countryCode", countryCode);
		
		return modelAndView;		
	}	
	
	/**
     * Whois 국가코드 Check
     * @param kisaVO
     * @param model
     * @return modelAndView
     * @throws Exception
     * https://www.data.go.kr => itn0202 계정 인코딩된 서비스키 사용
     */	
	@RequestMapping(value="/web/ipAjax.do")
	public ModelAndView ipAjax( 
			HttpServletRequest request
			, String ip) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		String response = "";
		String result = "";
		String whois = "";
		String rspCode = "";
		String countryCode = "";		// 국가코드
        StringBuilder sb = new StringBuilder();
		String ipAddress = ip;

		try {
		    System.out.println("ipAddress :: " + ipAddress);
		    
		    // IP Check
		    if (StringUtils.isNotEmpty(ipAddress) && !ipAddress.equals("127.0.0.1") && !ipAddress.equals("0:0:0:0:0:0:0:1")) {

		    	StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/B551505/whois/ipas_country_code");
		    	// 인코딩된 서비스키
		        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=aEjBXkHxYU%2FVrzFOU22Zqujv8JEFJ0y2AmmxqkEv0O411NTNcpE2FbwvD7BxbG0sbepQbNp0%2FVj7HwbrrwV%2FOA%3D%3D"); 
		        urlBuilder.append("&" + URLEncoder.encode("query","UTF-8") + "=" + URLEncoder.encode(ipAddress, "UTF-8"));
		        urlBuilder.append("&" + URLEncoder.encode("answer","UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8"));
				
		        URL url = new URL(urlBuilder.toString());
		        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		        conn.setRequestMethod("GET");
		        conn.setRequestProperty("Content-type", "application/json");
		        //System.out.println("Response code: " + conn.getResponseCode());
		        BufferedReader rd;
		        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
		            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		        } else {
		            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		        }
		        String line;
		        while ((line = rd.readLine()) != null) {
		            sb.append(line);
		        }
		        rd.close();
		        conn.disconnect();
		        //System.out.println("Return: " + sb.toString());
		        
		        // 전달받은 데이터 파싱
		        JSONParser jsonParser = new JSONParser();
		        JSONObject jsonObject = (JSONObject) jsonParser.parse(sb.toString()); 
		        response = jsonObject.get("response").toString();
		        
		        JSONParser jsonParser2 = new JSONParser();
		        JSONObject jsonObject2 = (JSONObject) jsonParser2.parse(response.toString()); 
		        result = jsonObject2.get("result").toString();
		        
		        JSONParser jsonParser3 = new JSONParser();
		        JSONObject jsonObject3 = (JSONObject) jsonParser3.parse(result.toString()); 
		        rspCode = jsonObject3.get("result_code").toString();
		        
		        JSONParser jsonParser22 = new JSONParser();
		        JSONObject jsonObject22 = (JSONObject) jsonParser22.parse(response.toString()); 
		        whois = jsonObject22.get("whois").toString();
		        
		        JSONParser jsonParser33 = new JSONParser();
		        JSONObject jsonObject33 = (JSONObject) jsonParser33.parse(whois.toString()); 
		        countryCode = jsonObject33.get("countryCode").toString();		        
		        
		        System.out.println("rspCode :: " + rspCode);
		        System.out.println("countryCode :: " + countryCode);		    			        
		    }
		    else {
				isSuccess = false;
				msg = "ipNoCheck";		    	
		    }
		} catch (Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}

		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("rspCode", rspCode);
		modelAndView.addObject("ipAddress", ipAddress);
		modelAndView.addObject("countryCode", countryCode);
		
		return modelAndView;		
	}
	
	// 차단IP 여부
	@RequestMapping(value = "/web/whois/ignoreIpCntAjax.do")
	public ModelAndView ignoreIpCntAjax(
			@ModelAttribute("hackIpVO") HackIpVO hackIpVO
			, HttpServletRequest request) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");

		boolean isSuccess = true;
		String msg = "";
		int ignoreIpCnt = 0;

		// 0:0:0:0:0:0:0:1
		String ipAddress = request.getHeader("X-Forwarded-For") == null ? request.getHeader("X-Forwarded-For") : request.getHeader("X-Forwarded-For").replaceAll("10.12.107.11", "").replaceAll(",", "").trim();
	    if (ipAddress == null) {
	    	ipAddress = request.getRemoteAddr();
	    }
		
        try {
		    hackIpVO.setIgnoreIp(ipAddress);
        	ignoreIpCnt = hackIpService.selectIgnoreIpCnt(hackIpVO);
			
		}
		catch(Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}		

		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("ipAddress", ipAddress);
		modelAndView.addObject("ignoreIpCnt", ignoreIpCnt);
		
		return modelAndView;
	}	    		
	
	/**
	 * IP Block 화면
	 * @param request
	 * @param model
	 * @param addrVO
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/block/blockAjax.do")
	public String blockAjax(HttpServletRequest request, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");

		// 0:0:0:0:0:0:0:1
		String ipAddress = request.getHeader("X-Forwarded-For") == null ? request.getHeader("X-Forwarded-For") : request.getHeader("X-Forwarded-For").replaceAll("10.12.107.11", "").replaceAll(",", "").trim();
	    if (ipAddress == null) {
	    	ipAddress = request.getRemoteAddr();
	    }
		
		model.addAttribute("ipAddress", ipAddress);
		
		return "/block/Block";
	}
	
	/*서비스소개*/
	@RequestMapping(value="/web/info/mjonInfo.do")
    public String mjonInfo(@RequestParam Map<String, Object> commandMap, Model model) throws Exception {  
		
    	//selectNaviList(68, model);
		System.out.println("=====================mjonInfo");
		model.addAttribute("url", "mjonInfo");
    	return  "/cnt/mjonInfo";
    }
	
	/*주요기능*/
	@RequestMapping(value="/web/info/mjonFunc.do")
	public String mjonFunc(@RequestParam Map<String, Object> commandMap, Model model) throws Exception {  
		//selectNaviList(68, model);
		System.out.println("=====================mjonFunc");
		model.addAttribute("url", "mjonFunc");
		return  "/cnt/mjonFunc";
	}
	
	@RequestMapping(value = "/web/main/mainTest.do")
	public String mainTest(HttpServletRequest request, ModelMap model, HttpSession session, 
			@RequestParam(value="message", defaultValue="0") String message, LetterVO letterVO) throws Exception{
		
		return "web/main/mainTest";
	}
	
	// 배너 클릭 업데이트
	@RequestMapping(value= {"/web/main/bannerClickUpdateAjax.do"})
	public ModelAndView bannerClickUpdate(HttpServletRequest request,
			ModelMap model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {
			String mCode		= request.getParameter("mCode");
			String bCode		= request.getParameter("bCode");

    		System.out.println("#############################################################");
			System.out.println("mCode : " + mCode);
			System.out.println("bCode : " + bCode);

    	}
		catch(Exception e) {
			isSuccess = false;
    		msg = e.getMessage();
    	}
			
		modelAndView.addObject("isSuccess", isSuccess);        		
		modelAndView.addObject("msg", msg);

		return modelAndView;
	} 		
	
	// 전용계좌 스케줄러 실행
	@RequestMapping(value= {"/web/main/vacsAutoChargeAjax.do"})
	public ModelAndView vacsAutoCharge(HttpServletRequest request,
			ModelMap model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {

			schdlrManageService.vacsAutoCharge();

    	}
		catch(Exception e) {
			isSuccess = false;
    		msg = e.getMessage();
    	}
			
		modelAndView.addObject("isSuccess", isSuccess);        		
		modelAndView.addObject("msg", msg);

		return modelAndView;
	} 			

	/*
	@Resource(name = "mberGrdService")
	MberGrdService mberGrdService;
	
	// test
	@RequestMapping(value= {"/web/main/testAjax.do"})
	public ModelAndView testAjax(HttpServletRequest request,
			ModelMap model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {

			MberGrdVO mberGrdVO = new MberGrdVO();
			mberGrdVO.setFirstIndex(0);
			mberGrdVO.setLastIndex(1000);
			mberGrdVO.setRecordCountPerPage(1000);
	    	
			if("".equals(mberGrdVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
				mberGrdVO.setSearchSortCnd("regDate");
				mberGrdVO.setSearchSortOrd("desc");
			}
			
			List<MberGrdVO> resultList = mberGrdService.selectMberGrdList(mberGrdVO);			
			for (MberGrdVO item : resultList) {
				mberGrdVO.setGrdNewDate("2022-01-01");
				mberGrdVO.setMberId(item.getMberId());
				// System.out.println("Step 3. 누적결제금액(이벤트금액 제외) 추출 및 등급 조회");
				MberGrdVO mberGrdVO3 = new MberGrdVO();				
				mberGrdVO3 = mberGrdService.selectMberGrdAmtDetail(mberGrdVO);
				System.out.println("MberId : " + item.getMberId());
				System.out.println("MberGrdVO3 : " + mberGrdVO3);
				if (null != mberGrdVO3) {
					System.out.println("GrdSetNo() : " + mberGrdVO3.getGrdSetNo());
				}
				System.out.println("");
			}			
			
			MberGrdVO mberGrdVO1 = new MberGrdVO();				
			if (!StringUtils.isEmpty(mberGrdVO1.getMberId())) {
				System.out.println("mberGrdVO1 : NOT NULL");
			}
			else {
				System.out.println("mberGrdVO1 : NULL");
			}
			
			MberGrdVO mberGrdVO2 = new MberGrdVO();	
			mberGrdVO2.setMberId("nopay");
			if (!StringUtils.isEmpty(mberGrdVO2.getMberId())) {
				System.out.println("mberGrdVO2 : NOT NULL");
			}
			else {
				System.out.println("mberGrdVO2 : NULL");
			}
    	}
		catch(Exception e) {
			isSuccess = false;
    		msg = e.getMessage();
    	}
			
		modelAndView.addObject("isSuccess", isSuccess);        		
		modelAndView.addObject("msg", msg);

		return modelAndView;
	} 	
	*/
	
	// 전용계좌 스케줄러 실행
	@RequestMapping(value= {"/web/main/payBackAutoChargeAjax.do"})
	public ModelAndView payBackAutoChargeAjax(HttpServletRequest request,
			ModelMap model) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {
			String pageType = "";
			if(request.getParameter("type") != null) {
				pageType = request.getParameter("type");
			}
			
			int limitCout = 500; 
			if(request.getParameter("limitCout") != null) {
				limitCout = Integer.parseInt(request.getParameter("limitCout"));
			}
			
			System.out.println("type : " + pageType);
			System.out.println("limitCout : " + limitCout);
			
			schdlrManageService.payBack(pageType, limitCout);
    	}
		catch(Exception e) {
			isSuccess = false;
    		msg = e.getMessage();
    	}
			
		modelAndView.addObject("isSuccess", isSuccess);        		
		modelAndView.addObject("msg", msg);

		return modelAndView;
	}
}
