package itn.let.mjo.pay.web;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
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.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.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.service.FileVO;
import itn.com.cmm.util.MJUtil;
import itn.com.cmm.util.RedirectUrlMaker;
import itn.com.uss.ion.fms.service.FmsFileVO;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.mail.service.StatusResponse;
import itn.let.mjo.event.service.MjonEventCheckVO;
import itn.let.mjo.event.service.MjonEventService;
import itn.let.mjo.event.service.MjonEventVO;
import itn.let.mjo.mjocommon.MjonCommon;
import itn.let.mjo.msgdata.service.MjonMsgDataService;
import itn.let.mjo.pay.service.MjonPayService;
import itn.let.mjo.pay.service.MjonPayVO;
import itn.let.mjo.pay.service.RefundService;
import itn.let.mjo.pay.service.RefundVO;
import itn.let.mjo.tax.service.TaxService;
import itn.let.mjo.tax.service.TaxVO;
import itn.let.sym.site.service.EgovSiteManagerService;
import itn.let.sym.site.service.JoinSettingVO;
import itn.let.uat.uia.service.EgovLoginService;
import itn.let.uss.umt.service.EgovMberManageService;
import itn.let.uss.umt.service.MberManageVO;
import itn.let.utl.user.service.MjonNoticeSendUtil;

@Controller
public class RefundController {
	@Resource(name = "refundService")
    private RefundService refundService;
	
	/** EgovMessageSource */
    @Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;

