package itn.let.fax.admin.web;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.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.FileUtil;
import itn.com.cmm.util.PdfUtil;
import itn.com.cmm.util.RedirectUrlMaker;
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.fax.admin.service.FaxAdmService;
import itn.let.fax.admin.service.FaxStatVO;
import itn.let.fax.user.service.FaxConvertVO;
import itn.let.fax.user.service.FaxGroupDataVO;
import itn.let.fax.user.service.FaxService;
import itn.let.mail.service.StatusResponse;
import itn.let.mjo.msg.service.MjonMsgResultCodeVO;
import itn.let.mjo.msg.service.MjonMsgService;
import itn.let.mjo.msgdata.service.MjonMsgDataService;
import itn.let.mjo.msgsent.service.MjonMsgSentService;
import itn.let.mjo.msgsent.service.MjonMsgSentVO;

@Controller
public class FaxAdmController {
	
	
    private static final Logger logger = LoggerFactory.getLogger(FaxAdmController.class);

	@Resource(name = "faxService")
	private FaxService faxService;
	
	@Resource(name = "faxAdmService")
	private FaxAdmService faxAdmService;
	
	@Resource(name = "MjonMsgDataService")
	private MjonMsgDataService mjonMsgDataService;

	@Resource(name = "mjonMsgService")
    private MjonMsgService mjonMsgService;
	
	@Resource (name = "FaxAddrService")
	private FaxAddrService faxAddrService;
	
	@Resource (name = "FaxAddrGroupService")
	private FaxAddrGroupService faxAddrGroupService;
	
	@Resource(name = "MjonMsgSentService")
    private MjonMsgSentService mjonMsgSentService;
	
	/** EgovMessageSource */
	@Resource(name="egovMessageSource")
	EgovMessageSource egovMessageSource;
	
	/** fax 원본 파일 저장 경로*/
	@Value("#{globalSettings['Globals.fax.file.ori.path']}")
	private String FAX_ORI_FILE_PATH;

	/** fax 변환 파일 저장 경로*/
	@Value("#{globalSettings['Globals.fax.file.convert.path']}")
	private String FAX_CONVERT_FILE_PATH;
	
	
	
	/** 
	 * @methodName	: faxAdmSendList 
	 * @author		: 이호영
	 * @date		: 2023.04.13 
	 * @description	: 팩스 관리 > 팩스 전송리스트
	 * @param faxGroupDataVO
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value= {"/uss/ion/fax/faxAdmSendList.do"})
	public String faxAdmSendList(@ModelAttribute("searchVO") FaxGroupDataVO faxGroupDataVO
			, ModelMap model) throws Exception{

		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());

    	if(StringUtils.isEmpty(userId)) { 
			return "redirect:/web/user/login/login.do";
    	}
		model.addAttribute("loginVO", loginVO);
		
		/* 목록을 가져 온다 */

		Map<String, Object> faxSendListMap = faxService.selectFaxSendList(faxGroupDataVO);
    	// 전송내역
		model.addAttribute("faxGroupListVO", faxSendListMap.get("faxGroupListVO"));
    	model.addAttribute("searchKeyword", faxSendListMap.get("searchKeyword"));
    	model.addAttribute("paginationInfo", faxSendListMap.get("paginationInfo"));
		
		return "/uss/ion/fax/faxAdmSendList";
	}
	
	
	/** 
	 * @methodName	: faxAdmSendDetailList 
	 * @author		: 이호영
	 * @date		: 2023.04.13 
	 * @description	: 팩스 관리 > 팩스 전송리스트 > 전송 상세리스트
	 * @param faxGroupDataVO
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value= {"/uss/ion/fax/faxAdmSendDetailList.do"})
	public String faxAdmSendDetailList(@ModelAttribute("searchVO") FaxGroupDataVO faxGroupDataVO
			, ModelMap model) throws Exception{
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(StringUtils.isEmpty(userId)) { 
			return "redirect:/web/user/login/login.do";
		}
		model.addAttribute("loginVO", loginVO);


		/* 목록을 가져 온다 */
		faxGroupDataVO.setUserId(userId);
		Map<String, Object> resultMap = faxService.selectFaxSendDetailList(faxGroupDataVO);
		// 전송내역
		model.addAttribute("faxDetailListVO", resultMap.get("faxDetailListVO"));
		model.addAttribute("paginationInfo", resultMap.get("paginationInfo"));
