package egovframework.com.cmm.selfauth;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sci.v2.pcc.secu.SciSecuManager;
import com.sci.v2.pcc.secu.hmac.SciHmac;

import egovframework.com.cmm.UserVO;
import egovframework.let.cop.bbs.service.BoardVO;
import egovframework.let.cop.resve.service.ResveVO;

/**
 * 휴대폰 인증 처리를 위한 컨트롤러 클래스
 * @author 공통 서비스 개발팀 이삼섭
 * @since 2009.03.19
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자          수정내용
 *  -------    --------    ---------------------------
 *  2009.03.19  이삼섭          최초 생성
 *  2009.06.29  한성곤	       2단계 기능 추가 (댓글관리, 만족도조사)
 *  2011.08.31  JJY            경량환경 템플릿 커스터마이징버전 생성
 *
 *  </pre>
 */
@Controller
public class SelfauthController {

	@Value("#{globalSettings['Globals.Site.URL']}")
	private String SITE_URL;
	@Value("#{globalSettings['Globals.selfauth.siteId']}")
	private String SELFAUTH_SITE_ID;
	@Value("#{globalSettings['Globals.selfauth.srvNo']}")
	private String SELFAUTH_SRV_NO;

	private static final Logger LOGGER = LoggerFactory.getLogger(SelfauthController.class);