    @Resource(name="EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;
    
    @Resource(name="EgovFileMngService")
    private EgovFileMngService fileMngService;
    
    @Resource(name = "EgovFileMngService")
	private EgovFileMngService fileService;
    
    /** EgovLoginService */
	@Resource(name = "loginService")
	private EgovLoginService loginService;
	
	@Resource(name = "EgovCmmUseService")
    private EgovCmmUseService cmmUseService;
	
	@Resource(name = "mjonPayService")
    private MjonPayService mjonPayService;
	
	@Resource(name="taxService")
    private TaxService taxService;
	
	/* MjonMsgDataService */
	@Resource(name = "MjonMsgDataService")
    private MjonMsgDataService mjonMsgDataService;
	
	/** 알림전송 Util */
	@Resource(name = "mjonNoticeSendUtil")
	private MjonNoticeSendUtil mjonNoticeSendUtil;
	
	@Resource(name="MjonCommon")
	private MjonCommon mjonCommon;
	
	@Resource(name = "mberManageService")
	private EgovMberManageService mberManageService;
	
	/** 사이트 설정 */ 
	@Resource(name = "egovSiteManagerService")
	EgovSiteManagerService egovSiteManagerService;
	
	@Resource(name = "MjonEventService")
    private MjonEventService mjonEventService;
	
    /**
     * 환불요청 목록 페이지
     * @param RefundVO
     * @param model
     * @return "/uss/ion/pay/RefundList"
     * @throws Exception
     */
	@RequestMapping(value="/uss/ion/pay/RefundList.do")
	public String RefundList(@ModelAttribute("RefundVO") RefundVO refundVO, 
			HttpServletRequest request ,
			ModelMap model) throws Exception{
		

		System.out.println("+ uss/ion/pay/RefundList. :: ");
		
		if(refundVO.getPageUnit() != 10) {
			refundVO.setPageUnit(refundVO.getPageUnit());
		}
		
		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(refundVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(refundVO.getPageUnit());
		paginationInfo.setPageSize(refundVO.getPageSize());
		
		refundVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		refundVO.setLastIndex(paginationInfo.getLastRecordIndex());
		refundVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		if("".equals(refundVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			refundVO.setSearchSortCnd("frstRegisterPnttm");
			refundVO.setSearchSortOrd("desc");
		}
		
		ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
		
		List<RefundVO> refundList = refundService.selectRefundList(refundVO);
		
        int totCnt = 0;
        if(refundList.size() > 0) {
			totCnt = refundList.get(0).getTotCnt();
		}
        model.addAttribute("refundList", refundList);
        
      //double 지수표현 제거를 위해 BigDecimal 사용
		List<BigDecimal> cashList = new ArrayList<>();
		for(int i = 0 ; i < refundList.size() ; i++) {
			BigDecimal b2 = new BigDecimal(refundList.get(i).getRefundMoney()).setScale(2, RoundingMode.HALF_EVEN);
			cashList.add(b2);
		}
		
		model.addAttribute("cashList", cashList);
        
        paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("paginationInfo", paginationInfo);
		
		return "/uss/ion/pay/RefundList";
        
	}
	
	/**
     * 환불요청 상세 페이지
     * @param RefundVO
     * @param model
     * @return "/uss/ion/pay/RefundList"
     * @throws Exception
     */
	@RequestMapping(value= {"/uss/ion/pay/RefundDetail.do"})
	public String RefundDetail(@ModelAttribute("RefundVO") RefundVO refundVO, 
			@ModelAttribute("searchVO") MjonPayVO mjonPayVO,
			HttpServletRequest request , 
			RedirectAttributes redirectAttributes,
			ModelMap model) throws Exception{
		
		// 삭제 및 노 데이터 조회 시
		if (refundVO == null) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("info.nodata.msg"));
			redirectAttributes.addAttribute("pageIndex", mjonPayVO.getPageIndex());
			return "redirect:/uss/ion/pay/RefundList.do";
		}
		// 환불업체 조회
		refundVO = refundService.selectRefundDetail(refundVO);
		if(mjonPayVO.getPageUnit() != 10) {
			mjonPayVO.setPageUnit(mjonPayVO.getPageUnit());
		}
		
		// 통장사본 첨부파일이 있을경우
		if(refundVO.getBankAtchFileId() !=null) {
			FileVO fileVO = new FileVO();
			fileVO.setAtchFileId(refundVO.getBankAtchFileId());
			List<FileVO> fileList = fileService.selectFileInfs(fileVO);
			model.addAttribute("bankfileList", fileList);	
		}
		
		// 증빙서류 첨부파일이 있을경우
		if(refundVO.getDocuAtchFileId() !=null) {
			FileVO fileVO = new FileVO();
			fileVO.setAtchFileId(refundVO.getDocuAtchFileId());
			List<FileVO> fileList = fileService.selectFileInfs(fileVO);
			model.addAttribute("docufileList", fileList);	
		}

		// 관리자 첨부파일이 있을경우
		if(refundVO.getAdmAtchFileId() !=null) {
			FileVO fileVO = new FileVO();
			fileVO.setAtchFileId(refundVO.getAdmAtchFileId());
			List<FileVO> fileList = fileService.selectFileInfs(fileVO);
			model.addAttribute("resultFileList", fileList);	
		}
		
		ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
		//환불요청 코드 조회
		comDefaultCodeVO.setCodeId("ITN041");
		List<?> codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("refundStatuscode", codeResult);
		
		//예금주 구분 코드 조회
		comDefaultCodeVO.setCodeId("ITN042");
		codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("dpsitTypecode", codeResult);
		
		//회원 정보 조회
		RefundVO mberInfoVO = refundService.selectRefundMberInfo(refundVO);
		model.addAttribute("mberInfoVO", mberInfoVO);
		model.addAttribute("refundVO", refundVO);
		
		
		//관리자 정보 조회
		RefundVO adminInfo = refundService.selectRefundAdminInfo(refundVO);
		model.addAttribute("adminInfo", adminInfo);
		
		
		
		return "/uss/ion/pay/RefundDetail";
	}
	

	/**
	 * 환불요청 상세 페이지
	 * @param RefundVO
	 * @param model
	 * @return "/uss/ion/pay/RefundList"
	 * @throws Exception
	 */
	@RequestMapping(value= {"/uss/ion/pay/refundDetailPayListAjax.do"})
	public String RefundDetailPayListAjax(@ModelAttribute("RefundVO") RefundVO refundVO, 
			@ModelAttribute("searchVO") MjonPayVO mjonPayVO,
			HttpServletRequest request , 
			RedirectAttributes redirectAttributes,
			ModelMap model) throws Exception{
			
			
			/** pageing */
			PaginationInfo paginationInfo = new PaginationInfo();
			paginationInfo.setCurrentPageNo(mjonPayVO.getPageIndex());
			paginationInfo.setRecordCountPerPage(mjonPayVO.getPageUnit());
			paginationInfo.setPageSize(mjonPayVO.getPageSize());

			
			mjonPayVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
			mjonPayVO.setLastIndex(paginationInfo.getLastRecordIndex());
			mjonPayVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
			
			mjonPayVO.setSearchSortCnd("moid");
			mjonPayVO.setSearchSortOrd("desc");
			
			mjonPayVO.setSearchCondition("1");
			mjonPayVO.setSearchKeyword(refundVO.getMberId());
			
			List<MjonPayVO> resultList = mjonPayService.selectPayListForRefund(mjonPayVO);
			
			model.addAttribute("resultList", resultList);
			model.addAttribute("mjonPayVO", mjonPayVO);
			paginationInfo.setTotalRecordCount(resultList.size() > 0 ? ((MjonPayVO)resultList.get(0)).getTotCnt() : 0);
			model.addAttribute("paginationInfo", paginationInfo);
			
			return "/uss/ion/pay/"+refundVO.getReturnUrl();
		
		
	}
	
	/**
     * 환불요청 등록 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/insertRefundAjax.do","/web/member/pay/insertRefundAjax.do"})
	public ModelAndView insertRefundAjax(final MultipartHttpServletRequest multiRequest
			, RefundVO refundVO , HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {

			refundVO.setMberId(user.getId());
			int userCnt = refundService.selectUserChk(refundVO);
			
			if (0 == userCnt) {// 비밀번호 다름
				modelAndView.addObject("msg", "비밀번호가 틀립니다.");
				modelAndView.addObject("status", "fail");
				return modelAndView;
			}
			
			/*if(true) {
				modelAndView.addObject("msg", "디버그존~");
				modelAndView.addObject("status", "fail");
				return modelAndView;
			}*/
			
			String atchFileId = "";
			final Map<String, MultipartFile> files = multiRequest.getFileMap();
			if (!files.isEmpty()) {
				if(files.containsKey("bank")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>(); 
					tmpMap.put("bank", files.get("bank"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setBankAtchFileId(atchFileId);
				}
				if(files.containsKey("docu")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>();
					tmpMap.put("docu", files.get("docu"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setDocuAtchFileId(atchFileId);
				}
			}
			refundVO.setMberId(user.getId());
			refundVO.setMberNm(user.getName());
			refundVO.setFrstRegisterId(user.getId());
			refundVO.setRefundStatus("1");
			refundService.insertRefund(refundVO);
			
			// 법인폰 알람여부 체크
			JoinSettingVO joinSettingVO = new JoinSettingVO();
			joinSettingVO = egovSiteManagerService.selectAdminNotiDetail();
			// 이메일 체크
			if (joinSettingVO != null && joinSettingVO.getEmailNoti().equals("Y")) {
				String emailTitle = "결제관리 > 환불 요청";
				// CS관리자 이메일 알림전송
				mjonNoticeSendUtil.csAdminEmailNoticeSend(user.getName(), user.getId(), emailTitle);			
			}			

			// SLACK 체크
			if (joinSettingVO != null && joinSettingVO.getSlackNoti().equals("Y")) {			
				// Slack 메시지 발송(단순본문)
				String msg = "[문자온] 환불 요청 - " + user.getName() +"("+ user.getId() + ")";
				mjonCommon.sendSimpleSlackMsg(msg);
			}
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	/**
     * 환불신청금액(환불요청 상태) Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/web/member/pay/refMonSumAjax.do"})
	public ModelAndView RefundMoneySumAjax(RefundVO refundVO, HttpServletRequest request) throws Exception {

		LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");

		boolean isSuccess = true;
		String msg = "";
		int refundMoneySum = 0;
		int userMoney = 0;
		
		try {
			refundVO.setMberId(loginVO.getId());
			
			refundVO = refundService.selectRefundMberInfo(refundVO);
	    	userMoney =  (int)Double.parseDouble(refundVO.getMberMoney());	// 보유Cash
			
			refundMoneySum = refundService.selectRefundMoneySum(refundVO);	// 환불신청금액(환불요청 상태)

		} catch (Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}
	
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("userMoney", userMoney);
		modelAndView.addObject("refundMoneySum", refundMoneySum);

		return modelAndView;
	}	
	
	/**
     * 환불요청 상태 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateRefundAjax.do"})
	public ModelAndView updateRefundAjax(RefundVO refundVO
			, HttpServletRequest request){
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			
			refundVO.setLastUpdusrId(user.getId());
			
			refundService.updateRefundStatus(refundVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	
	/**
     * 환불요청 환불처리완료 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateCompleteRefundAjax.do"})
	public ModelAndView updateCompleteRefundAjax(RefundVO refundVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request
			, @ModelAttribute("fmsFileVO") FmsFileVO fmsFileVO
			, @ModelAttribute("fileVO") FileVO fileVO
			, final MultipartHttpServletRequest multiRequest
			) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String s_status	=	"success";
		
		try {
			
			//회원 정보 조회
			RefundVO mberInfoVO = refundService.selectRefundMberInfo(refundVO);
			
			if(Float.valueOf(mberInfoVO.getMberMoney()) 
					< Float.valueOf(refundVO.getRefundCash())) {
				
				modelAndView.addObject("status", "moreThanUserMoney");
				modelAndView.addObject("msg", "현재 회원의 보유금액보다 큰 금액을 환불 할 수 없습니다.");
				
				return modelAndView;
			}
			if(refundVO.getRefundPoint() != null || refundVO.getRefundPoint() != "") {
				if(Integer.parseInt(mberInfoVO.getMberPoint()) 
						< Integer.parseInt(refundVO.getRefundPoint())) {
					
					modelAndView.addObject("status", "moreThanUserPoint");
					modelAndView.addObject("msg", "현재 회원의 보유포인트보다 큰 포인트을 환불 할 수 없습니다.");
					
					return modelAndView;
				}
			}
			
		} catch (Exception e) {
			modelAndView.addObject("status", "fail");
			return modelAndView;
		}
		
		
		
		try {
			
			//파일업로드
			String atchFileId = "";
			final Map<String, MultipartFile> files = multiRequest.getFileMap();
			if (!files.isEmpty()) {
				List<FileVO> result = fileUtil.parseFileInf(files, "RFND_", 0, "", "", "");
				atchFileId = fileMngService.insertFileInfs(result);
				refundVO.setAdmAtchFileId(atchFileId);
			}
			
			//1. mj_refund 테이블 update
			refundVO.setLastUpdusrId(user.getId());
			refundVO.setRefundHandleId(user.getId());
			refundService.updateCompleteRefundStatus(refundVO);
			
			//2. cash, point 처리 전 VO 세팅
			MjonPayVO mjonPayVO = new MjonPayVO();
			mjonPayVO.setUserId(refundVO.getMberId());
			mjonPayVO.setCash(Float.valueOf(refundVO.getRefundCash()) * -1);
			mjonPayVO.setPoint(Integer.parseInt(refundVO.getRefundPoint()) * -1);
			mjonPayVO.setDelFlag("N");
			mjonPayVO.setFrstRegisterId(user.getId());
			
			//2-1. mj_cash 테이블 insert
			mjonPayVO.setMemo("환불처리 " + refundVO.getRefundCash() + "원");
			mjonPayService.insertCash(mjonPayVO);
			
			//2-2. mj_point 테이블 insert
			mjonPayVO.setMemo("환불처리 " + refundVO.getRefundPoint() + "포인트");
			mjonPayService.insertPoint(mjonPayVO);
			
			
			//modelAndView.addObject("status", "success");
			s_status	=	"success";
			
		}catch (Exception e) {
			//modelAndView.addObject("status", "fail");
			 s_status	=	"fail";
		}
		
		modelAndView.addObject("status", s_status);

		System.out.println("s_status : " + s_status);
		
		//환불처리가 완료된 이후에 상태를 확인해서 이벤트 종료 처리를 한다.
		//2023-03-07 추가
		try {
			//환불처리가 완료된 이후에 상태를 확인해서 이벤트 종료 처리를 한다.
			if ("success".equals(s_status)) {
				
				//필요한 값을 가져온다.발송건수, 보유캐시잔액, 포인트가 모두 0이고, 이벤트가 진행중
				MjonEventCheckVO mjonEventCheckVO	=	new MjonEventCheckVO();
				mjonEventCheckVO.setMberId(refundVO.getMberId());			
				mjonEventCheckVO	=	mjonEventService.selectEventStatus(mjonEventCheckVO);
				
				//이벤트 테이블에 값이 없으면 null 이다.
				if (mjonEventCheckVO!=null) {						
					//step1.발송건수, 보유캐시잔액, 포인트가 모두 0이고, 이벤트가 진행중(Y)인지 확인
					//step1-1.MjonEventCheckVOstep1-1.Y면 이벤트 취소 처리
					if (Double.parseDouble(mjonEventCheckVO.getUserMoney())<=0
							//&&	Integer.parseInt(mjonEventCheckVO.getUserPoint())<=0
							&& "Y".equals(mjonEventCheckVO.getEventStatus())
							) {						
						//이벤트 강제 종료 처리 
						MjonEventVO mjonEventVO	=	new MjonEventVO();
						mjonEventVO.setEventEndDate(MJUtil.getRealTime());
						mjonEventVO.setEventStatus("E");
						mjonEventVO.setMberId(refundVO.getMberId());

						//
						mjonEventVO.setEventInfoId(mjonEventCheckVO.getEventInfoId());
						mjonEventVO.setEventMemo("관리자 전액 환불 처리 후 [자동]으로 이벤트 종료 처리 진행");
						
						
						//이벤트 강제 처리에 따른 회원 메모 추가
						MberManageVO mberManageVO = new MberManageVO(); 
						mberManageVO.setMberId(mjonEventVO.getMberId());
						mberManageVO.setFrstRegisterId(user.getId());//관리자 아이디
						mberManageVO.setUniqId(mjonEventVO.getUniqId());//회원의 고유 아이디
						mberManageVO.setMemoCn("이벤트 강제 종료 처리 사유 : " + mjonEventVO.getEventMemo());

				    	
						//이벤트 강제종료 처리 및 회원 메모 입력 대상 테이블 정보
				    	/*
				    	 *	UPDATE MJ_EVENT_MBER_INFO 
				    	 *		SET EVENT_STATUS = 'E' 
				    	 *		, LAST_UPDT_PNTTM = NOW() 
				    	 *		,EVENT_END_DATE = NOW() 
				    	 *		,EVENT_MEMO = '관리자 전액 환불 처리 후 [자동]으로 이벤트 종료 처리 진행' 
				    	 *		,EVENT_REMAIN_CASH = 0.0
         					WHERE MBER_ID = 'ssyoon88'
           						AND EVENT_INFO_ID = '518'
           						
           						&&
           				INSERT INTO lettngnrlmber_memo
           				
				    	 * */
						int resultCnt = mjonEventService.updateEventAdmClosedStatus(mjonEventVO, mberManageVO);
						
						
					}								
					//step1-2.N면 skip
				}				
			}
			
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}

		
		return modelAndView;
	}
	
