package itn.let.fax.addr.web;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.fax.addr.service.FaxAddrGroupService;
import itn.let.fax.addr.service.FaxAddrGroupVO;
import itn.let.fax.addr.service.FaxAddrService;
import itn.let.fax.addr.service.FaxAddrVO;
import itn.let.mjo.msgsent.service.MjonMsgSentService;
import itn.let.mjo.pay.service.KmcVO;
import itn.let.uat.uia.service.AuthCertVO;
import itn.let.uat.uia.web.KmcCertChecker;
import itn.let.uss.umt.service.EgovMberManageService;
import itn.let.uss.umt.service.MberManageVO;

@Controller
public class FaxAddrGroupController {

	@Resource(name = "MjonMsgSentService")
    private MjonMsgSentService mjonMsgSentService;
	
	@Resource (name = "FaxAddrGroupService")
	private FaxAddrGroupService faxAddrGroupService;
	
	@Resource (name = "FaxAddrService")
	private FaxAddrService faxAddrService;
	
	/** EgovMessageSource */
	@Resource(name="egovMessageSource")
	EgovMessageSource egovMessageSource;
	
	/** mberManageService */
	@Resource(name = "mberManageService")
	private EgovMberManageService mberManageService;
	
	
	/**
	 * 팩스 주소록 그룹 리스트
	 * @param FaxAddrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/selectFaxAddrGroupListAjax.do")
	public String selectFaxAddrGroupListAjax(@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, FaxAddrVO addrVO
			,ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(userId != "") {
			addrGroupVO.setMberId(userId);
			addrVO.setMberId(userId);
		} else {
			redirectAttributes.addFlashAttribute("fail", true);
			return "redirect:/web/user/login/login.do";
		}
		

    	if(addrGroupVO.getPageUnit() != 10) {
    		addrGroupVO.setPageUnit(addrGroupVO.getPageUnit());
		}
		
		if("".equals(addrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			addrGroupVO.setSearchSortCnd("grpOrder");
			addrGroupVO.setSearchSortOrd("desc");
		}
		
		addrGroupVO.setSiteId("web");
		List<FaxAddrGroupVO> addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(addrGroupVO);
		
		//회원별 주소록 전체 갯수 조회
		int addrTotalCount = faxAddrService.selectFaxAddrTotalCount(addrVO);
		
		addrVO.setType("bookmark");
		List<FaxAddrVO> addrBookmarkList = faxAddrService.selectFaxAddrBasicGrpList(addrVO);

		addrVO.setType("noGrp");
		List<FaxAddrVO> addrNoGrpList = faxAddrService.selectFaxAddrBasicGrpList(addrVO);
		
		
		
		model.addAttribute("addrTotalCount", addrTotalCount);
		model.addAttribute("addrGroupList", addrGroupList);
	 	model.addAttribute("addrBookmarkList", addrBookmarkList);
		model.addAttribute("addrNoGrpList", addrNoGrpList);
		model.addAttribute("userId", userId);
		
		return "/web/fax/addr/FaxAddrGroupListAjax";
		
	}
	
	/**
	 * 주소록 합치기 팝업 리스트
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/selectFaxAddrGroupMergetAjax.do")
	public ModelAndView selectFaxAddrGroupMergetAjax(@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, FaxAddrVO addrVO
			, ModelMap model) throws Exception {
		
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(userId != "") {
			addrGroupVO.setMberId(userId);
			addrVO.setMberId(userId);
		} 
		
    	if(addrGroupVO.getPageUnit() != 10) {
    		addrGroupVO.setPageUnit(addrGroupVO.getPageUnit());
		}
		
		if("".equals(addrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			addrGroupVO.setSearchSortCnd("addrGrpId");
			addrGroupVO.setSearchSortOrd("desc");
		}
		
		addrGroupVO.setSiteId("web");
		List<FaxAddrGroupVO> addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(addrGroupVO);
		
		model.addAttribute("addrGroupList", addrGroupList);
		modelAndView.addObject("status", "success");
		
		return modelAndView;
		
	}
	
	/**
	 * 팩스 주소록 등록 페이지(ajax)
	 * @param FaxAddrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/selectFaxAddrGroupAjax.do")
	public String selectFaxAddrGroupAjax(HttpServletRequest request, ModelMap model, 
			FaxAddrGroupVO addrGroupVO, FaxAddrVO addrVO, RedirectAttributes redirectAttributes
			) throws Exception {
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(userId != "") {
			addrGroupVO.setMberId(userId);
			addrVO.setMberId(userId);
		} else {
			redirectAttributes.addFlashAttribute("fail", true);
			return "redirect:/web/user/login/login.do";
		}
		
    	if(addrGroupVO.getPageUnit() != 10) {
    		addrGroupVO.setPageUnit(addrGroupVO.getPageUnit());
		}
		
		addrGroupVO.setSiteId("web");
		List<FaxAddrGroupVO> faxAddrGroupList = faxAddrGroupService.selectFaxAddrGroupList(addrGroupVO);
		
		model.addAttribute("addrGroupList", faxAddrGroupList);
		
		
		return "/web/fax/addr/FaxAddrGroupSelectAjax";
	}
	
	/**
	 * 주소록 그룹 등록 로직 (ajax)
	 * @param addrGroupVO
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/insertFaxAddrGroupAjax.do")
	public ModelAndView insertFaxAddrGroup(HttpServletRequest request, ModelMap model, 
			FaxAddrGroupVO addrGroupVO
			) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("jsonView");
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());

		addrGroupVO.setMberId(userId);
		
		int usedCnt = faxAddrGroupService.selectDuplFaxAddrGroupCnt(addrGroupVO);
		if(usedCnt > 0) {
			mv.addObject("result","dupl");
		}else {
			if(userId != "") {
				try {
					faxAddrGroupService.insertFaxAddrGroup(addrGroupVO);
					mv.addObject("result","success");
				} catch (Exception e) {
					e.printStackTrace();
					mv.addObject("result","fail");
				}
			} else {
				mv.addObject("result","fail");
			}
		}
		return mv;
	}
	
	/**
	 * 주소록 그룹 중복체크 로직 (ajax)
	 * @param addrGroupVO
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/getFaxAddrGroupDuplCheckAjax.do")
	public ModelAndView getFaxAddrGroupDuplCheckAjax(HttpServletRequest request, ModelMap model, 
			FaxAddrGroupVO addrGroupVO
			) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("jsonView");
		
		boolean isSuccess = true;
		boolean isDupl = false;
		String msg = "";
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());

		try {		
			addrGroupVO.setMberId(userId);
			
			int usedCnt = faxAddrGroupService.selectDuplFaxAddrGroupCnt(addrGroupVO);
			if(usedCnt > 0) {
				isDupl = true;
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}	
		
		mv.addObject("isSuccess", isSuccess);
		mv.addObject("isDupl", isDupl);
		mv.addObject("msg", msg);
		
		return mv;
	}	
	
	
	/**
	 * 주소록 그룹 수정 로직 Ajax
	 * 
	 * @param request
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/updateFaxAddrGroupAjax.do")
	public ModelAndView updateFaxAddrGroupAjax(@RequestParam("addrGrpNms") String[] addrGrpNms, 
			@RequestParam("addrGrpIds") String[] addrGrpIds,
			HttpServletRequest request, 
			@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, Model model
			,RedirectAttributes redirectAttributes
			) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		addrGroupVO.setLastUpdusrId(user.getId());
		addrGroupVO.setMberId(user.getId());

		boolean dupl = false;
		for (int i=0; i<addrGrpNms.length; i++) { 
			String str1 = addrGrpNms[i]; 
			for (int j=0; j<addrGrpNms.length; j++) { 
				if (i == j) continue; 
				String str2 = addrGrpNms[j]; 
				if (str1.equals(str2)) { 
					dupl = true;
					break;
				}
			}
		}
		
		if(dupl) {
			modelAndView.addObject("result", "dupl");
		} else {
			for(int i=0; i<addrGrpIds.length; i++) {
				try {
					addrGroupVO.setAddrGrpNm(addrGrpNms[i]);
					addrGroupVO.setAddrGrpId(addrGrpIds[i]);
					addrGroupVO.setGrpOrder(i+1);
					faxAddrGroupService.updateFaxAddrGroup(addrGroupVO);
					
					
				} catch (Exception e) {
					e.printStackTrace();
					modelAndView.addObject("result", "fail");
					return modelAndView;
				}
			}
		}
		return modelAndView;
		
	}
	
	/**
	 * 주소록 그룹 삭제 로직 Ajax
	 * 
	 * @param request
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/mjon/fax/addr/deleteFaxAddrGroupAjax.do")
	public ModelAndView deleteFaxAddrGroupAjax(@RequestParam("grpCheck") String[] grpCheck, HttpServletRequest request, 
			@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, Model model
			,RedirectAttributes redirectAttributes
			) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		addrGroupVO.setLastUpdusrId(user.getId());
		addrGroupVO.setMberId(user.getId());
		FaxAddrVO addrVO = new FaxAddrVO();
		
		for(String id:grpCheck) {
			try {
				addrGroupVO.setAddrGrpId(id);
				faxAddrGroupService.deleteFaxAddrGroup(addrGroupVO); 
				
				addrVO.setAddrGrpId(id);
				addrVO.setGrpDelete("Y");
				addrVO.setMberId(user.getId());
				addrVO.setLastUpdusrId(user.getId());
				faxAddrService.deleteFaxAddr(addrVO);
				
				modelAndView.addObject("result", "success");
			} catch (Exception e) {
				e.printStackTrace();
				modelAndView.addObject("result", "fail");
				return modelAndView;
			}
		}
		
		return modelAndView;
		
	}
 
	/**
	 * 주소록 그룹명 중복체크
	 *
	 * @param addrGroupVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value= {"/web/mjon/fax/addr/selectDuplAddrGroupNameAjax.do"})
	@ResponseBody
	public ModelAndView selectDuplFaxAddrGroupAjax(FaxAddrGroupVO addrGroupVO
			,HttpServletRequest request
			,ModelMap model
		) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		int usedCnt = faxAddrGroupService.selectDuplFaxAddrGroupCnt(addrGroupVO);
		
		if(usedCnt > 0) {
			modelAndView.addObject("result1", "dupl");
		} else {
			modelAndView.addObject("result1", "success");
		}
		modelAndView.addObject("status1", "success");
		
		return modelAndView;
	}
	
	/**
	 * 주소록 합치기
	 * @param addrGrpNewNm
	 * @param request
	 * @param addrGroupVO
	 * @param addrVO
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping("/web/mjon/fax/addr/mergeFaxAddrGroupAjax.do")
	public ModelAndView mergeFaxAddrGroupAjax(@RequestParam("addrGrpNewNm") String addrGrpNewNm
			,HttpServletRequest request 
			,@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO
			,FaxAddrVO addrVO
			,Model model
			,RedirectAttributes redirectAttributes
			) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		addrGroupVO.setLastUpdusrId(user.getId());
		addrGroupVO.setMberId(user.getId());
		addrGroupVO.setFrstRegisterId(user.getId());
		addrGroupVO.setAddrGrpNm(addrGrpNewNm);
		
		int usedCnt = faxAddrGroupService.selectDuplFaxAddrGroupCnt(addrGroupVO);
		
		if(usedCnt > 0) {
			modelAndView.addObject("result", "dupl");
		}else {
			addrVO.setMberId(user.getId());
			addrVO.setLastUpdusrId(user.getId());
			
			try {
				faxAddrGroupService.mergeFaxAddrGroupAjax(addrGroupVO, addrVO);
				
				modelAndView.addObject("result", "success");
			} catch (Exception e) {
				e.printStackTrace();
				modelAndView.addObject("result", "fail");
				return modelAndView;
			}
		}
		
		
		return modelAndView;
		
	}
	
	
	
	
	/**
	 * 주소록 그룹 복사하기
	 * @param addrGrpNewNm
	 * @param request
	 * @param addrGroupVO
	 * @param addrVO
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping("/web/mjon/fax/addr/copyFaxAddrGroupAjax.do")
	public ModelAndView copyFaxAddrGroupAjax(@RequestParam("addrGrpNewNm") String addrGrpNewNm
			,HttpServletRequest request 
			,@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO
			,FaxAddrVO addrVO
			,Model model
			,RedirectAttributes redirectAttributes
			) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		addrGroupVO.setLastUpdusrId(user.getId());
		addrGroupVO.setMberId(user.getId());
		addrGroupVO.setFrstRegisterId(user.getId());
		addrGroupVO.setAddrGrpNm(addrGrpNewNm);
		
		int usedCnt = faxAddrGroupService.selectDuplFaxAddrGroupCnt(addrGroupVO);
		
		if(usedCnt > 0) {
			modelAndView.addObject("result", "dupl");
		}else {
			addrVO.setMberId(user.getId());
			addrVO.setLastUpdusrId(user.getId());
			
			try {
				faxAddrGroupService.copyFaxAddrGroupAjax(addrGroupVO, addrVO);
				
				modelAndView.addObject("result", "success");
			} catch (Exception e) {
				e.printStackTrace();
				modelAndView.addObject("result", "fail");
				return modelAndView;
			}
		}
		
		
		return modelAndView;
		
	}
	
	
	// 주소록 내보내기 kmc본인인증
		@RequestMapping(value = "/web/mjon/fax/addr/kmcPopupFaxAddrSubmitPramAjax.do")
		public ModelAndView kmcPopupIdPwPramAjax(@ModelAttribute("mberManageVO") MberManageVO mberManageVO,
				HttpServletRequest request) throws Exception {

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

			try {
				KmcCertChecker kmcCertCheck = new KmcCertChecker();

				// mberId null일경우 ""로
				mberManageVO.setMberId(EgovStringUtil.isNullToString(mberManageVO.getMberId()));

				// kmc 본인인증 실/개발 서버 구분
				String serverNm = "";
				if (request.getServerName().contains("219.240.88.15") || request.getServerName().contains("localhost")) {
					serverNm = request.getScheme() + "://219.240.88.15:8095";
				} else {
					serverNm = request.getScheme() + "://www.munjaon.co.kr";
				}

				AuthCertVO certVO = kmcCertCheck.authCertCheckEight(serverNm + "/web/cop/kmc/authRequestAddrSubmitAjax.do",
						mberManageVO.getMberId());

				modelAndView.addObject("tr_cert", certVO.getTr_cert());
				modelAndView.addObject("tr_url", certVO.getTr_url());
				modelAndView.addObject("tr_add", certVO.getTr_add());

				modelAndView.addObject("result", "success");

			} catch (Exception e) {
				modelAndView.addObject("result", "fail");
				modelAndView.addObject("message", "기타 시스템 오류 : " + e.getMessage());
			}

			return modelAndView;
		}

		
		// 파라미터 유효성 검증 --------------------------------------------
		public Boolean paramChk(String patn, String param) {
			Pattern pattern = Pattern.compile(patn);
			Matcher matcher = pattern.matcher(param);
			boolean b = matcher.matches();
			return b;
		}

		// 파라미터 유효성 검증 --------------------------------------------
		public String returnPage(ModelMap model, String errMessage, KmcVO kmcVO) {
			kmcVO.setErrMessage(errMessage);
			model.addAttribute("kmcVO", kmcVO);
			return "web/cop/nicepay/payRequestAjax";
		}
	
	
}
