package itn.let.mjo.apikey.web;

import java.util.ArrayList;
import java.util.List;

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.servlet.HandlerMapping;
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.apikey.service.ApiCallInfoMngService;
import itn.let.mjo.apikey.service.ApiKeyMngService;
import itn.let.mjo.apikey.service.ApiKeyVO;
import itn.let.mjo.mjocommon.MjonCommon;
import itn.let.mjo.msg.service.MjonMsgService;
import itn.let.sym.site.service.EgovSiteManagerService;
import itn.let.sym.site.service.JoinSettingVO;
import itn.let.uss.umt.service.EgovUserManageService;
import itn.let.utl.user.service.MjonNoticeSendUtil;
import itn.let.utl.user.service.SecuKeyUtil;

/**
*
* @author api key manager
* @since 2021.03.20
* @version 1.0
* @see
*
*
*   수정일      수정자           수정내용
*  -------    --------    ---------------------------
*   2021.03.20  신명섭          최초 생성
* </pre>
*/

@Controller
public class ApiKeyMngController {

	@Resource(name = "mjonMsgService")
    private MjonMsgService mjonMsgService;
	
	//api key 정보
	@Resource(name = "apiKeyMngService")
    private ApiKeyMngService apiKeyMngService;

	//api call info 정보
	@Resource(name = "apiCallInfoMngService")
    private ApiCallInfoMngService apiCallInfoMngService;
	
	/** EgovMessageSource */
    @Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;
    
	/** userManageService */
	@Resource(name = "userManageService")
	private EgovUserManageService userManageService;
	
	/** 사이트 설정 */ 
	@Resource(name = "egovSiteManagerService")
	EgovSiteManagerService egovSiteManagerService;
	
	/** 알림전송 Util */
	@Resource(name = "mjonNoticeSendUtil")
	private MjonNoticeSendUtil mjonNoticeSendUtil;
	
	@Resource(name="MjonCommon")
	private MjonCommon mjonCommon;
	
	/*
	//문자발송테스트
	@Resource(name = "mjonMsgSentTestService")
    private MjonMsgSentTestService mjonMsgSentTestService;

	//문자수신테스트
	@Resource(name = "mjonMsgRecvTestService")
    private MjonMsgRecvTestService mjonMsgRecvTestService;
	
	/** EgovMessageSource */
	/*
    @Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;
    
    @Resource(name = "mjonPayService")
    private MjonPayService mjonPayService;
    
	@Resource(name = "certService")
    private CertService certService;
	
    //문자발송 서비스
	@Resource(name = "MjonMsgDataService")
    private MjonMsgDataService mjonMsgDataService;
    
	@Resource(name = "MjonReservMsgService")
    private MjonReservMsgService mjonReservMsgService;
	
	@Resource(name="EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;
	
	@Resource(name="EgovFileMngService")
	private EgovFileMngService fileMngService;
	
	/** mberManageService */
	/*
	@Resource(name = "mberManageService")
	private EgovMberManageService mberManageService;
	
	/** 첨부파일 저장경로 */
	/*
	@Value("#{globalSettings['Globals.file.saveDir']}")
	private String fileSaveDir;
	
	/** userManageService */
	/*
	@Resource(name = "userManageService")
	private EgovUserManageService userManageService;	

    /**
     * 신규회원 문자전송 리스트 
     * @param searchVO
     * @param model
     * @return	"/uss/ion/msg/NewUserSendMsgList.do"
     * @throws Exception
     */
	@RequestMapping(value= {"/uss/ion/apikey/UserAPIKEYList.do"})
	public String ussIonApikeyUserAPIKEYList(@ModelAttribute("searchVO") ApiKeyVO searchVO, 
			HttpServletRequest request ,
			ModelMap model) throws Exception{
		//value 값 가져오기 
//	    String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE) ;
	    
		try {
			/** 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());
			
			if("".equals(searchVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
				searchVO.setSearchSortCnd("b.FRST_REGIST_PNTTM");
				searchVO.setSearchSortOrd("desc");
			}
			
			List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
			resultList = apiKeyMngService.selectMberApiKeyList(searchVO);
			
			
	        model.addAttribute("resultList", resultList);
	        /*
	        //문자발송 실패 결과 코드정보 리스트 불러오기
	        MjonMsgResultCodeVO mjonMsgResultCodeVO = new MjonMsgResultCodeVO();
	        apiKeyMngService.selectMberList(userSearchVO);
	        */
	        
	        //List<MjonMsgResultCodeVO> resultMsgCodeList = mjonMsgService.selectMsgResultCodeAllList(mjonMsgResultCodeVO);
	        
	        //model.addAttribute("resultMsgCodeList", resultMsgCodeList);
	        
	        paginationInfo.setTotalRecordCount(resultList.size() > 0 ? ((ApiKeyVO)resultList.get(0)).getTotCnt() : 0);
			model.addAttribute("paginationInfo", paginationInfo);			
		}catch(Exception ex) {
			ex.printStackTrace();
		}

		
		return "/uss/ion/apikey/UserAPIKEYList";
        
	}
	
