package itn.let.mjo.addr.web;

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

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

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 egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.cmm.util.RedirectUrlMaker;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.mjo.addr.service.AddrGroupService;
import itn.let.mjo.addr.service.AddrGroupVO;
import itn.let.mjo.addr.service.AddrService;
import itn.let.mjo.addr.service.AddrVO;
import itn.let.mjo.msgsent.service.MjonMsgSentService;
import itn.let.mjo.msgsent.service.MjonMsgSentVO;
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 클래스를 정의한다.
 * @author ITN
 * @since 2021.05.21
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자           수정내용
 *  -------    --------    ---------------------------
 *   2021.04.08  ITN          최초 생성
 *
 * </pre>
 */
@Controller
public class AddrGroupController {
	@Resource(name = "MjonMsgSentService")
    private MjonMsgSentService mjonMsgSentService;
	
	@Resource (name = "AddrGroupService")
	private AddrGroupService addrGroupService;
	
	@Resource (name = "AddrService")
	private AddrService addrService;
	
	/** EgovMessageSource */
	@Resource(name="egovMessageSource")
	EgovMessageSource egovMessageSource;
	
	/** mberManageService */
	@Resource(name = "mberManageService")
	private EgovMberManageService mberManageService;
	
	/**
	 * 주소록 그룹 리스트
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/selectAddrGroupList.do")
	public String selectAddrGroupList(@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			,ModelMap model) throws Exception {
		
		if(addrGroupVO.getPageUnit() != 10) {
			addrGroupVO.setPageUnit(addrGroupVO.getPageUnit());
		}
		
		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(addrGroupVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(addrGroupVO.getPageUnit());
		paginationInfo.setPageSize(addrGroupVO.getPageSize());
		
		addrGroupVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		addrGroupVO.setLastIndex(paginationInfo.getLastRecordIndex());
		addrGroupVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		if("".equals(addrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			addrGroupVO.setSearchSortCnd("addrGrpId");
			addrGroupVO.setSearchSortOrd("desc");
		}
		
		addrGroupVO.setSiteId("admin");
		List<AddrGroupVO> addrGroupList = addrGroupService.selectAddrGroupList(addrGroupVO);
		
		int totCnt = 0;
		if(addrGroupList.size() > 0) {
			totCnt = addrGroupList.get(0).getTotcnt();
		}
		
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("addrGroupList", addrGroupList);
	 	model.addAttribute("paginationInfo", paginationInfo);
		
		
		return "/uss/ion/addr/AddrGroupList";
		
	}
	
	
	/**
	 * 주소록 그룹 리스트
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/selectAddrGroupListAjax.do")
	public ModelAndView selectAddrGroupListAdminAjax(@ModelAttribute("searchVO") AddrGroupVO addrGroupVO, AddrVO addrVO
			,ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		if("".equals(addrGroupVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			addrGroupVO.setSearchSortCnd("grpOrder");
			addrGroupVO.setSearchSortOrd("desc");
		}
		
		List<AddrGroupVO> addrGroupList = addrGroupService.selectAddrGroupList(addrGroupVO);
		
		modelAndView.addObject("addrGroupList", addrGroupList);
		modelAndView.addObject("addrGroupListCnt", addrGroupList.size());
		return modelAndView;
		
	}
	

	
	/**
	 * 주소록 그룹 리스트
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/selectAddrGroupListAjax.do")
	public String selectAddrGroupListAjax(@ModelAttribute("searchVO") AddrGroupVO addrGroupVO, AddrVO 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<AddrGroupVO> addrGroupList = addrGroupService.selectAddrGroupList(addrGroupVO);

		/*
		 * JSPark 2023.08.30 => Ajax 로 변경		
		//회원별 주소록 전체 갯수 조회
		int addrTotalCount = addrService.selectAddrTotalCount(addrVO);
		
		addrVO.setType("bookmark");
		List<AddrVO> addrBookmarkList = addrService.selectAddrBasicGrpList(addrVO);

		addrVO.setType("noGrp");
		List<AddrVO> addrNoGrpList = addrService.selectAddrBasicGrpList(addrVO);
		
		model.addAttribute("addrTotalCount", addrTotalCount);
	 	model.addAttribute("addrBookmarkList", addrBookmarkList);
		model.addAttribute("addrNoGrpList", addrNoGrpList);
		*/
		