//		
		return "/uss/ion/fax/faxAdmSendDetailList";
	}
	
	/** 
	 * @methodName	: faxAdmSendDetail 
	 * @author		: 이호영
	 * @date		: 2023.04.13 
	 * @description	: 팩스 관리 > 팩스 전송리스트 > 전송 상세리스트 > 상세 내용
	 * @param faxGroupDataVO
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value= {"/uss/ion/fax/faxAdmSendDetail.do"})
	public String faxAdmSendDetail(@ModelAttribute("searchVO") FaxGroupDataVO faxGroupDataVO
			, ModelMap model) throws Exception{
		
		//로그인 권한정보 불러오기
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
		if(StringUtils.isEmpty(userId)) { 
			return "redirect:/web/user/login/login.do";
		}
		model.addAttribute("loginVO", loginVO);
		
		try {
			
			Map<String, Object> resultMap = faxAdmService.selectFaxAdmSendDetail(faxGroupDataVO);
			model.addAttribute("faxDetailVO", resultMap.get("faxDetailVO"));
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		/* 목록을 가져 온다 */
//		
		return "/uss/ion/fax/faxAdmSendDetail";
	}
	
	
	
	
	/** 
	 * @methodName	: fileDownload 
	 * @author		: 이호영
	 * @date		: 2023.04.13
	 * @description	: 전송 상세에 파일 다운로드
	 * @param response
	 * @param faxGroupDataVO
	 * @throws Exception 
	 */
	@RequestMapping(value= {"/uss/ion/fax/fileDownload.do"})
	public void fileDownload(HttpServletResponse response, FaxGroupDataVO faxGroupDataVO) throws Exception{

		String filePath = "";
		String fileName = "";
		if(StringUtils.isNotEmpty(faxGroupDataVO.getFaxConvertFilePath()))
			fileName = faxGroupDataVO.getFaxConvertFilePath();
		else if(StringUtils.isNotEmpty(faxGroupDataVO.getFaxOriFilePath()))
			fileName = faxGroupDataVO.getFaxOriFilePath();

		System.out.println("faxGroupDataVO.getOrignlFileNm() : "+ faxGroupDataVO.getOrignlFileNm());
		
//		FAX_CONVERT_FILE_PATH
		if(fileName.indexOf("/") < 0)
			filePath = FAX_ORI_FILE_PATH+"/" + fileName;

		FileUtil.downLoad(response, filePath, faxGroupDataVO.getOrignlFileNm());
	}
	

	/** 
	 * @methodName	: pdfPreview 
	 * @author		: 이호영
	 * @date		: 2023.04.13 
	 * @description	: 전송 상세에 pdf 보기 
	 * @param response
	 * @param faxConvertVO
	 * @throws Exception 
	 */
	@RequestMapping(value= {"/uss/ion/fax/pdfPreview.do"})
	public void pdfPreview(HttpServletResponse response, FaxConvertVO faxConvertVO) throws Exception{

		String pdfFileName = faxConvertVO.getFaxConvertFilePath();
		
		if(pdfFileName.indexOf("/") < 0)
			pdfFileName = FAX_CONVERT_FILE_PATH+"/" + pdfFileName;
		
		PdfUtil.showPdf(response, pdfFileName);
	}
	
	

    @RequestMapping(value= {"/uss/ion/msg/faxResultCodeList.do"})
	public String MsgResultCodeList(@ModelAttribute("searchVO") MjonMsgResultCodeVO searchVO, 
			HttpServletRequest request,
			ModelMap model) throws Exception{
    	/*
		if(StringUtil.isEmpty(searchVO.getAgentCode())){ //최초 전송사 코드가 없는 경우 아이하트로 설정함
			searchVO.setAgentCode("01");
		}
		*/
		
		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());
		paginationInfo.setPageSize(searchVO.getPageSize());
		
		searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		searchVO.setAgentCode("06");
		List<MjonMsgResultCodeVO> resultList = mjonMsgService.selectMsgResultCodeListPageing(searchVO);        
        model.addAttribute("resultList", resultList);
        
        paginationInfo.setTotalRecordCount(resultList.size() > 0 ? ((MjonMsgResultCodeVO)resultList.get(0)).getTotCnt() : 0);
		model.addAttribute("paginationInfo", paginationInfo);

		return "/uss/ion/fax/faxResultCodeList";
	}
    
    // 팩스발송 통계
    @RequestMapping(value= {"/uss/ion/msg/faxSentStatistics.do"})
   	public String faxSentStatistics(
   			@ModelAttribute("searchVO") FaxStatVO searchVO
   			, HttpServletRequest request
   			, ModelMap model) throws Exception{
    	
		Map<String, Object> resultMap = faxAdmService.selectFaxCountStatList(searchVO);
		
		model.addAttribute("statList", resultMap.get("statList"));
		model.addAttribute("paginationInfo", resultMap.get("paginationInfo"));
		model.addAttribute("searchVO", searchVO);
    	
    	return "/uss/ion/fax/faxAdmSendStatistics";
    }
    
    // 팩스 금일 발송통계 갱신
 	@RequestMapping(value = "/uss/ion/msg/insertFaxCountStatTodayAjax.do")
 	public ResponseEntity<StatusResponse> insertFaxCountStatTodayAjax(FaxStatVO faxStatVO) throws Exception {
 		Map<String, String> resultMap = new HashMap<String, String>();
 		StatusResponse rspn = new StatusResponse(HttpStatus.OK, resultMap, LocalDateTime.now());
 		try {
			faxAdmService.insertFaxCountStat(faxStatVO);
			resultMap.put("result", "success");
			resultMap.put("message", "알림톡 발송건수 통계 생성을 성공적으로 마쳤습니다.");
			rspn.setObject(resultMap);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resultMap.clear();
			resultMap.put("result", "fail");
			resultMap.put("message", "알림톡 발송건수 통계 생성을 실패했습니다.");
			rspn.setObject(resultMap);
			return ResponseEntity.ok().body(rspn);
			
		}
		return ResponseEntity.ok().body(rspn);
	}	
 	
	// 팩스 전송실적
    @RequestMapping(value= {"/uss/ion/msg/faxSentPerformanceStatistics.do"})
   	public String faxSentPerformanceStatistics(
   			@ModelAttribute("searchVO") FaxGroupDataVO faxGroupDataVO
   			, ModelMap model) throws Exception{
    	
		try {
			Map<String, Object> faxStatListMap = faxAdmService.selectFaxStatList(faxGroupDataVO);
			model.addAttribute("faxGroupListVO", faxStatListMap.get("faxGroupListVO"));
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return "/uss/ion/fax/faxAdmSendPerformanceStatistics";
    }
    
    
    ////////////////////////////////////////팩스 주소록 관리 기능//////////////////////////////////////////////////////////////
    
	/**
	 * 주소록 리스트
	 * @param FaxAddrVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/selectFaxAddrList.do")
	public String selectFaxAddrList(@ModelAttribute("searchVO") FaxAddrVO addrVO
			,ModelMap model) throws Exception {
		
		if(addrVO.getPageUnit() != 10) {
			addrVO.setPageUnit(addrVO.getPageUnit());
		}

		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(addrVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(addrVO.getPageUnit());
		paginationInfo.setPageSize(addrVO.getPageSize());
		
		addrVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		addrVO.setLastIndex(paginationInfo.getLastRecordIndex());
		addrVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		if("".equals(addrVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			addrVO.setSearchSortCnd("addrId");
			addrVO.setSearchSortOrd("desc");
		}
		
		
		List<FaxAddrVO> addrList = faxAddrService.selectFaxAddrNewList(addrVO);
		
		int totCnt = 0;
		 if(addrList.size() > 0) {
 			totCnt = addrList.get(0).getTotcnt();
 		}
		 
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("addrList", addrList);
		model.addAttribute("paginationInfo", paginationInfo);
		
		return "/uss/ion/fax/addr/FaxAddrList";
	}
	
	/**
	 * 주소록 등록 페이지 이동
	 * @param FaxAddrVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/registFaxAddr.do")
	public String registFaxAddr(ModelMap model) throws Exception {
		
		return "/uss/ion/fax/addr/FaxAddrRegist";
	}
	
	
	/**
	 * 주소록 추가 로직
	 * @param FaxAddrVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/insertFaxAddr.do")
	public String insertFaxAddr(FaxAddrVO addrVO
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request) throws Exception {
		
		try {
			LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

			if( addrVO.getMberId() == null || "".equals(addrVO.getMberId()) ) {
				addrVO.setMberId(user.getId());
			}
			
			// 자주 보내는 번호
			if("bookmark".equals(addrVO.getAddrGrpId())) {
				addrVO.setBookmark("Y");
				addrVO.setAddrGrpId("0");
			}
			
			// 주소록 그룹 내 휴대폰번호 중복체크
			int usedCnt = faxAddrService.selectDuplFaxAddrCnt(addrVO);
			if (usedCnt > 0) {
				redirectAttributes.addFlashAttribute("message", "해당 그룹내 중복된 휴대폰 번호가 있습니다.");
			}
			else {
				faxAddrService.insertFaxAddr(addrVO);
				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/fax/addr/selectFaxAddrList.do");
		return redirectUrlMaker.getRedirectUrl();
		
	}
	

	/**
	 * 주소록 수정 로직
	 * 
	 * @param FaxAddrVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/updateFaxAddrByAdminAjax.do")
	public ModelAndView updateFaxAddrByAdminAjax(FaxAddrVO addrVO
			,RedirectAttributes redirectAttributes
			,HttpServletRequest request
			) throws Exception{
		
		ModelAndView modelAndView =  new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		boolean isSuccess = true;
		String msg = "";
		
		try {
			
			faxAddrService.updateFaxAddrByAdmin(addrVO);
			
		}
		catch(Exception e) {
			System.out.println("++++++ updateFaxAddrByAdminAjax Contrller Error @!!!" + e);
			isSuccess = false;
			msg = "에러메시지 : " + e.getMessage();			
			
		}		
		
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		
		return modelAndView;
	}
	
	
	/**
	 * 주소록 수정 페이지 이동
	 * 
	 * @param FaxAddrVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/editFaxAddr.do")
	public String editFaxAddr(FaxAddrVO addrVO
			, ModelMap model ) throws Exception {
		
		FaxAddrVO addrInfo = faxAddrService.selectFaxAddrDetail(addrVO);
		
		model.addAttribute("addrInfo", addrInfo);
		
		return "/uss/ion/fax/addr/FaxAddrEdit";
	}
	
	/**
	 * 주소록 삭제 로직
	 * 
	 * @param request
	 * @param FaxAddrVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/deleteFaxAddr.do")
	public String deleteFaxAddr (HttpServletRequest request, @ModelAttribute("searchVO") FaxAddrVO addrVO
			,RedirectAttributes redirectAttributes
			,ModelMap model) throws Exception {
		
		int result = faxAddrService.deleteFaxAddrByAdminAll(addrVO); 
		
		if (result > 0) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		} else {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.delete"));
		}
		redirectAttributes.addAttribute("pageIndex", addrVO.getPageIndex());
		redirectAttributes.addAttribute("searchCondition", addrVO.getSearchCondition());
		redirectAttributes.addAttribute("searchKeyword", addrVO.getSearchKeyword());
		
		return "redirect:/uss/ion/fax/addr/selectFaxAddrList.do";
	}
	
	
	
	///////////////////////////////////////////팩스 주소록 그룹 관리 ////////////////////////////////////////////////////////////
	
	
	/**
	 * 주소록 그룹 리스트
	 * @param FaxAddrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/selectFaxAddrGroupList.do")
	public String selectFaxAddrGroupList(@ModelAttribute("searchVO") FaxAddrGroupVO 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<FaxAddrGroupVO> addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(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/fax/addrGroup/FaxAddrGroupList";
		
	}
	
	
	/**
	 * 주소록 그룹 리스트
	 * @param FaxAddrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/selectFaxAddrGroupListAjax.do")
	public ModelAndView selectFaxAddrGroupListAjax(@ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO, FaxAddrVO 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<FaxAddrGroupVO> addrGroupList = faxAddrGroupService.selectFaxAddrGroupList(addrGroupVO);
		
		modelAndView.addObject("addrGroupList", addrGroupList);
		modelAndView.addObject("addrGroupListCnt", addrGroupList.size());
		return modelAndView;
		
	}
	
	/**
	 * 주소록 그룹 등록 페이지 이동
	 * @param FaxAddrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/registFaxAddrGroup.do")
	public String registFaxAddrGroup(FaxAddrGroupVO addrGroupVO, ModelMap model) throws Exception {
		
		model.addAttribute("addrGroupVO", addrGroupVO);
		return "/uss/ion/fax/addrGroup/FaxAddrGroupRegist";
	}
	
	

	/**
	 * 주소록 그룹 등록 로직
	 * @param FaxAddrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/insertFaxAddrGroup.do")
	public String insertFaxAddrGroup(FaxAddrGroupVO 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<FaxAddrGroupVO> resultAddrGrpList = mjonMsgSentService.selectFaxAddrGrpNmList(mjonMsgSentVO);
			if(resultAddrGrpList.size() > 0) { //기존 같은 이름의 그룹이 있으면 해당 그룹에 연락처를 추가해줌
				redirectAttributes.addFlashAttribute("message", "같은 이름의 그룹명이 있습니다.");
			}
			else {
				faxAddrGroupService.insertFaxAddrGroup(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/fax/addr/selectFaxAddrGroupList.do");
		return redirectUrlMaker.getRedirectUrl();
	}
	
	/**
	 * 주소록 그룹 수정 로직
	 * 
	 * @param FaxAddrGroupVO
	 * @param redirectAttributes
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/updateFaxAddrGroupAjax.do")
	public ModelAndView updateFaxAddrGroupAjax(FaxAddrGroupVO 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<FaxAddrGroupVO> resultAddrGrpList = mjonMsgSentService.selectFaxAddrGrpNmList(mjonMsgSentVO);
			if(resultAddrGrpList.size() > 0) { //기존 같은 이름의 그룹이 있으면 해당 그룹에 연락처를 추가해줌
				isSuccess = false;
				msg = "같은 이름의 그룹명이 있습니다.";
			}
			else {
				faxAddrGroupService.updateFaxAddrGroup(addrGroupVO);
			}
		}
		catch(Exception e) {
			isSuccess = false;
			msg = "에러메시지 : " + e.getMessage();			
			e.printStackTrace();
		}		
		
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		
		return modelAndView;
		
	}
	
	/**
	 * 주소록 그룹 수정 페이지 이동
	 * 
	 * @param FaxAddrGroupVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/editFaxAddrGroup.do")
	public String editFaxAddrGroup(FaxAddrGroupVO addrGroupVO
			, ModelMap model ) throws Exception {
		
		model.addAttribute("searchVO", addrGroupVO);
		model.addAttribute("addrGrpInfo", faxAddrGroupService.selectFaxAddrGroupDetail(addrGroupVO));
		
		return "/uss/ion/fax/addrGroup/FaxAddrGroupEdit";
	}
	

	/**
	 * 주소록 그룹 삭제 로직
	 * 
	 * @param request
	 * @param FaxAddrGroupVO
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/ion/fax/addr/deleteFaxAddrGroup.do")
	public String deleteFaxAddrGroup(HttpServletRequest request, @ModelAttribute("searchVO") FaxAddrGroupVO addrGroupVO
			,RedirectAttributes redirectAttributes
			,ModelMap model) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		addrGroupVO.setLastUpdusrId(user.getUniqId());
		
		// 1. 그룹 삭제
		// 2. 그룹에 소속된 주소록 삭제
		int result = faxAddrGroupService.deleteFaxAddrGroupByAdminAll(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/fax/addr/selectFaxAddrGroupList.do";
	}
 
	
	/**
	 * 주소록 그룹명 중복체크
	 *
	 * @param FaxAddrGroupVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value= {"/uss/ion/fax/addr/duplFaxAddrGroupAjax.do"})
	@ResponseBody
	public ModelAndView duplFaxAddrGroupAjax(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;
	}
	
	
    
}