	/**
     * 환불요청 환불처리불가 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateCancelRefundAjax.do"})
	public ModelAndView updateCancelRefundStatus(RefundVO refundVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			
			refundVO.setLastUpdusrId(user.getId());
			refundVO.setRefundHandleId(user.getId());
			
			refundService.updateCancelRefundStatus(refundVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	/**
     * 환불요청 재등록 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateRestRefundAjax.do"})
	public ModelAndView updateRestRefundAjax(RefundVO refundVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			
			refundVO.setLastUpdusrId(user.getId());
			refundVO.setRefundHandleId(user.getId());
			
			refundService.updateRestRefundStatus(refundVO);
			
			
			
			String beforeStatus = refundVO.getBeforeRefundStatus();
			String afterStatus = refundVO.getRefundStatus();
			
			
			//2. cash, point 처리 전 VO 세팅
			MjonPayVO mjonPayVO = new MjonPayVO();
			mjonPayVO.setUserId(refundVO.getMberId());
			mjonPayVO.setDelFlag("N");
			mjonPayVO.setFrstRegisterId(user.getId());
			
		

			if(afterStatus.equals("3")) {// 처리완료로 변경 시
				
				if(beforeStatus.equals("4")) {
					mjonPayVO.setMemo("환불처리 " + refundVO.getRefundCash() + "원");
					mjonPayVO.setCash(Float.valueOf(refundVO.getRefundCash()) * -1);
					//2-1. mj_cash 테이블 insert
					mjonPayService.insertCash(mjonPayVO);
					
					mjonPayVO.setMemo("환불처리 " + refundVO.getRefundPoint() + "포인트");
					mjonPayVO.setPoint(Integer.parseInt(refundVO.getRefundPoint()) * -1);
					//2-2. mj_point 테이블 insert
					mjonPayService.insertPoint(mjonPayVO);
					
				}else {
					// 이전 환불 포인트 - 신규 입력 포인트
					int resultPoint =	Integer.parseInt(refundVO.getRefundPoint()) - Integer.parseInt(refundVO.getBeforePoint());
					resultPoint = resultPoint * -1;
					System.out.println("이전 포인트 : "+refundVO.getBeforePoint());
					System.out.println("신규 포인트 : "+refundVO.getRefundPoint());
					System.out.println("계산 포인트 : "+resultPoint);
					if(resultPoint != 0) {
						mjonPayVO.setMemo("환불처리 " + refundVO.getRefundPoint() + "포인트");
						mjonPayVO.setPoint(resultPoint);
						//2-2. mj_point 테이블 insert
						mjonPayService.insertPoint(mjonPayVO);
					}
				}
				
			}else if(afterStatus.equals("4")) {// 처리불가로 변경 시
				
				if(beforeStatus.equals("3")) {
					mjonPayVO.setMemo("환불처리 " + refundVO.getRefundCash() + "원");
					mjonPayVO.setCash(Float.valueOf(refundVO.getRefundCash()));
					//2-1. mj_cash 테이블 insert
					mjonPayService.insertCash(mjonPayVO);
					
					mjonPayVO.setMemo("환불처리 " + refundVO.getBeforePoint() + "포인트");
					mjonPayVO.setPoint(Integer.parseInt(refundVO.getBeforePoint()));
					//2-2. mj_point 테이블 insert
					mjonPayService.insertPoint(mjonPayVO);
				}
			}
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	/**
     * 환불요청 결제취소 완료 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateRefundPayCanCleAjax.do"})
	public ModelAndView updateRefundPayCanCleAjax(RefundVO refundVO
			, MjonPayVO mjonPayVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			refundVO.setLastUpdusrId(user.getId());
			
			// 1. mj_pg 테이블 결제 상태 update
			mjonPayService.updateMjonPgStatus(refundVO);
			
			// 2. mj_refund 테이블에 moid update
			refundVO.setMberId(user.getId());
			refundService.updateRefundMoid(refundVO);
			
			// 3. mj_tax 테이블 update
			TaxVO taxVO = new TaxVO();
			taxVO.setMoid(refundVO.getMoid());
			taxVO.setPayCancleDiv(refundVO.getPayCancleDiv()); // 결제 취소 완료/결제취소 취소 요청 구분 (9 - 결제취소 완료, 1 - 결제취소 취소)
			taxService.updateTaxForRefundCancle(taxVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	/**
     * 환불요청 메모 업데이트 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/updateRefundMemoAjax.do"})
	public ModelAndView updateRefundMemoAjax(RefundVO refundVO) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			refundVO.setLastUpdusrId(user.getId());
			
			refundService.updateRefundMemo(refundVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	
	
	/**
     * 환불요청 재등록 페이지
     * @param RefundVO
     * @param model
     * @return "/uss/ion/pay/RefundReRegist"
     * @throws Exception
     */
	@RequestMapping(value= {"/uss/ion/pay/RefundReRegist.do"})
	public String RefundReRegist(@ModelAttribute("RefundVO") RefundVO refundVO, 
			@ModelAttribute("searchVO") MjonPayVO mjonPayVO,
			HttpServletRequest request , 
			RedirectAttributes redirectAttributes,
			ModelMap model) throws Exception{
		
		// 삭제 및 노 데이터 조회 시
		if (refundVO == null) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("info.nodata.msg"));
			redirectAttributes.addAttribute("pageIndex", mjonPayVO.getPageIndex());
			return "redirect:/uss/ion/pay/RefundList.do";
		}
		
		refundVO = refundService.selectRefundDetail(refundVO);
		
		if(mjonPayVO.getPageUnit() != 10) {
			mjonPayVO.setPageUnit(mjonPayVO.getPageUnit());
		}
		
		ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
		//환불요청 코드 조회
		comDefaultCodeVO.setCodeId("ITN041");
		List<?> codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("refundStatuscode", codeResult);
		
		//회원 정보 조회
		RefundVO mberInfoVO = refundService.selectRefundMberInfo(refundVO);
		
		model.addAttribute("mberInfoVO", mberInfoVO);
		model.addAttribute("refundVO", refundVO);
		
		return "/uss/ion/pay/RefundReRegist";
	}
	
	@RequestMapping(value = {"/uss/ion/pay/deleteRefundInfo.do"})
    public String deleteRefundInfo(
    		@RequestParam("del") String[] del
    		, @ModelAttribute("RefundVO") RefundVO refundVO
    		, HttpServletRequest request
    		, RedirectAttributes redirectAttributes
    		, Model model) throws Exception {
		RedirectUrlMaker redirectUrlMaker = new RedirectUrlMaker("/uss/ion/pay/RefundList.do");
		try {
			LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
			String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
		
			for(String id: del) {
				refundVO.setLastUpdusrId(userId);
				refundVO.setRefundId(id);
				refundService.deleteRefundInfo(refundVO);
			}
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.update"));
			return redirectUrlMaker.getRedirectUrl();
		}catch(Exception e) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.update"));
		}
		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		return redirectUrlMaker.getRedirectUrl();
	}
	
	
	/**
     * 환불요청 재등록 Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/insertRefundReRegistAjax.do"})
	public ModelAndView insertRefundReRegistAjax(final MultipartHttpServletRequest multiRequest
			, RefundVO refundVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			
			String atchFileId = "";
			final Map<String, MultipartFile> files = multiRequest.getFileMap();
			if (!files.isEmpty()) {
				if(files.containsKey("bank")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>(); 
					tmpMap.put("bank", files.get("bank"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setBankAtchFileId(atchFileId);
				}
				if(files.containsKey("docu")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>();
					tmpMap.put("docu", files.get("docu"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setDocuAtchFileId(atchFileId);
				}
			}
			
			refundVO.setFrstRegisterId(user.getId());
			refundVO.setRefundStatus("1");
			refundService.insertRefund(refundVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	/**
	 * 결제취소 등록
	 * @param RefundVO
	 * @param model
	 * @return "/uss/ion/pay/cancelRegist"
	 * @throws Exception
	 */
	@RequestMapping(value="/uss/ion/pay/cancelRegist.do")
	public String cancelRegist(@ModelAttribute("refundVO") RefundVO refundVO) throws Exception{
		return "/uss/ion/pay/cancelRegist";
	}
	
	/**
	 * 환불 등록
	 * @param RefundVO
	 * @param model
	 * @return "/uss/ion/pay/RefundRegist"
	 * @throws Exception
	 */
	@RequestMapping(value="/uss/ion/pay/refundRegist.do")
	public String refundRegist(@ModelAttribute("refundVO") RefundVO refundVO) throws Exception{
		return "/uss/ion/pay/RefundRegist";
	}	

	/**
	 * 결제취소 페이지
	 * @param refundVO
	 * @param mjonPayVO
	 * @param request
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws Exception
	 */						 
	@RequestMapping(value= "/uss/ion/pay/cancelDetail.do")
	public String cancelDetail(@ModelAttribute("refundVO") RefundVO refundVO
				, ModelMap model) throws Exception{
		refundVO = refundService.selectRefundDetail(refundVO);
		try {
			if(StringUtils.isNotEmpty(refundVO.getRefundPoint()))
			{
				refundVO.setRefundCash(refundVO.getRefundCash().split("\\.")[0]);
				refundVO.setRefundPoint(refundVO.getRefundPoint().split("\\.")[0]);	
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		model.addAttribute("refundVO", refundVO);
		return "/uss/ion/pay/cancelDetail";
	}
	
    /**
	 * 입력한 사용자아이디의 중복여부를 체크하여 사용가능여부를 확인
	 * @param checkId
	 * @return
     * @throws Exception 
	 */
	@RequestMapping(value = "/uss/ion/pay/cancelRegistIdChkAjax.do")
	public ResponseEntity<StatusResponse> cancelRegistIdChkAjax(@RequestParam String checkId) throws Exception {
		return ResponseEntity.ok().body(refundService.cancelRegistIdChkAjax(checkId));
	}
	
	/**
	 * 결제취소요청 취소 처리 
	 * @param refundVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uss/ion/pay/updateProcStatusAjax.do")
	public ResponseEntity<StatusResponse> updateProcStatusAjax(RefundVO refundVO) throws Exception {
		return ResponseEntity.ok().body(refundService.updateProcStatusAjax(userInfoAdd(refundVO)));
	}
	
	
	/**
	 * 결제취소 등록 Ajax
	 * @param refundVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"/uss/ion/pay/insertPayCanAjax.do"})
	public ResponseEntity<StatusResponse>  insertPayCanAjax(RefundVO refundVO) throws Exception {
		return ResponseEntity.ok().body(refundService.insertPayCanAjax(userInfoAdd(refundVO)));
	}
	

	@RequestMapping(value = {"/uss/ion/msg/refMonInsAjax.do"})
	public ModelAndView refMonInsAjax(final MultipartHttpServletRequest multiRequest
			, RefundVO refundVO , HttpServletRequest request) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		try {
			String atchFileId = "";
			final Map<String, MultipartFile> files = multiRequest.getFileMap();
			if (!files.isEmpty()) {
				if(files.containsKey("bank")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>(); 
					tmpMap.put("bank", files.get("bank"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setBankAtchFileId(atchFileId);
				}
				if(files.containsKey("docu")){
					Map<String, MultipartFile> tmpMap = new LinkedHashMap<>();
					tmpMap.put("docu", files.get("docu"));
					List<FileVO> result = fileUtil.parseFileInf(tmpMap, "REFUND_", 0, "", "", "");
					atchFileId = fileMngService.insertFileInfs(result);
					refundVO.setDocuAtchFileId(atchFileId);
				}
			}

			refundVO.setFrstRegisterId(refundVO.getMberId());
			refundVO.setRefundStatus("1");
			refundService.insertRefund(refundVO);
			
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			System.out.println("REFUND ERROR : " + e.getMessage());
			
			modelAndView.addObject("status", "fail");
		}
		
		return modelAndView;
	}
	
	
	/**
     * 환불신청금액(환불요청 상태) Ajax
     * @param RefundVO
     * @param model
     * @return modelAndView
     * @throws Exception
     */
	@RequestMapping(value = {"/uss/ion/pay/refMonSumAjax.do"})
	public ModelAndView refMonSumAjax(RefundVO refundVO, HttpServletRequest request) throws Exception {

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");

		boolean isSuccess = true;
		String msg = "";
		int refundMoneySum = 0;
		int userMoney = 0;
		
		try {
			refundVO = refundService.selectRefundMberInfo(refundVO);
	    	userMoney =  (int)Double.parseDouble(refundVO.getMberMoney());	// 보유Cash
			
			refundMoneySum = refundService.selectRefundMoneySum(refundVO);	// 환불신청금액(환불요청 상태)

		} catch (Exception e) {
			isSuccess = false;
			msg = e.getMessage();
		}
	
		modelAndView.addObject("isSuccess", isSuccess);
		modelAndView.addObject("msg", msg);
		modelAndView.addObject("userMoney", userMoney);
		modelAndView.addObject("refundMoneySum", refundMoneySum);

		return modelAndView;
	}	
	
	/**
	 * 캐쉬 환불 처리
	 * @param refundVO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"/uss/ion/pay/updateCashAndPointAjax.do"})
	public ResponseEntity<StatusResponse> updateCashAndPointAjax(RefundVO refundVO) throws Exception {
		System.out.println(" + refundVO.getPayCancleDiv() :: "+refundVO.getPayCancleDiv());
		return ResponseEntity.ok().body(refundService.updateCashAndPointAjax(userInfoAdd(refundVO)));
	}
	
	public RefundVO userInfoAdd(RefundVO refundVO) {
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		refundVO.setFrstRegisterId(user.getId());
		refundVO.setLastUpdusrId(user.getId());
		return refundVO;
		
	}
	
	
}
