package itn.let.mjo.test.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import itn.com.cmm.ComDefaultCodeVO;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.cmm.service.EgovCmmUseService;
import itn.com.cmm.service.EgovFileMngService;
import itn.com.cmm.service.EgovFileMngUtil;
import itn.com.cmm.web.EgovFileDownloadController;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.kakao.kakaoComm.KakaoReturnVO;
import itn.let.kakao.kakaoComm.KakaoSendUtil;
import itn.let.kakao.kakaoComm.KakaoVO;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiImageUpload;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiJsonSave;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiProfile;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiProfileCategory;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiTemplate;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiTemplateCategory;
import itn.let.kakao.kakaoComm.kakaoApi.service.KakaoApiService;
import itn.let.kakao.user.kakaoAt.service.KakaoAlimTalkService;
import itn.let.mjo.msgdata.service.MjonMsgDataService;
import itn.let.mjo.msgdata.service.MjonMsgReturnVO;
import itn.let.uss.umt.service.EgovMberManageService;
import itn.let.utl.user.service.CheckLoginUtil;

@Controller
public class TestKakaoController {

	private static final Logger LOGGER = LoggerFactory.getLogger(EgovFileDownloadController.class);
	
	//로그인 처리
	@Resource(name = "checkLoginUtil")
	private CheckLoginUtil checkLoginUtil;
	
	/** mberManageService */
	@Resource(name = "mberManageService")
	private EgovMberManageService mberManageService;
	
	@Resource(name = "EgovCmmUseService")
	private EgovCmmUseService cmmUseService;
	
	@Resource(name = "kakaoApiService")
	private KakaoApiService kakaoApiService;
	
	@Resource(name = "MjonMsgDataService")
	private MjonMsgDataService mjonMsgDataService;
	
	@Autowired
	KakaoApiProfile kakaoApiProfile;
	
	@Autowired
	KakaoApiProfileCategory kakaoApiProfileCategory;
	
	@Autowired
	KakaoApiTemplateCategory kakaoApiTemplateCategory;
	
	@Autowired
	KakaoApiTemplate kakaoApiTemplate;
	
	@Autowired
	KakaoApiImageUpload kakaoApiImageUpload;
	
	@Autowired
	KakaoApiJsonSave kakaoApiJsonSave;
	
	@Autowired
	KakaoSendUtil kakaoSendUtil;
	
	/** EgovMessageSource */
	@Resource(name="egovMessageSource")
	EgovMessageSource egovMessageSource;
	