	/**
     *  API KEY 내용 수정 페이지
     * @param searchVO
     * @param model
     * @return	"/uss/ion/apikey/UserAPIKEYModify"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIKEYModify.do"})
    public String UserAPIKEYModify(
            @ModelAttribute("searchVO") ApiKeyVO searchVO, 
            HttpServletRequest request ,
            Model model) throws Exception {

    	//String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE) ;
    	
    	try {
        	//api key 정보
        	ApiKeyVO apiKeyVO = new ApiKeyVO();
        	apiKeyVO.setAccessNo(searchVO.getAccessNo());
        	
    		List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
    		resultList = apiKeyMngService.selectMberApiKeyList(apiKeyVO);
    		
    		if (resultList.size()>0) {
    			model.addAttribute("apiKeyVO", resultList.get(0));
    		}else {
    			model.addAttribute("apiKeyVO", null);
    		}   	
        	
    		
    		//api call info 정보
    		List<ApiKeyVO> resultList_call = new ArrayList<ApiKeyVO>();
    		resultList_call = apiCallInfoMngService.selectMberApiCallInfoList(apiKeyVO);		
    		model.addAttribute("apiCallInfoVOList", resultList_call);
    		
    	}catch(Exception ex) {
    		ex.printStackTrace();
    	}
	
		
        return "/uss/ion/apikey/UserAPIKEYModify";
    }
	
    /**
     * 회원 API KEY 삭제  프로세서(use_yn : N로 업데이트)
     * @param searchVO
     * @param model
     * @return	"/uss/ion/apikey/UserAPIKEYDelete"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIKEYDelete.do", "/uss/ion/apikey/UserAPIKEYListDelete.do"})
    public String UserAPIKEYDelete(
    		@RequestParam("del") String[] del,
    		@ModelAttribute("searchVO") ApiKeyVO mjonMsgVO, 
            HttpServletRequest request , RedirectAttributes redirectAttributes,
            Model model) throws Exception {
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	for(String id: del) {
        		mjonMsgVO.setAccessNo(id);        		
        		apiKeyMngService.deleteApiKey(mjonMsgVO);;
     	    }
        	
    	}catch(Exception e) {
    		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.update"));
    	}
    	
    	if(mjonMsgVO.getUseYn().equals("N")) {
    		
    		//redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.delete"));
    		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.update"));
    		
    		
    	}else {
    		
    		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.update"));
    	 
    	}
    	
    	//redirectAttributes.addFlashAttribute("searchVO", mjonMsgVO);
    	
    	
    	//value 값 가져오기 
	    String pattern = (String) request.getAttribute(
	                HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE) ;
	    
    	String returnUrl = "";
    	if(pattern.contains("/uss/ion/apikey/UserAPIKEYListDelete.do")) {	// API KEY 관리리스트 에서 삭제/복구하였을 경우 리스트로 이동
    		returnUrl = "/uss/ion/apikey/UserAPIKEYList.do";
    		
    	}else if(pattern.contains("/uss/ion/apikey/UserAPIKEYDelete.do")) {	// API KEY 관리리스트 > 상세 화면에서 삭제/복구하였을 경우 상세로 이동
    		returnUrl = "/uss/ion/apikey/UserAPIKEYModify.do";
    		returnUrl = "/uss/ion/apikey/UserAPIKEYList.do";
    	}
    	
    	RedirectUrlMaker redirectUrlMaker = new RedirectUrlMaker(returnUrl);
		return redirectUrlMaker.getRedirectUrl();
		
    }
    
    /**
     * api call info 생성
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIInsertCallInfoAjax.do"})
    public ModelAndView UserAPIInsertCallInfoAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, @RequestParam("callType") String p_callType
    		, @RequestParam("callInfo") String p_callInfo
    		, Model model) throws Exception {
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);
    		apiKeyVO.setCallType(p_callType);
    		apiKeyVO.setCallInfo(p_callInfo);
    		apiKeyVO.setFrstRegisterId(userId);
    		apiKeyVO.setLastUpdusrId(userId);
    		
    		//api call info 생성
    		apiCallInfoMngService.insertApiCallInfo(apiKeyVO);
    		
    		modelAndView.addObject("message", "저장 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		modelAndView.addObject("message", "저장에 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }
    
    /**
     * api call info 생성
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/AdminAPIInsertCallInfoAjax.do"})
    public ModelAndView AdminAPIInsertCallInfoAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, @RequestParam("callType") String p_callType
    		, @RequestParam("callInfo") String p_callInfo
    		, Model model) throws Exception {
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);
    		apiKeyVO.setCallType(p_callType);
    		apiKeyVO.setCallInfo(p_callInfo);
    		apiKeyVO.setFrstRegisterId(userId);
    		apiKeyVO.setLastUpdusrId(userId);
    		
    		//api call info 생성
    		apiCallInfoMngService.insertApiCallInfo(apiKeyVO);
    		
    		modelAndView.addObject("message", "저장 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		modelAndView.addObject("message", "저장에 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }
    
    /**
     * api call info 삭제
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIDeleteCallInfoAjax.do"})
    public ModelAndView UserAPIdeleteCallInfoAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, @RequestParam("infoNo") String p_infoNo
    		, Model model) throws Exception {
    	
    	System.out.println("111111111111");
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	System.out.println("1111111111112");
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);
    		apiKeyVO.setInfoNo(p_infoNo);
    		
    		apiCallInfoMngService.deleteApiCallInfo(apiKeyVO);
    		
    		modelAndView.addObject("message", "삭제 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "삭제에 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }	

    /**
     * api key 관련 정보 실제 삭제
     * @param searchVO
     * @param model
     * @return	
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/AdminAPIKEYDeleteRealAjax.do"})
    public ModelAndView AdminAPIKEYDeleteRealAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, Model model) throws Exception {
    	    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);    		
    		
    		apiCallInfoMngService.deleteApiKeyInfoReal(apiKeyVO);
    		
    		modelAndView.addObject("message", "삭제 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "삭제에 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }
    
    /**
     * api key 관련 정보 실제 삭제
     * @param searchVO
     * @param model
     * @return	
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIKEYDeleteRealAjax.do"})
    public ModelAndView UserAPIKEYDeleteRealAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, Model model) throws Exception {
    	    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setMberId(userId);
    		apiKeyVO.setAccessNo(p_accessNo);    		
    		
    		apiCallInfoMngService.deleteApiKeyInfoReal(apiKeyVO);
    		
    		modelAndView.addObject("message", "삭제 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "삭제에 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }
    
    /**
     * api key 관련 정보 DB 변경 useYn
     * @param searchVO
     * @param model
     * @return	
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIKEYDeleteAjax.do"})
    public ModelAndView UserAPIKEYDeleteAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, @RequestParam("useYn") String p_useYn
    		, Model model) throws Exception {
    	    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());

    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setMberId(userId);
    		apiKeyVO.setAccessNo(p_accessNo);
    		apiKeyVO.setUseYn(p_useYn);
    		
    		apiKeyMngService.deleteApiKey(apiKeyVO);

    		modelAndView.addObject("message", "처리 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    	}catch(Exception e) {
    		modelAndView.addObject("message", "처리중 오류가 발생하였습니다.");
    		modelAndView.addObject("result", "success");
    	}
    	
    	return modelAndView;
    }
    
    /**
     * 사용자 생성 후 api key 생성
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/AdminAPIInsertAPIKEYAjax.do"})
    public ModelAndView AdminAPIInsertAPIKEYAjax(
    		@RequestParam("mberId") String p_mberId
    		, Model model) throws Exception {
    	    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	System.out.println("1111111111112");
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setMberId(p_mberId);
    		    		

    		//난수
    		String p_make_apikey;
    		List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
    		do {
        		//step1.난수 발생
        		p_make_apikey	=	SecuKeyUtil.makeKey(30, 40, "H");
        		
        		//step2.api key 중복 확인        		
        		apiKeyVO.setAccessKey(p_make_apikey);
        		resultList = apiKeyMngService.selectCheckApiKeyDup(apiKeyVO);
        		
    		}while(resultList.size()>=1);
    		    		
    		//step3.create user and api key
    		apiKeyVO.setLastUpdusrId(userId);
    		int i_ret	=	apiKeyMngService.insertApiKey(apiKeyVO);
    		
    		//apiCallInfoMngService.deleteApiCallInfo(apiKeyVO);
    		
    		if (i_ret>0) {
        		modelAndView.addObject("message", "api key 생성 완료되었습니다.");
        		modelAndView.addObject("result", "success");
        		
    		}else {
        		modelAndView.addObject("message", "api key 생성 실패했습니다.");
        		modelAndView.addObject("result", "fail");
        		
    		}
    		    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "api key 생성 실패했습니다.");
    		modelAndView.addObject("result", "db");
    	}
    	
    	return modelAndView;
    }	
    
    /**
     * 사용자 생성 후 api key 생성
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIInsertAPIKEYAjax.do"})
    public ModelAndView UserAPIInsertAPIKEYAjax(
    		@RequestParam("mberId") String p_mberId, 
    		Model model) throws Exception {
    	    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
    		// 기업회원 확인 => 2023.09.25 JSPark 개인, 기업 모두 허용
    		/*
    		System.out.println("loginVO.getDept() :: "+ loginVO.getDept());
    		if(!"c".equals(loginVO.getDept())) {
        		modelAndView.addObject("message", "기업회원만 api 신청이 가능합니다.");
        		modelAndView.addObject("result", "deptC");
            	return modelAndView;
    		}
    		*/
    		
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	String userNm = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getName());
        	
        	System.out.println("1111111111112");
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setMberId(p_mberId);
    		apiKeyVO.setUseYn("A");
    		apiKeyVO.setAccessKey("");

    		//키 생성 없이 신청서만 생성한다.
    		//난수    		
    		String p_make_apikey;
    		List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
    		do {
        		//step1.난수 발생
        		p_make_apikey	=	SecuKeyUtil.makeKey(30, 40, "H");
        		
        		//step2.api key 중복 확인        		
        		apiKeyVO.setAccessKey(p_make_apikey);
        		resultList = apiKeyMngService.selectCheckApiKeyDup(apiKeyVO);
        		
    		}while(resultList.size()>=1);    		
    		    		
    		//step3.create user and api key
    		apiKeyVO.setLastUpdusrId(userId);
    		int i_ret	=	apiKeyMngService.insertApiKey(apiKeyVO);
    		
    		//apiCallInfoMngService.deleteApiCallInfo(apiKeyVO);
    		
    		if (i_ret>0) {
        		modelAndView.addObject("message", "api 신청이 완료되었습니다.");
        		modelAndView.addObject("result", "success");
        		
				// 법인폰 알람여부 체크
				JoinSettingVO joinSettingVO = new JoinSettingVO();
				joinSettingVO = egovSiteManagerService.selectAdminNotiDetail();
				// SMS 체크
				if (joinSettingVO != null && joinSettingVO.getSmsNoti().equals("Y")) {
					// 스미싱의심 SMS 알림전송
					mjonNoticeSendUtil.smishingSmsNoticeSend("API 신청", userId, userNm);
				}					
				
				// SLACK 체크
				if (joinSettingVO != null && joinSettingVO.getSlackNoti().equals("Y")) {					
					// Slack 메시지 발송(단순본문)
					String msg = "[문자온] API 신청 - " + userNm +"("+ userId + ")";
					mjonCommon.sendSimpleSlackMsg(msg);					
				}
    		}else {
        		modelAndView.addObject("message", "api 신청이 실패했습니다.");
        		modelAndView.addObject("result", "fail");
    		}
    		    		
    	}catch(Exception e) {
    		e.printStackTrace();
    		modelAndView.addObject("message", "api 신청이 실패했습니다.");
    		modelAndView.addObject("result", "db");
    	}
    	
    	return modelAndView;
    }	
    
    /**
     * api key 변경
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/AdminAPIUpdateAPIKEYAjax.do"})
    public ModelAndView AdminAPIUpdateAPIKEYAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, Model model) throws Exception {
    	
    	System.out.println("111111111111");
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
        	System.out.println("1111111111112");
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);
    		

    		//난수
    		String p_make_apikey;
    		List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
    		do {
        		//step1.난수 발생
        		p_make_apikey	=	SecuKeyUtil.makeKey(30, 40, "H");
        		
        		//step2.api key 중복 확인        		
        		apiKeyVO.setAccessKey(p_make_apikey);
        		resultList = apiKeyMngService.selectCheckApiKeyDup(apiKeyVO);
        		
    		}while(resultList.size()>=1);
    		    		
    		//step3.api key update
    		apiKeyVO.setLastUpdusrId(userId);
    		apiKeyMngService.updateApiKey(apiKeyVO);
    		
    		//apiCallInfoMngService.deleteApiCallInfo(apiKeyVO);
    		
    		modelAndView.addObject("message", "api key 변경 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "api key 변경 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }	
    
    /**
     * api key 변경
     * @param searchVO
     * @param model
     * @return	"/uss/umt/user/selectMberSttusAjax"
     * @throws Exception
     */
    @RequestMapping(value = {"/uss/ion/apikey/UserAPIUpdateAPIKEYAjax.do"})
    public ModelAndView UserAPIUpdateAPIKEYAjax(
    		@RequestParam("accessNo") String p_accessNo
    		, Model model) throws Exception {
    	
    	
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");
    	
    	try {
    		LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        	String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
    		ApiKeyVO apiKeyVO = new ApiKeyVO();
    		apiKeyVO.setAccessNo(p_accessNo);
    		

    		//난수
    		String p_make_apikey;
    		List<ApiKeyVO> resultList = new ArrayList<ApiKeyVO>();
    		do {
        		//step1.난수 발생
        		p_make_apikey	=	SecuKeyUtil.makeKey(30, 40, "H");
        		
        		//step2.api key 중복 확인        		
        		apiKeyVO.setAccessKey(p_make_apikey);
        		resultList = apiKeyMngService.selectCheckApiKeyDup(apiKeyVO);
        		
    		}while(resultList.size()>=1);
    		    		
    		//step3.api key update
    		apiKeyVO.setLastUpdusrId(userId);
    		apiKeyVO.setMberId(userId);
    		apiKeyMngService.updateApiKey(apiKeyVO);
    		
    		//apiCallInfoMngService.deleteApiCallInfo(apiKeyVO);
    		
    		modelAndView.addObject("message", "api key 변경 완료되었습니다.");
    		modelAndView.addObject("result", "success");
    		
    		
    	}catch(Exception e) {
    		System.out.println("1111111111113");
    		modelAndView.addObject("message", "api key 변경 실패했습니다.");
    		modelAndView.addObject("result", "fail");
    	}
    	
    	return modelAndView;
    }	    
}