		model.addAttribute("addrGroupList", addrGroupList);		
		model.addAttribute("userId", userId);
		
		return "/web/addr/AddrGroupListAjax";
		
	}
	
	
	/**
	 * 주소록 합치기 팝업 리스트
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/selectAddrGroupMergetAjax.do")
	public ModelAndView selectAddrGroupMergetAjax(@ModelAttribute("searchVO") AddrGroupVO addrGroupVO, AddrVO 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<AddrGroupVO> addrGroupList = addrGroupService.selectAddrGroupList(addrGroupVO);
		
		model.addAttribute("addrGroupList", addrGroupList);
		modelAndView.addObject("status", "success");
		
		return modelAndView;
		
	}
	
	
	
	/**
	 * 주소록 그룹 등록 페이지 이동
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/registAddrGroup.do")
	public String registAddrGroup(AddrGroupVO addrGroupVO, ModelMap model) throws Exception {
		
		model.addAttribute("addrGroupVO", addrGroupVO);
		return "/uss/ion/addr/AddrGroupRegist";
	}
	
	

	/**
	 * 주소록 그룹 등록 로직
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/insertAddrGroup.do")
	public String insertAddrGroup(AddrGroupVO addrGroupVO
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request) throws Exception {
		
		try {
			LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

			if( addrGroupVO.getMberId() == null || "".equals(addrGroupVO.getMberId()) ) {
				addrGroupVO.setMberId(user.getId());
			}
			
			//주소록 그룹 이름 불러오기(중복체크 용)
			MjonMsgSentVO mjonMsgSentVO = new MjonMsgSentVO();
			mjonMsgSentVO.setUserId(addrGroupVO.getMberId());
			mjonMsgSentVO.setAddrGrpNm(addrGroupVO.getAddrGrpNm());
			List<AddrGroupVO> resultAddrGrpList = mjonMsgSentService.selectAddrGrpNmList(mjonMsgSentVO);
			if(resultAddrGrpList.size() > 0) { //기존 같은 이름의 그룹이 있으면 해당 그룹에 연락처를 추가해줌
				redirectAttributes.addFlashAttribute("message", "같은 이름의 그룹명이 있습니다.");
			}
			else {
				addrGroupService.insertAddrGroup(addrGroupVO);
				redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.insert"));
			}
		}catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.insert"));
		}
		
		RedirectUrlMaker redirectUrlMaker = new RedirectUrlMaker("/uss/ion/addr/selectAddrGroupList.do");
		return redirectUrlMaker.getRedirectUrl();
	}
	
	
	/**
	 * 주소록 그룹 등록 로직 (ajax)
	 * @param addrGroupVO
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/insertAddrGroupAjax.do")
	public ModelAndView insertAddrGroup(HttpServletRequest request, ModelMap model, 
			AddrGroupVO 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 = addrGroupService.selectDuplAddrGroupCnt(addrGroupVO);
		if(usedCnt > 0) {
			mv.addObject("result","dupl");
		}else {
			if(userId != "") {
				try {
					addrGroupService.insertAddrGroup(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/addr/getAddrGroupDuplCheckAjax.do")
	public ModelAndView getAddrGroupDuplCheckAjax(HttpServletRequest request, ModelMap model, 
			AddrGroupVO addrGroupVO
			) throws Exception {
		System.out.println(" :: /web/addr/getAddrGroupDuplCheckAjax.do :: ");
		System.out.println(" :: /web/addr/getAddrGroupDuplCheckAjax.do :: ");
		System.out.println(" :: /web/addr/getAddrGroupDuplCheckAjax.do :: ");
		System.out.println(" :: addrGrpNm :: "+ addrGroupVO.getAddrGrpNm());
		
		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 = addrGroupService.selectDuplAddrGroupCnt(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 addrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/selectAddrGroupAjax.do")
	public String selectAddrGroupAjax(HttpServletRequest request, ModelMap model, 
			AddrGroupVO addrGroupVO, AddrVO 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<AddrGroupVO> addrGroupList = addrGroupService.selectAddrGroupList(addrGroupVO);
		
		model.addAttribute("addrGroupList", addrGroupList);
		
		
		return "/web/addr/AddrGroupSelectAjax";
	}

	// 주소록 그룹 카운트 조회(전체) Ajax
	@RequestMapping("/web/addr/selectAddrGroupTotCntAjax.do")
	public ModelAndView selectAddrGroupTotCntAjax(HttpServletRequest request, 
			@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			, Model model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		int addrTotCnt = 0;
		
        try{		
			LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
			addrGroupVO.setMberId(user.getId());
			
			addrGroupVO = addrGroupService.selectAddrGroupTotCnt(addrGroupVO);
			if (addrGroupVO != null) {
				addrTotCnt = addrGroupVO.getAddrTotCnt();
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}	
        
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("addrTotCnt", addrTotCnt);
		
		return modelAndView;
	}	
	
	// 주소록 그룹 카운트 조회(전체) Ajax
	@RequestMapping("/web/addr/selectAddrGroupNogrpCntAjax.do")
	public ModelAndView selectAddrGroupNogrpCntAjax(HttpServletRequest request, 
			@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			, Model model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		int nogrpCnt = 0;
		
        try{		
			LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
			addrGroupVO.setMberId(user.getId());
			
			addrGroupVO = addrGroupService.selectAddrGroupNogrpCnt(addrGroupVO);
			if (addrGroupVO != null) {
				nogrpCnt = addrGroupVO.getNogrpCnt();
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}	
        
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("nogrpCnt", nogrpCnt);
		
		return modelAndView;
	}	
	
	// 주소록 그룹 카운트 조회(전체) Ajax
	@RequestMapping("/web/addr/selectAddrGroupBookmarkCntAjax.do")
	public ModelAndView selectAddrGroupBookmarkCntAjax(HttpServletRequest request, 
			@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			, Model model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		int bookmarkCnt = 0;
		
        try{		
			LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
			addrGroupVO.setMberId(user.getId());
			
			addrGroupVO = addrGroupService.selectAddrGroupBookmarkCnt(addrGroupVO);
			if (addrGroupVO != null) {
				bookmarkCnt = addrGroupVO.getBookmarkCnt();
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}	
        
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("bookmarkCnt", bookmarkCnt);
		
		return modelAndView;
	}	
	
	/**
	 * 주소록 그룹 수정 로직
	 * 
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/updateAddrGroupAjax.do")
	public ModelAndView updateAddrGroupAjax(AddrGroupVO addrGroupVO
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request
			,HttpServletResponse response
			) throws Exception{
		
		ModelAndView modelAndView =  new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {		
			//주소록 그룹 이름 불러오기(중복체크 용)
			MjonMsgSentVO mjonMsgSentVO = new MjonMsgSentVO();
			mjonMsgSentVO.setUserId(addrGroupVO.getMberId());
			mjonMsgSentVO.setAddrGrpNm(addrGroupVO.getAddrGrpNm());
			List<AddrGroupVO> resultAddrGrpList = mjonMsgSentService.selectAddrGrpNmList(mjonMsgSentVO);
			if(resultAddrGrpList.size() > 0) { //기존 같은 이름의 그룹이 있으면 해당 그룹에 연락처를 추가해줌
				isSuccess = false;
				msg = "같은 이름의 그룹명이 있습니다.";
			}
			else {
				addrGroupService.updateAddrGroup(addrGroupVO);
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = "에러메시지 : " + e.getMessage();			
			e.printStackTrace();
		}		
		
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		
		return modelAndView;
		
	}

	
	/**
	 * 주소록 그룹 수정 로직 Ajax
	 * 
	 * @param request
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/updateAddrGroupAjax.do")
	public ModelAndView updateAddrGroupAjax(@RequestParam("addrGrpNms") String[] addrGrpNms, 
			@RequestParam("addrGrpIds") String[] addrGrpIds,
			HttpServletRequest request, 
			@ModelAttribute("searchVO") AddrGroupVO 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);
					addrGroupService.updateAddrGroup(addrGroupVO);
					
					
				} catch (Exception e) {
					e.printStackTrace();
					modelAndView.addObject("result", "fail");
					return modelAndView;
				}
			}
		}
		return modelAndView;
		
	}
 

	
	/**
	 * 주소록 그룹 수정 페이지 이동
	 * 
	 * @param addrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/editAddrGroup.do")
	public String editAddrGroup(AddrGroupVO addrGroupVO
			, ModelMap model ) throws Exception {
		
		model.addAttribute("searchVO", addrGroupVO);
		model.addAttribute("addrGrpInfo", addrGroupService.selectAddrGroupDetail(addrGroupVO));
		
		return "/uss/ion/addr/AddrGroupEdit";
	}
	

	/**
	 * 주소록 그룹 삭제 로직
	 * 
	 * @param request
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/addr/deleteAddrGroup.do")
	public String deleteAddrGroup(HttpServletRequest request, @ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			,RedirectAttributes redirectAttributes
			,ModelMap model) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		addrGroupVO.setLastUpdusrId(user.getUniqId());
		
		// 1. 그룹 삭제
		// 2. 그룹에 소속된 주소록 삭제
		int result = addrGroupService.deleteAddrGroupByAdminAll(addrGroupVO); 
		
		if (result > 0) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		} else {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.delete"));
		}
		redirectAttributes.addAttribute("pageIndex", addrGroupVO.getPageIndex());
		redirectAttributes.addAttribute("searchCondition", addrGroupVO.getSearchCondition());
		redirectAttributes.addAttribute("searchKeyword", addrGroupVO.getSearchKeyword());
		
		return "redirect:/uss/ion/addr/selectAddrGroupList.do";
	}
 

	/**
	 * 주소록 그룹 삭제 로직 Ajax
	 * 
	 * @param request
	 * @param addrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/web/addr/deleteAddrGroupAjax.do")
	public ModelAndView deleteAddrGroupAjax(@RequestParam("grpCheck") String[] grpCheck, HttpServletRequest request, 
			@ModelAttribute("searchVO") AddrGroupVO 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());
		
		for(String id:grpCheck) {
			try {
				
//				id = "13026";
				addrGroupVO.setAddrGrpId(id);
				addrGroupVO.setMberId(user.getId());
				int tot = addrService.getAddrCount(addrGroupVO);
				addrGroupVO.setTotCnt(tot);
				
				addrService.deleteAddr_advc(addrGroupVO);
				
				
/*				addrGroupVO.setAddrGrpId(id);
				addrGroupService.deleteAddrGroup(addrGroupVO); 
				
				addrVO.setAddrGrpId(id);
				addrVO.setGrpDelete("Y");
				addrVO.setMberId(user.getId());
				addrVO.setLastUpdusrId(user.getId());
				addrService.deleteAddr(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= {"/uss/ion/addr/duplAddrGroupAjax.do","/web/addr/selectDuplAddrGroupNameAjax.do"})
	@ResponseBody
	public ModelAndView selectDuplAddrGroupAjax(AddrGroupVO addrGroupVO
			,HttpServletRequest request
			,ModelMap model
		) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		int usedCnt = addrGroupService.selectDuplAddrGroupCnt(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/addr/mergeAddrGroupAjax.do")
	public ModelAndView mergeAddrGroupAjax(@RequestParam("addrGrpNewNm") String addrGrpNewNm
			,HttpServletRequest request 
			,@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			,AddrVO 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 = addrGroupService.selectDuplAddrGroupCnt(addrGroupVO);
		
		if(usedCnt > 0) {
			modelAndView.addObject("result", "dupl");
		}else {
			addrVO.setMberId(user.getId());
			addrVO.setLastUpdusrId(user.getId());
			
			try {
				addrGroupService.mergeAddrGroupAjax(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/addr/copyAddrGroupAjax.do")
	public ModelAndView copyAddrGroupAjax(@RequestParam("addrGrpNewNm") String addrGrpNewNm
			,HttpServletRequest request 
			,@ModelAttribute("searchVO") AddrGroupVO addrGroupVO
			,AddrVO 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 = addrGroupService.selectDuplAddrGroupCnt(addrGroupVO);
		
		if(usedCnt > 0) {
			modelAndView.addObject("result", "dupl");
		}else {
			addrVO.setMberId(user.getId());
			addrVO.setLastUpdusrId(user.getId());
			
			try {
				addrGroupService.copyAddrGroupAjax(addrGroupVO, addrVO);
				
				modelAndView.addObject("result", "success");
			} catch (Exception e) {
				e.printStackTrace();
				modelAndView.addObject("result", "fail");
				return modelAndView;
			}
		}
		
		
		return modelAndView;
		
	}
	
	
	// 주소록 내보내기 kmc본인인증
		@RequestMapping(value = "/web/addr/kmcPopupAddrSubmitPramAjax.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;
		}

		/**
		 * 아이디 비밀번호 찾기 kmc 본인인증(PG사 전송화면)
		 *
		 * @param
		 * @return
		 * @throws Exception
		 */

		@RequestMapping("/web/cop/kmc/authRequestAddrSubmitAjax.do")
		public String authRequestFindIdPwAjax(HttpServletRequest request, ModelMap model,
				@RequestParam Map<String, Object> commandMap, @ModelAttribute("searchVO") KmcVO kmcVO,
				RedirectAttributes redirectAttributes) throws Exception {

			String errMessage = ""; // 에러메세지

			String rec_cert = ""; // 결과값(암호화)
			String certNum = ""; // certNum

			rec_cert = request.getParameter("rec_cert").trim();
			certNum = request.getParameter("certNum").trim();

			kmcVO.setRecCert(rec_cert);
			kmcVO.setCertNum(certNum);
			// 파라미터 유효성 검증
			if (rec_cert.length() == 0 || certNum.length() == 0) {
				errMessage = "비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			// 변수선언
			// --------------------------------------------------------------------------------------------------------
			String k_certNum = ""; // 파라미터로 수신한 요청번호
			k_certNum = certNum;
			String date = ""; // 요청일시
			String CI = ""; // 연계정보(CI)
			String DI = ""; // 중복가입확인정보(DI)
			String phoneNo = ""; // 휴대폰번호
			String phoneCorp = ""; // 이동통신사
			String birthDay = ""; // 생년월일
			String gender = ""; // 성별
			String nation = ""; // 내국인
			String name = ""; // 성명
			String M_name = ""; // 미성년자 성명
			String M_birthDay = ""; // 미성년자 생년월일
			String M_Gender = ""; // 미성년자 성별
			String M_nation = ""; // 미성년자 내외국인
			String result = ""; // 결과값

			String certMet = ""; // 인증방법
			String ip = ""; // ip주소
			String plusInfo = "";

			String encPara = "";
			String encMsg1 = "";
			String encMsg2 = "";
			String msgChk = "";

			com.icert.comm.secu.IcertSecuManager seed = new com.icert.comm.secu.IcertSecuManager();

			// 02. 1차 복호화
			// 수신된 certNum를 이용하여 복호화
			rec_cert = seed.getDec(rec_cert, k_certNum);

			// 03. 1차 파싱
			int inf1 = rec_cert.indexOf("/", 0);
			int inf2 = rec_cert.indexOf("/", inf1 + 1);

			encPara = rec_cert.substring(0, inf1); // 암호화된 통합 파라미터
			encMsg1 = rec_cert.substring(inf1 + 1, inf2); // 암호화된 통합 파라미터의 Hash값

			// 04. 위변조 검증
			encMsg2 = seed.getMsg(encPara);
			kmcVO.setEncMsg2(encMsg2);
			if (encMsg2.equals(encMsg1)) {
				msgChk = "Y";
			}

			if (!"Y".equals(msgChk)) {
				errMessage = "비정상접근입니다.";
				return returnPage(model, errMessage, kmcVO);
			}

			// 05. 2차 복호화
			rec_cert = seed.getDec(encPara, k_certNum);
			kmcVO.setRecCert(rec_cert);
			// 06. 2차 파싱
			int info1 = rec_cert.indexOf("/", 0);
			int info2 = rec_cert.indexOf("/", info1 + 1);
			int info3 = rec_cert.indexOf("/", info2 + 1);
			int info4 = rec_cert.indexOf("/", info3 + 1);
			int info5 = rec_cert.indexOf("/", info4 + 1);
			int info6 = rec_cert.indexOf("/", info5 + 1);
			int info7 = rec_cert.indexOf("/", info6 + 1);
			int info8 = rec_cert.indexOf("/", info7 + 1);
			int info9 = rec_cert.indexOf("/", info8 + 1);
			int info10 = rec_cert.indexOf("/", info9 + 1);
			int info11 = rec_cert.indexOf("/", info10 + 1);
			int info12 = rec_cert.indexOf("/", info11 + 1);
			int info13 = rec_cert.indexOf("/", info12 + 1);
			int info14 = rec_cert.indexOf("/", info13 + 1);
			int info15 = rec_cert.indexOf("/", info14 + 1);
			int info16 = rec_cert.indexOf("/", info15 + 1);
			int info17 = rec_cert.indexOf("/", info16 + 1);
			int info18 = rec_cert.indexOf("/", info17 + 1);

			certNum = rec_cert.substring(0, info1);
			kmcVO.setCertNum(certNum);
			date = rec_cert.substring(info1 + 1, info2);
			kmcVO.setDate(date);
			CI = rec_cert.substring(info2 + 1, info3);
			kmcVO.setCI(CI);
			phoneNo = rec_cert.substring(info3 + 1, info4);
			kmcVO.setPhoneNo(phoneNo);
			phoneCorp = rec_cert.substring(info4 + 1, info5);
			kmcVO.setPhoneCorp(phoneCorp);
			birthDay = rec_cert.substring(info5 + 1, info6);
			kmcVO.setBirthDay(birthDay);
			gender = rec_cert.substring(info6 + 1, info7);
			kmcVO.setGender(gender);
			nation = rec_cert.substring(info7 + 1, info8);
			kmcVO.setNation(nation);
			name = rec_cert.substring(info8 + 1, info9);
			kmcVO.setName(name);
			result = rec_cert.substring(info9 + 1, info10);
			kmcVO.setResult(result);
			certMet = rec_cert.substring(info10 + 1, info11);
			kmcVO.setCertMet(certMet);
			ip = rec_cert.substring(info11 + 1, info12);
			kmcVO.setIp(ip);
			M_name = rec_cert.substring(info12 + 1, info13);
			kmcVO.setMName(M_name);
			M_birthDay = rec_cert.substring(info13 + 1, info14);
			kmcVO.setMBirthDay(M_birthDay);
			M_Gender = rec_cert.substring(info14 + 1, info15);
			kmcVO.setMGender(M_Gender);
			M_nation = rec_cert.substring(info15 + 1, info16);
			kmcVO.setMNation(M_nation);
			plusInfo = rec_cert.substring(info16 + 1, info17);
			kmcVO.setPlusInfo(plusInfo);
			DI = rec_cert.substring(info17 + 1, info18);
			kmcVO.setDI(DI);

			// 07. CI, DI 복호화
			CI = seed.getDec(CI, k_certNum);
			kmcVO.setCI(CI);
			DI = seed.getDec(DI, k_certNum);
			kmcVO.setDI(DI);

			if ("Y".equals(result)) {

			}

			// --------------------------------------------------------------
			String regex = "";
			if (certNum.length() == 0 || certNum.length() > 40) {
				errMessage = "요청번호 비정상.";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[0-9]*";
			if (date.length() != 14 || !paramChk(regex, date)) {
				errMessage = "요청일시";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[A-Z]*";
			if (certMet.length() != 1 || !paramChk(regex, certMet)) {
				errMessage = "본인인증방법 비정상" + certMet;
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[0-9]*";
			if ((phoneNo.length() != 10 && phoneNo.length() != 11) || !paramChk(regex, phoneNo)) {
				errMessage = "휴대폰번호 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[A-Z]*";
			if (phoneCorp.length() != 3 || !paramChk(regex, phoneCorp)) {
				errMessage = "이동통신사 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[0-9]*";
			if (birthDay.length() != 8 || !paramChk(regex, birthDay)) {
				errMessage = "생년월일 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[0-9]*";
			if (gender.length() != 1 || !paramChk(regex, gender)) {
				errMessage = "성별 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[0-9]*";
			if (nation.length() != 1 || !paramChk(regex, nation)) {
				errMessage = "내/외국인 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[\\sA-Za-z가-�R.,-]*";
			if (name.length() > 60 || !paramChk(regex, name)) {
				errMessage = "성명 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[A-Z]*";
			if (result.length() != 1 || !paramChk(regex, result)) {
				errMessage = "결과값 비정상";
				return returnPage(model, errMessage, kmcVO);
			}

			regex = "[\\sA-Za-z가-?.,-]*";
			if (M_name.length() != 0) {
				if (M_name.length() > 60 || !paramChk(regex, M_name)) {
					errMessage = "미성년자 성명 비정상";
					return returnPage(model, errMessage, kmcVO);
				}
			}

			regex = "[0-9]*";
			if (M_birthDay.length() != 0) {
				if (M_birthDay.length() != 8 || !paramChk(regex, M_birthDay)) {
					errMessage = "미성년자 생년월일  비정상";
					return returnPage(model, errMessage, kmcVO);
				}
			}

			regex = "[0-9]*";
			if (M_Gender.length() != 0) {
				if (M_Gender.length() != 1 || !paramChk(regex, M_Gender)) {
					errMessage = "미성년자 성별 비정상";
					return returnPage(model, errMessage, kmcVO);
				}
			}

			regex = "[0-9]*";
			if (M_nation.length() != 0) {
				if (M_nation.length() != 1 || !paramChk(regex, M_nation)) {
					errMessage = "미성년자 내/외국인 비정상";
					return returnPage(model, errMessage, kmcVO);
				}
			}

			// KMC 본인인증 로그
			AuthCertVO certVO = new AuthCertVO();

			certVO.setMberId(kmcVO.getPlusInfo());
			certVO.setCertNum(kmcVO.getCertNum());
			certVO.setCertDate(kmcVO.getDate());
			certVO.setCertDi(kmcVO.getDI());
			certVO.setCertPhone(kmcVO.getPhoneNo());
			certVO.setCertNation(kmcVO.getNation());
			certVO.setCertName(kmcVO.getName());
			certVO.setCertResult(kmcVO.getResult());
			certVO.setCertType("KMC_주소록내보내기");
			certVO.setCertIpaddr(kmcVO.getIp());
			certVO.setBirthDay(kmcVO.getBirthDay());
			certVO.setSexdstnCode(kmcVO.getGender());

			// 디비 테이블에 저장하기
			mberManageService.insertCertInfoLog(certVO);

			model.addAttribute("kmcVO", kmcVO);
			return "web/addr/AddrSubmitKmcReqPage";
		}
		
		
		
		
		// 파라미터 유효성 검증 --------------------------------------------
		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";
		}
	

}