	@Resource(name="EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;
	
	@Resource(name="EgovFileMngService")
	private EgovFileMngService fileMngService;
	
	
	@Resource(name="kakaoAlimTalkService")
	private KakaoAlimTalkService kakaoAlimTalkService;
	
	@Resource(name = "egovMjonMsgGroupIdGnrService")
    private EgovIdGnrService idgenMjonMsgGroupId;
	
	/** 카카오 카테고리  시작----------------------------------------------------------------------*/
	
	// 카카오 카테고리 등록 페이지
	@RequestMapping(value= {"/web/mjon/test/selectSendCategoryView.do"})
	public String selectSendCategoryView(ModelMap model) throws Exception {
		
		// BIZ 공통코드 조회
		ComDefaultCodeVO vo = new ComDefaultCodeVO();
		vo.setCodeId("BIZ01");
		List<?>  bizList= cmmUseService.selectCmmCodeDetail(vo);
		model.addAttribute("bizList", bizList);
		
		KakaoVO kakaoVO = new KakaoVO();
		kakaoVO.setCategoryDepth("1");
		kakaoVO.setCategoryType("P");
		List<KakaoVO> profileCatagoryfirstList = kakaoApiService.selectKakaoCategory(kakaoVO);
		model.addAttribute("profileCatagoryfirstList", profileCatagoryfirstList);
		
		kakaoVO = new KakaoVO();
		kakaoVO.setCategoryDepth("1");
		kakaoVO.setCategoryType("T");
		List<KakaoVO> templateCatagoryfirstList = kakaoApiService.selectKakaoCategory(kakaoVO);
		model.addAttribute("templateCatagoryfirstList", templateCatagoryfirstList);
		
		return "/uss/ion/test/TestKakaoCategory";
	}
	
	// 카카오 카테고리 등록
	@RequestMapping(value= {"/web/mjon/test/kakaoApiCategoryAjax.do"})
	public ModelAndView kakaoApiCategoryAjax(
		KakaoVO kakaoVO
		, ModelAndView modelAndView
		) throws Exception {
		//json 알림
		modelAndView.setViewName("jsonView");
		try {
			
			KakaoVO kakaoInfo =  new KakaoVO();
			
			String tempUrl = kakaoVO.getBizUrl();
			
			if(!tempUrl.equals("") && tempUrl != null) {
				
				if(tempUrl.contains("profile/category/all")) {
					//발신프로필 카테고리 전체 내역 조회하기
					kakaoApiProfileCategory.kakaoApiProfileCategoryAll(kakaoVO);
				}else if(tempUrl.contains("profile/category")) {
					//발신프로필 카테고리 코드 정보 조회하기
					kakaoApiProfileCategory.kakaoApiProfileCategoryCode(kakaoVO);
				}else if(tempUrl.contains("template/category/all")) {
					kakaoApiTemplateCategory.kakaoApiProfileCategoryAll(kakaoVO);
				}
				
			}else{//요청 정보가 없으면 오류 반환
				
				modelAndView.addObject("message", "요청 URL이 없습니다.");
				modelAndView.addObject("result", "fail");
				return modelAndView;
				
			}
			
			modelAndView.addObject("kakaoInfo", kakaoInfo);
			modelAndView.addObject("result", "success");
			
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		
		return modelAndView;
	}
	
	// 발신프로필 카테고리 선택 조회
	@RequestMapping(value= {"/web/mjon/test/selectKakaoProfileCategoryAjax.do"})
	public ModelAndView selectKakaoProfileCategoryAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		kakaoVO.setCategoryType("P");
		List<KakaoVO> selectCatagoryList = kakaoApiService.selectKakaoCategory(kakaoVO);
		modelAndView.addObject("selectCatagoryList", selectCatagoryList);
		
		return modelAndView;
	}
	
	// 카카오 템플릿 카테고리 선책 조회
	@RequestMapping(value= {"/web/mjon/test/selectKakaoTemplateCategoryAjax.do"})
	public ModelAndView selectKakaoTemplateCategoryAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		kakaoVO.setCategoryType("T");
		List<KakaoVO> selectCatagoryList = kakaoApiService.selectKakaoCategory(kakaoVO);
		modelAndView.addObject("selectCatagoryList", selectCatagoryList);
		
		return modelAndView;
	}
	/** 카카오 카테고리 끝----------------------------------------------------------------------- */
	
	/** 카카오 프로필  시작----------------------------------------------------------------------*/
	// 카카오 발신 프로필 등록 페이지
	@RequestMapping(value= {"/web/mjon/test/selectSendTestView.do"})
	public String selectSendTestView(ModelMap model) throws Exception {
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		if(userId == "") {
			return "redirect:/web/user/login/login.do";
		}
		
		KakaoVO kakaoVO = new KakaoVO();
		kakaoVO.setUserId(userId);
		kakaoVO.setCategoryDepth("1");
		kakaoVO.setCategoryType("P");
		List<KakaoVO> firstCatagoryList = kakaoApiService.selectKakaoCategory(kakaoVO);
		model.addAttribute("firstCatagoryList", firstCatagoryList);
		
		//사용자 등록 발신프로필 정보 조회해오기
		List<KakaoVO> resultProfileList = kakaoApiService.selectKakaoProfileList(kakaoVO);
		model.addAttribute("resultProfileList", resultProfileList);
		
		return "/uss/ion/test/TestSandKakao";
	}
	
	// 카카오 발신 프로필 인증토큰 요청
	@RequestMapping(value= {"/web/mjon/test/kakaoApiProfileTokenSendAjax.do"})
	public ModelAndView kakaoApiProfileTokenSendAjax(
		KakaoVO kakaoVO
		, ModelAndView modelAndView
		) throws Exception {
		//json 알림
		modelAndView.setViewName("jsonView");
		try {
			
			KakaoReturnVO kakaoInfo = kakaoApiProfile.kakaoApiProfileToken(kakaoVO); //발신프로필 인증 토큰 요처하기
			
			modelAndView.addObject("kakaoInfo", kakaoInfo);
			modelAndView.addObject("result", "success");
			
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		
		return modelAndView;
	}
	
	// 카카오 발신 프로필 카테고리 등록
	@RequestMapping(value= {"/web/mjon/test/kakaoApiProfileCreateAjax.do"})
	public ModelAndView kakaoApiProfileCreateAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
	) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				kakaoVO.setUserId(userId);
				kakaoVO.setFrstRegisterId(userId);
				kakaoVO.setLastUpdusrId(userId);
				KakaoReturnVO kakaoInfo = kakaoApiProfile.kakaoApiProfileCreate(kakaoVO);
				