	/**
	 * (사용자)인증여부 체크 (본인인증(휴대폰), 아이핀인증)
	 *
	 * @param ResveVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/authCheckAjax.do")
	public ModelAndView authenticationAjax(HttpServletRequest request, @ModelAttribute("searchVO") ResveVO resveVO, ModelMap model, @RequestParam Map<String, Object> commandMap) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String returnType = (String) commandMap.get("returnType");
		String returnUrl =  (String) commandMap.get("returnUrl");
		
		UserVO userVO = (UserVO)request.getSession().getAttribute("userVO"); // 사용자 정보
		String authChck = "";
		
		// 인증여부
		if (userVO != null) {
			authChck = "true";
			modelAndView.addObject("userNm", userVO.getName());
		} else {
			authChck = "false";
			
			request.getSession().setAttribute("returnType", returnType);
			request.getSession().setAttribute("returnUrl", returnUrl);
		}
		
		modelAndView.addObject("authChck", authChck);
		return modelAndView;
	}

	/**
	 * (사용자)인증 처리 Test
	 *
	 * @param boardVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/authenticationResult.do")
	public String authenticationResult(HttpServletRequest request, ModelMap model
			,RedirectAttributes redirectAttributes) throws Exception {
		UserVO userVO = new UserVO();
		String nameEn =  (String)request.getParameter("nameEn");
		String returnType =  (String)request.getParameter("returnType");

		switch (nameEn) {
			case "yu1" :
				userVO.setName("홍길동"); userVO.setMblDn("1111"); break;
			case "yu2" :
				userVO.setName("김길동"); userVO.setMblDn("2222"); break;
			case "yu3" :
				userVO.setName("박길동"); userVO.setMblDn("3333"); break;
		}
		
		request.getSession().setAttribute("userVO", userVO); // 인증 처리 개발용이니 실서버 적용 되면 안됨.
		
		String url = returnType;
		url = "";
//		if (("resveAdd").equals(returnType)) {
//			url = "/web/cop/resve/addResveIntro.do";
//		} else if (("resveInqire").equals(returnType)) {
//			url = "/web/cop/resve/selectResveList.do";
//			redirectAttributes.addAttribute("resveInqire", "resveInqire"); //내 대관현황
//		}
		
		
//		url = "/web/cop/resve/selectResveList.do?viewCnd=resveList";

		return "redirect:" + url;
	}

	

	/**
	 * (사용자)본인인증 요청 입력 Sample
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/bbs/pccInput.do")
	public String pccInput(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		return "web/cop/selfauth/pcc_V3_input_seed";
	}
	
	/**
	 * (사용자)본인인증 요청 팝업 Sample
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/bbs/selfauth.do")
	public String selfauthTest(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		return "web/cop/selfauth/pcc_V3_sample_seed";
	}
	
	
	
	/**
	 * (사용자)본인인증 결과 리턴 Sample
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/bbs/pccPopSeed.do")
	public String pccPopSeed(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		return "web/cop/selfauth/pcc_V3_popup_seed";
	}
	
	/**
	 * (사용자)본인인증 결과 Sample
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/bbs/pccResult.do")
	public String pccResult(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		return "web/cop/selfauth/pcc_V3_result_seed";
	}
	
	
	/**
	 * (사용자)본인인증 안내 화면 휴대폰인증. 사용안함
	 *
	 * @param 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/authentication.do")
	public String authentication(ModelMap model) throws Exception {
		
		model.addAttribute("SITE_URL", SITE_URL);
		return "web/cop/selfauth/authentication";
	}
	
	/**
	 * (사용자) 휴대폰 본인인증 요청 1 pop
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/selfauth.do")
	public String selfauth(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		// 사이렌 요청 URL 등록 :  /web/cop/selfauth/selfauth.do 
		// test 서버 서비스 번호 001001
		
        //날짜 생성
        Calendar today = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String day = sdf.format(today.getTime());

        java.util.Random ran = new Random();
        //랜덤 문자 길이
        int numLength = 6;
        String randomStr = "";

        for (int i = 0; i < numLength; i++) {
            //0 ~ 9 랜덤 숫자 생성
            randomStr += ran.nextInt(10);
        }

        String reqNum = day + randomStr; // //reqNum은 최대 40byte 까지 사용 가능
        String certDate=day;
        
        String exVar = "0000000000000000"; // 복호화용 임시필드
		String certGb = "H"; // 인증구분 H: 휴대폰
		String addVar = "";

		request.getSession().setAttribute("reqNum", reqNum); // 결과값 복호화시 필요
		
	    //01. 암호화 모듈 선언
		SciSecuManager seed  = new SciSecuManager();
		
		//02. 1차 암호화
		String encStr = "";
		String reqInfo      = SELFAUTH_SITE_ID+"^"+SELFAUTH_SRV_NO+"^"+reqNum+"^"+certDate+"^"+certGb+"^"+addVar+"^"+exVar;  // 데이터 암호화
		encStr              = seed.getEncPublic(reqInfo);
		
		//03. 위변조 검증 값 생성
		String hmacMsg = SciHmac.HMacEncriptPublic(encStr);

		//03. 2차 암호화
		reqInfo  = seed.getEncPublic(encStr + "^" + hmacMsg + "^" + "0000000000000000");  //2차암호화
		
		request.getSession().setAttribute("reqInfo", reqInfo); // 본인확인 요청 정보
		request.getSession().setAttribute("SITE_URL", SITE_URL); // 사이트 URL
		
		return "web/cop/selfauth/selfauth";
	}
	
	/**
	 * (사용자)본인인증 결과 휴대폰인증2 리턴 
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/cop/selfauth/resultSeed.do")
	public String resultSeed(HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes)throws Exception {
		
		String retInfo   = request.getParameter("retInfo").trim();
		String cookiereqNum = (String)request.getSession().getAttribute("reqNum");
		
		//복화화용 변수
		String encPara		= "";
		String encMsg		= "";
		String msgChk       = "N";  
		
        // 1. 암호화 모듈 (jar) Loading
		SciSecuManager sciSecuMg  = new SciSecuManager();
        //쿠키에서 생성한 값을 Key로 생성 한다.
        retInfo  = sciSecuMg.getDec(retInfo, cookiereqNum);

        // 2.1차 파싱---------------------------------------------------------------
        String[] aRetInfo1 = retInfo.split("\\^");

		encPara  = aRetInfo1[0];         //암호화된 통합 파라미터
        encMsg   = aRetInfo1[1];    //암호화된 통합 파라미터의 Hash값
		
		String  encMsg2   = sciSecuMg.getMsg(encPara);
		// 3.위/변조 검증 ---------------------------------------------------------------
        if(encMsg2.equals(encMsg)) msgChk="Y";

        // 비정상 접근 처리
		if(msgChk.equals("N")) {
			model.addAttribute("msgChk", msgChk);
			return "web/cop/selfauth/resultSeed";
		}

        
		retInfo  = sciSecuMg.getDec(encPara, cookiereqNum);

        String[] aRetInfo = retInfo.split("\\^");
    	String name		= aRetInfo[0];                                                               //성명
//    	String birYMD		= aRetInfo[1];																//생년월일
//    	String sex			= aRetInfo[2];																//성별
//    	String fgnGbn	= aRetInfo[3];																//내외국인 구분값
        String di			= aRetInfo[4];																//DI
//        String ci1			= aRetInfo[5];																//CI
//        String ci2			= aRetInfo[6];																//CI
//        String civersion  = aRetInfo[7];                                                               //CI Version
//        String reqNum	= aRetInfo[8];                                                               // 본인확인 요청번호
//        String result		= aRetInfo[9];                                                               // 본인확인결과 (Y/N)
//        String certGb		= aRetInfo[10];                                                               // 인증수단
//        String cellNo		= aRetInfo[11];																// 핸드폰 번호
//    	String cellCorp	= aRetInfo[12];																// 이동통신사
//    	String certDate	= aRetInfo[13];                                                               // 검증시간
//    	String addVar		= aRetInfo[14];

        // 비정상 접근 처리
		if(di == null || di.equals("")) {
			model.addAttribute("msgChk", "N");
			return "web/cop/selfauth/resultSeed";
		}

        
    	// 사용자 세션생성
		UserVO userVO = new UserVO();
		userVO.setName(name);
		userVO.setMblDn(di);
		request.getSession().setAttribute("userVO", userVO);
		
		String returnType = (String)request.getSession().getAttribute("returnType");
		String returnUrl = (String)request.getSession().getAttribute("returnUrl");
		
//		if (!("resveAdd").equals(returnType) && !("resveInqire").equals(returnType)) {
//			BoardVO searchVO = (BoardVO)request.getSession().getAttribute("searchVO");
//			model.addAttribute("searchVO", searchVO);
//		} 
		
		model.addAttribute("returnType", returnType);
		model.addAttribute("returnUrl", returnUrl);
		model.addAttribute("name", name);
		return "web/cop/selfauth/resultSeed";
	}
	
}
