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.cert.phone.service.MberCertPhoneVO;
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;
	
	@Resource(name = "KmcCertChecker")
	private KmcCertChecker kmcCertChecker;
	
	/**
	 * 주소록 그룹 리스트
	 * @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);
		
		int totalGrpCount = addrGroupList.stream()
			    .mapToInt(group -> {
			        String grpCountStr = group.getGrpCount();
			        if (grpCountStr != null && !grpCountStr.isEmpty()) {
			            try {
			                return Integer.parseInt(grpCountStr);
			            } catch (NumberFormatException e) {
			                // 파싱에 실패한 경우 0을 반환하거나 예외 처리를 합니다.
			                return 0;
			            }
			        } else {
			            return 0;
			        }
			    })
			    .sum();

			// 결과 출력

		System.out.println("totalGrpCount :: "+ totalGrpCount);
		
		int addrTotalCount = (addrNoGrpList.size() >0 ? addrNoGrpList.get(0).getTotcnt() : 0)
				+ (addrBookmarkList.size() >0 ? addrBookmarkList.get(0).getTotcnt() : 0)
				+ totalGrpCount
				;		

		model.addAttribute("addrTotalCount", addrTotalCount);
	 	model.addAttribute("addrBookmarkCnt", addrBookmarkList.size() >0 ? addrBookmarkList.get(0).getTotcnt() : 0);
		model.addAttribute("addrNoGrpCnt", addrNoGrpList.size() >0 ? addrNoGrpList.get(0).getTotcnt() : 0);
		
		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();
		}	
        
        System.out.println("addrTotCnt : "+ addrTotCnt);
		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 {
				
				addrGroupVO.setAddrGrpId(id);
				addrGroupVO.setMberId(user.getId());
				addrGroupVO.setLastUpdusrId(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";
//				}
				
				MberCertPhoneVO mberCertPhoneVO = new MberCertPhoneVO();
				mberCertPhoneVO.setTrUrl("/web/cop/kmc/authRequestAddrSubmitAjax.do");
				mberCertPhoneVO.setPlusInfo(mberManageVO.getMberId());
				
				AuthCertVO certVO = kmcCertChecker.authCertCheck(mberCertPhoneVO, request);

				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
											, HttpServletResponse response
											, ModelMap model
											, @RequestParam Map<String, Object> commandMap
											, @ModelAttribute("searchVO") KmcVO kmcVO
											, RedirectAttributes redirectAttributes
										) throws Exception {

			kmcVO = kmcCertChecker.authCertResult(request, response, model);

			// 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";
		}
	

}