				modelAndView.addObject("kakaoInfo", kakaoInfo);
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		
		return modelAndView;
	}
	
	/** 카카오 프로필 끝----------------------------------------------------------------------- */
	
	/** 카카오 템플릿  시작----------------------------------------------------------------------- */
	// 카카오 템플릿 등록 페이지
	@RequestMapping(value= {"/web/mjon/test/selectTemplateView.do"})
	public String selectTemplateView(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		if(userId == "") {
			return "redirect:/web/user/login/login.do";
		}
		
		// 사용자 아이디를 이용한 발신프로필 조회
		kakaoVO.setUserId(userId); 
		List<KakaoVO> selectKakaoProfileList = kakaoApiService.selectKakaoProfileList(kakaoVO);
		model.addAttribute("kakaoProfileList", selectKakaoProfileList);
		
		kakaoVO = new KakaoVO();
		kakaoVO.setCategoryDepth("1");
		kakaoVO.setCategoryType("T");
		List<KakaoVO> templateCatagoryfirstList = kakaoApiService.selectKakaoCategory(kakaoVO);
		model.addAttribute("templateCatagoryfirstList", templateCatagoryfirstList);
		
		
		
		return "/uss/ion/test/TestTemplaKakao";
	}
	
	// 카카오 템플릿 등록
	@RequestMapping(value= {"/web/mjon/test/insertKakaoApiTemplateAjax.do"})
	public ModelAndView insertKakaoApiTemplateAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				
				KakaoReturnVO kakaoTemplateInfo = kakaoApiTemplate.insertKakaoApiTemplate(kakaoVO);
				modelAndView.addObject("kakaoTemplateInfo", kakaoTemplateInfo);
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		return modelAndView;
	}
	
	// 카카오 템플릿 목록 조회
	@RequestMapping(value= {"/web/mjon/test/selectKakaoApiTemplateAjax.do"})
	public ModelAndView selectKakaoApiTemplateAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				
				KakaoReturnVO kakaoTemplateList = kakaoApiTemplate.selectKakaoApiTemplate(kakaoVO);
				
				System.out.println("++++++++++++++"+kakaoTemplateList.getBizReturnCode()+"-----------------------");
				
				modelAndView.addObject("kakaoTemplateList", kakaoTemplateList);
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.select"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		return modelAndView;
	}
	
	// 카카오 템플릿 목록 조회 load용
	@RequestMapping(value= {"/web/mjon/test/selectKakaoApiTemplateLoadAjax.do"})
	public String selectKakaoApiTemplateLoadAjax(
			@ModelAttribute("kakaoVO")  KakaoVO kakaoVO, ModelMap model, HttpServletResponse response
			) throws Exception {

			kakaoVO.setCount("10"); //페이지 별 템플릿 개수 디폴트:30 
			KakaoReturnVO kakaoTemplateList = kakaoApiTemplate.selectKakaoApiTemplate(kakaoVO);
			
			System.out.println("++++++++++++++"+kakaoTemplateList.getBizReturnCode()+"-----------------------");
			
			model.addAttribute("kakaoTemplateList", kakaoTemplateList); //카카오 API 조회 정보
			model.addAttribute("templatList", kakaoTemplateList.getTemplatList()); //카카오 API 템플릿 조회 정보
				
			//템플릿 페이징 처리 - 결과가 있는 경우(코드 200)
			if("200".equals(kakaoTemplateList.getBizReturnCode())) {
				PaginationInfo paginationInfo = new PaginationInfo();
				paginationInfo.setCurrentPageNo(Integer.parseInt(kakaoTemplateList.getCurrentPage())); //현재페이지
				paginationInfo.setRecordCountPerPage(Integer.parseInt(kakaoVO.getCount())); //한 페이지당 게시되는 템플릿 개수
				paginationInfo.setPageSize(10); //페이지 건수
				paginationInfo.setTotalRecordCount(Integer.parseInt(kakaoTemplateList.getTotalCount()));//전체 템플릿 수
				
				model.addAttribute("paginationInfo", paginationInfo);
			}
		return "/uss/ion/test/TestTemplaKakaoLoadListAjax";
	}
	
	// 카카오 템플릿 상세 조회
	@RequestMapping(value= {"/web/mjon/test/selectKakaoApiTemplateInfoAjax.do"})
	public ModelAndView selectKakaoApiTemplateInfoAjax(
			@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
			) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				
				KakaoReturnVO kakaoTemplateInfo =kakaoApiTemplate.selectKakaoApiTemplateDetail(kakaoVO);
				modelAndView.addObject("kakaoTemplateInfo", kakaoTemplateInfo);
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		return modelAndView;
	}
	
	// 카카오 템플릿 검수 요청
	@RequestMapping(value= {"/web/mjon/test/requestKakaoApiTemplateAjax.do"})
	public ModelAndView requestKakaoApiTemplateAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				
				String[] arrTemplateCode = kakaoVO.getArrTemplateCode();
				int resultCnt = 0;
				for(String tmpCode : arrTemplateCode) {
					
					kakaoVO.setTemplateCode(tmpCode);
					System.out.println(kakaoVO.getTemplateCode());
					KakaoReturnVO requestKakaoTemplate = kakaoApiTemplate.requestKakaoApiTemplate(kakaoVO);
					
					String resultCode = requestKakaoTemplate.getBizReturnCode();
					
					if(resultCode.equals("200")) {
						resultCnt = resultCnt + 1;
					}
					
				}
				
				//KakaoReturnVO requestKakaoTemplate = kakaoApiTemplate.requestKakaoApiTemplate(kakaoVO);
				//modelAndView.addObject("requestKakaoTemplate", requestKakaoTemplate);

				if(resultCnt > 0) {
					
					modelAndView.addObject("result", "success");
					modelAndView.addObject("message", "템플릿 심사요청이 완료되었습니다.");
					
				}
				
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		return modelAndView;
	}
	
	// 카카오 템플릿 상세정보 요청
	@RequestMapping(value= {"/web/mjon/test/requestKakaoApiTemplateDetailAjax.do"})
	public ModelAndView requestKakaoApiTemplateDetailAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "notLogin");
				return modelAndView;
			}else {
				
				KakaoReturnVO requestKakaoTemplateDetail = kakaoApiTemplate.selectKakaoApiTemplateDetail(kakaoVO);
				
				modelAndView.addObject("requestKakaoTemplateDetail", requestKakaoTemplateDetail);
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		return modelAndView;
	}
	
	/** 카카오 템플릿  끝----------------------------------------------------------------------- */
	
	
	/** 카카오 친구톡 이미지 등록 시작----------------------------------------------------------------------- */	
	// 카카오 발신 프로필 조회 페이지
	@RequestMapping(value= {"/web/mjon/test/selectKakaoImageView.do"})
	public String selectKakaoImageView(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		if(userId == "") {
			return "redirect:/web/user/login/login.do";
		}
		
		// 사용자 아이디를 이용한 발신프로필 조회
		kakaoVO.setUserId(userId); 
		List<KakaoVO> selectKakaoProfileList = kakaoApiService.selectKakaoProfileList(kakaoVO);
		model.addAttribute("kakaoProfileList", selectKakaoProfileList);
		
		
		return "/uss/ion/test/TestKakaoImage";
	}
	
	// 카카오 친구톡 이미지 등록요청
	@RequestMapping(value= {"/web/mjon/test/sendKakaoImageUploadAjax.do"})
	public ModelAndView sendKakaoImageUploadAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		, final MultipartHttpServletRequest multiRequest
	) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("result", "loginFail");
				return modelAndView;
			}else {
				
				final Map<String, MultipartFile> files = multiRequest.getFileMap();
				if (!files.isEmpty()){
					
					Map<String, String> resultMap = kakaoApiImageUpload.kakaoApiImageUpload(kakaoVO, files, 0);
					
					//테스트 용 
					System.out.println(resultMap.get("code"));
					System.out.println(resultMap.get("msg"));
					System.out.println(resultMap.get("imgUrl"));
					modelAndView.addObject("code", resultMap.get("code"));
					modelAndView.addObject("msg", resultMap.get("msg"));
					modelAndView.addObject("imgUrl", resultMap.get("imgUrl"));
				}
				
				modelAndView.addObject("result", "success");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		
		return modelAndView;
	}
	/** 카카오 친구톡 이미지 등록 끝----------------------------------------------------------------------- */
	
	/** 카카오 알림톡 발송 시작----------------------------------------------------------------------- */
	// 카카오 템플릿 등록 페이지
	@RequestMapping(value= {"/web/mjon/test/kakaoApiNotityTalkView.do"})
	public String kakaoApiNotityTalkView(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		if(userId == "") {
			return "redirect:/web/user/login/login.do";
		}
		
		// 사용자 아이디를 이용한 발신프로필 조회
		kakaoVO.setUserId(userId); 
		List<KakaoVO> selectKakaoProfileList = kakaoApiService.selectKakaoProfileList(kakaoVO);
		model.addAttribute("kakaoProfileList", selectKakaoProfileList);
		
		return "/uss/ion/test/TestKakaoNotityTalk";
	}
	
	// 카카오 알림톡 전송
	@RequestMapping(value= {"/web/mjon/test/kakaoNotityTalkSendAjax.do"})
	public ModelAndView kakaoNotityTalkSendAjax(
		@ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		, final MultipartHttpServletRequest multiRequest
	) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
		try {
			LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
			
			if(userId == "") {
				modelAndView.addObject("message", "로그인 후 이용이 가능합니다.");
				modelAndView.addObject("result", "loginFail");
				return modelAndView;
			}
			
/**카카오톡 전송 기본 설정  --------------------------------------------*/
			kakaoVO.setUserId(userId);
			kakaoVO.setMsgGroupId(idgenMjonMsgGroupId.getNextStringId());	// 문자 그룹ID 설정
			

/**카카오톡 전송 메세지 설정  ---------- -------------------------------*/
			
			KakaoVO kakaoSendMsgSet = kakaoSendUtil.kakaoSendMsg(kakaoVO);
			kakaoVO.setKakaoSendList(kakaoSendMsgSet.getKakaoSendList());
			
/**전송금액 설정   --------------------------------------------------*/
			KakaoVO priceSet = kakaoSendUtil.kakaoSendPrice(kakaoVO);
			BigDecimal befCash = new BigDecimal(priceSet.getBefCash()).setScale(2, RoundingMode.HALF_EVEN);
			BigDecimal totMsgPrice = new BigDecimal(priceSet.getTotPrice()).setScale(2, RoundingMode.HALF_EVEN);
			
			kakaoVO.setEachPrice(priceSet.getEachPrice());
			kakaoVO.setBefCash(befCash.toString());
			kakaoVO.setTotPrice(totMsgPrice.toString());
			
			//현재 보유 금액이 발송 문자 총 금액보다 클 경우만 문자 발송
			//BigDecimal 비교 연산
			// befCash(현재 보유금액) 값이 totMsgPrice(문자전송 금액) 보다 많으면 문자 전송
			if(befCash.compareTo(totMsgPrice) != -1) { // -1 : befCash < totMsgPrice, 0 : befCash = totMsgPrice, 1 : befCash > totMsgPrice,
				
/**json 파일 설정 -----------------------------------------------*/
				// json파일 생성 여부 확인 후 json파일 생성
				/*if(kakaoVO.getBizJsonYn().equals("Y")) {
					String jsonFileName = kakaoApiJsonSave.kakaoApiJsonSave(kakaoVO);
					kakaoVO.setBizJsonName(jsonFileName); //json 파일명
				}*/
				
/**카카오톡 발송 ----------------------------------------------*/
				MjonMsgReturnVO returnVO = kakaoAlimTalkService.insertKakaoAtSandAjax(kakaoVO);
				
				
				

				
				// 환불 (대체문자 있는 고객중 성공한 고객만 뽑아서 차액 환불)
				// 환불 (대체문자 실패시 대체문자 가격 환불)
				
				
			}else {
				modelAndView.addObject("message", "알림톡 발송에 필요한 보유 잔액이 부족 합니다.");
				modelAndView.addObject("result", "fail");
				return modelAndView;
			}
			
			modelAndView.addObject("result", "success");
			modelAndView.addObject("message", "알림톡 전송이 완료되었습니다.");
			
		}catch(Exception ex){
			ex.printStackTrace();
			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
			modelAndView.addObject("result", "fail");
			return modelAndView;
		}
		
		return modelAndView;
	}
		
	/** 카카오 알림톡 발송 끝----------------------------------------------------------------------- */
	
	/** 카카오 알림톡 발송 시 샘플 엑셀 다운로드, 엑셀 업로드 테스트 메뉴 화면----------------------------------------------------------------------- */
	// 카카오 템플릿 등록 페이지
	@RequestMapping(value= {"/web/mjon/test/kakaoApiNotityTalkViewWithExcel.do"})
	public String kakaoApiNotityTalkViewWithExcel(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		
		LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		if(userId == "") {
			return "redirect:/web/user/login/login.do";
		}
		
		// 사용자 아이디를 이용한 발신프로필 조회
		kakaoVO.setUserId(userId); 
		List<KakaoVO> selectKakaoProfileList = kakaoApiService.selectKakaoProfileList(kakaoVO);
		model.addAttribute("kakaoProfileList", selectKakaoProfileList);
		
		return "/uss/ion/test/TestKakaoNotityTalkWithExcel";
	}
	/** 카카오 알림톡 발송 시 샘플 엑셀 다운로드, 엑셀 업로드 테스트 메뉴 화면 끝----------------------------------------------------------------------- */
	
	/** 카카오 알림톡 발송 시 샘플 엑셀 다운로드 테스트 메뉴----------------------------------------------------------------------- */
	@RequestMapping(value= {"/web/mjon/test/kakaoApiNotityTalkSampleExcelDownload.do"})
	public void kakaoApiNotityTalkSampleExcelDownload(ModelMap model
		, @RequestParam(value = "excelVarNmList", required = false) String[] varNmList
		, HttpServletResponse response
	) throws Exception {
		
		Map<Integer,String[]> aaa = new HashMap<Integer, String[]>();
		
		//받아온 변수 리스트 중복 제거하기
		List<String>  varListDistinct = Arrays.asList(varNmList).stream().distinct().collect(Collectors.toList());
		
		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		CellStyle style = wb.createCellStyle();
		//텍스트 서식 처리 - 수신번호 010 입력 시 0 제거를 방지
		XSSFDataFormat format = (XSSFDataFormat)wb.createDataFormat();
		style.setDataFormat(format.getFormat("@")); //@ 텍스트 서식
		
		Cell cell = null;
		Row row = null;
		
		String fileName ="전송하기 업로드 양식";
		
		String sheetTitle = "전송하기 업로드 양식"; 
		try{
			
				// row, cell 개수 순서대로 증가용 필드
				int rowNumber = 0;
				int celNumber = 0;
				// 엑셀 시트명 설정
				Sheet sheet = wb.createSheet(sheetTitle);
				sheet.setDefaultColumnStyle(0, style); //텍스트 서식 처리 - 수신번호 010 입력 시 0 제거를 방지
				sheet.setColumnWidth(0, 7000);
				for(int i = 1 ; i <= varListDistinct.size(); i++){
					sheet.setColumnWidth(i, 4000);
					sheet.setDefaultColumnStyle(i, style);
				}
				
				row = sheet.createRow(rowNumber++);
	
				cell = row.createCell(celNumber++);
				cell.setCellValue("메시지 수신 휴대폰 번호");
				cell.setCellStyle(style);
	
				for(String field : varListDistinct) {
					cell = row.createCell(celNumber++);
					cell.setCellValue("#{"+field+"}");
					cell.setCellStyle(style);
				}
			
			response.setHeader("Set-Cookie", "fileDownload=true; path=/");
			SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy_MM_dd", Locale.KOREA );
			Date currentTime = new Date ();
			String mTime = mSimpleDateFormat.format ( currentTime );
			fileName = fileName+"("+mTime+")";
			
			response.setHeader("Content-Disposition", String.format("attachment; filename=\""+new String((fileName).getBytes("KSC5601"),"8859_1")+".xlsx"));
			wb.write(response.getOutputStream());

		}catch(Exception e) {
			e.printStackTrace();
			response.setHeader("Set-Cookie", "fileDownload=false; path=/");
			response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.setHeader("Content-Type","text/html; charset=utf-8");
			OutputStream out = null;
			try {
				out = response.getOutputStream();
				byte[] data = new String("fail..").getBytes();
				out.write(data, 0, data.length);
			} catch(Exception ignore) {
				ignore.printStackTrace();
			} finally {
				if(out != null) try { out.close(); } catch(Exception ignore) {}
			}
		}finally {
			// 디스크 적었던 임시파일을 제거합니다.
			wb.dispose();
			try { wb.close(); } catch(Exception ignore) {}
		}
	}
	
	@RequestMapping(value= {"/web/mjon/test/kakaoApiAlimtalkMsgSendAjax.do"})
	@ResponseBody
	public ModelAndView kakaoApiAlimtalkMsgSendAjax(
		KakaoVO kakaoVO
//		String VarNmList 
//		, @RequestParam(value="VarValList[]") ArrayList<String> VarValList
		) throws Exception {
		ModelAndView modelAndView = new ModelAndView();		
		modelAndView.setViewName("jsonView");
		
//		for(String varNm : kakaoVO.getVarNmList())
//		{
//			System.out.println("varNm  : "+ varNm );
//		}
//
//		// value 값
//		List<String[]> varValList = kakaoVO.varValPaser(kakaoVO.getVarValList());
//		
//		try {
//			
//
//			String[] name = kakaoVO.getVarNmList();
//			for(int j=0; j < name.length; j++) {
//				System.out.print(name[j]+" ");
//			}
//			System.out.println();
//			for(int i=0; i < varValList.size(); i++) {
//				for(int j=0; j < varValList.get(i).length; j++) {
//					System.out.print(varValList.get(i)[j]+"   ");
//				}
//				System.out.println();
//			}
//			
//			String[] call = kakaoVO.getCallToList();
//			for(int i=0; i < call.length; i++) {
//				System.out.println(call[i]);
//			}
//			
//		}catch(Exception ex){
//			ex.printStackTrace();
//			modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
//			modelAndView.addObject("result", "fail");
//			return modelAndView;
//		}
		return modelAndView;
	}
	/** 카카오 알림톡 발송 시 샘플 엑셀 다운로드, 엑셀 업로드 테스트 메뉴 끝----------------------------------------------------------------------- */
	/*
	@RequestMapping(value= {"/web/mjon/test/selectCallNumDownFileView.do"})
	public String selectCallNumDownFile(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		) throws Exception {
		
		kakaoVO.setPhmType("01");
		List<KakaoVO>  resultList = kakaoApiService.selectCallNumList(kakaoVO);
		model.addAttribute("totCut01", resultList.get(0).getTotCnt());
		
		kakaoVO.setPhmType("03");
		resultList = kakaoApiService.selectCallNumList(kakaoVO);
		model.addAttribute("totCut03", resultList.get(0).getTotCnt());
		
		
		return "/uss/ion/test/TestCallNumDownFile";
	}
	
	@RequestMapping(value= {"/web/mjon/test/selectCallNumDownFile.do"})
	public void selectCallNumDownFile(ModelMap model
			, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
			, HttpServletResponse response
			, HttpServletRequest request
		) throws Exception {
		
		List<KakaoVO>  resultList = kakaoApiService.selectCallNumList(kakaoVO);
		
		String zipFile = "test.zip";
		String downloadFileName = "result";
		
		for(int i=0; i < resultList.size(); i++) {
			System.out.println("첨부파일 : @@"+resultList.get(i).getAtchFileId()+"@@");
			if(resultList.get(i).getAtchFileId() != null && !resultList.get(i).getAtchFileId().equals("")) {
		
				KakaoVO fileVO = new KakaoVO();
				
				fileVO.setAtchFileId(resultList.get(i).getAtchFileId());
				List<KakaoVO>  fileInfo = kakaoApiService.selectCallNumInfo(kakaoVO);
				for(int j=0; j < fileInfo.size(); j++) {
					
				}
			}
		}
	}
	*/
	@RequestMapping(value= {"/uss/ion/msg/selectDownFileView.do"})
	public String selectDownFileView(ModelMap model
		, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
		, RedirectAttributes redirectAttributes
		
		) throws Exception {
		
		//관리자 로그인 여부 체크
    	String isLogin = checkLoginUtil.isAdminLogin4PageMove(redirectAttributes);    	
    	if (!"Y".equals(isLogin)) return isLogin;
    	
		List<KakaoVO>  resultList = kakaoApiService.selectFileList(kakaoVO);
		model.addAttribute("totCut", resultList.get(0).getTotCnt());
		
		
		
		return "/uss/ion/test/TestDownFile";
	}
	
	@RequestMapping(value= {"/uss/ion/msg/selectDownFile.do"})
	public void selectDownFile(ModelMap model
			, @ModelAttribute("kakaoVO")  KakaoVO kakaoVO
			, HttpServletResponse response
			, HttpServletRequest request
		) throws Exception {
		List<KakaoVO>  resultList = kakaoApiService.selectFileList(kakaoVO);
		
		String zipFile = "test.zip";
		String downloadFileName = "result";

		
		FileOutputStream fout = new FileOutputStream(zipFile);
	    ZipOutputStream zout = new ZipOutputStream(fout);
		
	    System.out.println("사용자 수량  !! "+resultList.size());
	    
		for(int i=0; i < resultList.size(); i++) {
			
			System.out.println("사업자등록증 : @@"+resultList.get(i).getAtchFileId()+"@@");
			System.out.println("재직증명서 : @@"+ resultList.get(i).getWorkAtchFileId()+"@@");
			if(resultList.get(i).getAtchFileId() != null && !resultList.get(i).getAtchFileId().equals("")) {
				KakaoVO fileInfo = new KakaoVO();
				fileInfo.setAtchFileId(resultList.get(i).getAtchFileId());
				KakaoVO fvo = kakaoApiService.selectFileInfo(fileInfo);
				
				String fileNm = fvo.getStreFileNm();
				String filePath = fvo.getFileStreCours();
				
				System.out.println("파일위치 : @@"+filePath);
				System.out.println("파일명 : @@"+fileNm);
				
				
				File uFile = new File(filePath, fileNm);
				long fSize = uFile.length();
				if (fSize > 0) {
					ZipEntry zipEntry = new ZipEntry("/"+resultList.get(i).getUserId()+"/사업자등록증."+fvo.getFileExtsn());
			        zout.putNextEntry(zipEntry);
			        
			        
			        FileInputStream fin = new FileInputStream(uFile);
			        byte[] buffer = new byte[1024];
			        int length;

			        // input file을 1024바이트로 읽음, zip stream에 읽은 바이트를 씀
			        while((length = fin.read(buffer)) > 0){
			            zout.write(buffer, 0, length);
			        }
			        
			        zout.closeEntry();
			        fin.close();
				}
			}
			
			if(resultList.get(i).getWorkAtchFileId() != null && !resultList.get(i).getWorkAtchFileId().equals("")) {
				KakaoVO fileInfo = new KakaoVO();
				fileInfo.setAtchFileId(resultList.get(i).getWorkAtchFileId());
				KakaoVO fvo = kakaoApiService.selectFileInfo(fileInfo);
				
				String fileNm = fvo.getStreFileNm();
				String filePath = fvo.getFileStreCours();
				
				System.out.println("파일위치 : @@"+filePath);
				System.out.println("파일명 : @@"+fileNm);
				
				File uFile = new File(filePath, fileNm);
				long fSize = uFile.length();
				if (fSize > 0) {
					ZipEntry zipEntry = new ZipEntry("/"+resultList.get(i).getUserId()+"/재직증명서."+fvo.getFileExtsn());
			        zout.putNextEntry(zipEntry);
			        
			        
			        FileInputStream fin = new FileInputStream(uFile);
			        byte[] buffer = new byte[1024];
			        int length;

			        // input file을 1024바이트로 읽음, zip stream에 읽은 바이트를 씀
			        while((length = fin.read(buffer)) > 0){
			            zout.write(buffer, 0, length);
			        }
			        
			        zout.closeEntry();
			        fin.close();
				}
			}
		}
		
		 zout.close();
		 
		response.setContentType("application/zip");
		response.addHeader("Content-Disposition", "attachment; filename=" + downloadFileName + ".zip");
		
		FileInputStream fis=new FileInputStream(zipFile);
		BufferedInputStream bis=new BufferedInputStream(fis);
		ServletOutputStream so=response.getOutputStream();
		BufferedOutputStream bos=new BufferedOutputStream(so);
		
		byte[] data=new byte[2048];
		int input=0;
		
		while((input=bis.read(data))!=-1){
			bos.write(data,0,input);
			bos.flush();
		}
		
		if(bos!=null) bos.close();
		if(bis!=null) bis.close();
		if(so!=null) so.close();
		if(fis!=null) fis.close();


	}
	
	private String getBrowser(HttpServletRequest request) {
		String header = request.getHeader("User-Agent");
		if (header.indexOf("MSIE") > -1) {
			return "MSIE";
		} else if (header.indexOf("Trident") > -1) { // IE11 문자열 깨짐 방지
			return "Trident";
		} else if (header.indexOf("Chrome") > -1) {
			return "Chrome";
		} else if (header.indexOf("Opera") > -1) {
			return "Opera";
		}
		return "Firefox";
	}
	
	private void setDisposition(String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String browser = getBrowser(request);

		String dispositionPrefix = "attachment; filename=";
		String encodedFilename = null;

		if (browser.equals("MSIE")) {
			encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
		} else if (browser.equals("Trident")) { // IE11 문자열 깨짐 방지
			encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
		} else if (browser.equals("Firefox")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Opera")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Chrome")) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < filename.length(); i++) {
				char c = filename.charAt(i);
				if (c > '~') {
					sb.append(URLEncoder.encode("" + c, "UTF-8"));
				} else {
					sb.append(c);
				}
			}
			encodedFilename = sb.toString();
		} else {
			//throw new RuntimeException("Not supported browser");
			throw new IOException("Not supported browser");
		}

		response.setHeader("Content-Disposition", dispositionPrefix + encodedFilename);

		if ("Opera".equals(browser)) {
			response.setContentType("application/octet-stream;charset=UTF-8");
		}
	}
}
