package itn.let.mjo.msgCustom.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Value;
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.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.let.mjo.msgCustom.service.MjonMsgCustomService;
import itn.let.mjo.msgCustom.service.MjonMsgCustomVO;
import itn.let.mjo.pay.service.MjonPayService;
import itn.let.mjo.pay.service.MjonPayVO;

@Controller
public class MjonMsgCustomController {

	@Resource(name = "mjonMsgCustomService")
	private MjonMsgCustomService mjonMsgCustomService;

	@Resource(name = "EgovFileMngService")
	private EgovFileMngService fileMngService;

	@Resource(name = "EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;

	@Resource(name = "EgovCmmUseService")
	private EgovCmmUseService cmmUseService;
	
	@Resource(name = "EgovFileMngService")
	private EgovFileMngService fileService;
	
	@Resource(name = "mjonPayService")
    private MjonPayService mjonPayService;
	
	/** 첨부파일 저장경로 */
	@Value("#{globalSettings['Globals.file.saveDir']}")
	private String fileSaveDir;
	
	/**
	* @Method Name : selectMjonMsgCustomList
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 : 관리자 맞춤문자 요청 전체 리스트
	*/
	@RequestMapping(value= {"/uss/ion/custom/selectMjonMsgCustomList.do"})
	public String selectMjonMsgCustomList(@ModelAttribute("searchVO") MjonMsgCustomVO mjonMsgCustomVO
			, ModelMap model) throws Exception{
		
		ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
		//제작형태 코드 조회
		comDefaultCodeVO.setCodeId("ITN040");
		List<?> codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("codeResult", codeResult);
		
		
		if(mjonMsgCustomVO.getPageUnit() != 10) {
			mjonMsgCustomVO.setPageUnit(mjonMsgCustomVO.getPageUnit());
		}
		
		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(mjonMsgCustomVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(mjonMsgCustomVO.getPageUnit());
		paginationInfo.setPageSize(mjonMsgCustomVO.getPageSize());

		mjonMsgCustomVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		mjonMsgCustomVO.setLastIndex(paginationInfo.getLastRecordIndex());
		mjonMsgCustomVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage()); 
		
		if("".equals(mjonMsgCustomVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			mjonMsgCustomVO.setSearchSortCnd("frstRegistPnttm");
			mjonMsgCustomVO.setSearchSortOrd("desc");
		}
		
		List<MjonMsgCustomVO> customList = mjonMsgCustomService.selectMjonMsgCustomList(mjonMsgCustomVO);
		paginationInfo.setTotalRecordCount(customList.size()> 0 ? customList.get(0).getTotCnt() : 0);
		
		model.addAttribute("paginationInfo", paginationInfo);
		model.addAttribute("customList", customList);
		
		return "/uss/ion/custom/MsgCustomList";
	}
	
	
	/**
	* @Method Name : msgCustomInfo
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 : 관리자  맞춤문자 등록화면 / 상세보기 / 수정화면 
	*/
	@RequestMapping(value = {"/uss/ion/msg/MsgCustomInfo.do"})
	public String msgCustomInfo(
			@ModelAttribute("searchVO") MjonMsgCustomVO mjonMsgCustomVO
			, HttpServletRequest request
			, Model model) throws Exception {

		if(!mjonMsgCustomVO.getCustomId().equals(null) && mjonMsgCustomVO.getCustomId() != "" ) { //수정
			MjonMsgCustomVO mjonMsgCustomInfo = mjonMsgCustomService.selectMjonMsgCustomInfo(mjonMsgCustomVO);
			
//			if(mjonMsgCustomInfo.getCustomResultImg() != null) {
//				FileVO fileVO = new FileVO();
//				String atchFileId = mjonMsgCustomInfo.getCustomResultImg();
//				fileVO.setAtchFileId(atchFileId);
//				List<FileVO> fileList = fileService.selectFileInfs(fileVO);
//				model.addAttribute("fileList", fileList);
//			}
			
			ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
			//제작형태 코드 조회
			comDefaultCodeVO.setCodeId("ITN030");
			List<?> codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
			model.addAttribute("codeResult", codeResult);
			
			//제작형태 코드 조회
			comDefaultCodeVO.setCodeId("ITN040");
			List<?> progCodeList = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
			model.addAttribute("progCodeList", progCodeList);
			
			model.addAttribute("mjonMsgCustomInfo", mjonMsgCustomInfo);
			
			//제작완료 시 첨부파일 변경 가능하게 수정 23.01.25
			if("05".equals(mjonMsgCustomInfo.getCustomPaymentYn())) {
				FileVO fileVO = new FileVO();
				fileVO.setAtchFileId(mjonMsgCustomInfo.getCustomResultImg());
				List<FileVO> fileList = fileService.selectFileInfs(fileVO);
				model.addAttribute("fileList", fileList);
			}
			return "/uss/ion/custom/MsgCustomInfo";	
		}
		model.addAttribute("mjonMsgCustomVO", mjonMsgCustomVO);
		return "/uss/ion/custom/MsgCustomInsert";
	}
	
	/**
	* @Method Name : selectMsgCustomSampleImgList
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 : 관리자 맞춤문자 사용자 요청이미지 리스트 조회
	*/
	@RequestMapping("/uss/ion/custom/selectMsgCustomSampleImgList.do")
	public String selectMsgCustomSampleImgList(@ModelAttribute("searchVO") FileVO fileVO
			, @RequestParam Map<String, Object> commandMap
			, ModelMap model) throws Exception {

		String atchFileId = (String) commandMap.get("atchFileId");
		String fileSn = (String) commandMap.get("fileSn");
		
		String sampleId[] = atchFileId.split("/");
		String sampleFileSn[] = fileSn.split("/");
		
		List<FileVO> imgList = new ArrayList<FileVO>();
		for(int i=0; i< sampleId.length; i++) {
			fileVO.setAtchFileId(sampleId[i]);
			fileVO.setFileSn(sampleFileSn[i]);
//			fileVO.setFileSn(fileSn);
			List<FileVO> result = fileService.selectImageFileList(fileVO);
			imgList.addAll(result);
		}

		model.addAttribute("fileList", imgList);

		return "/uss/ion/custom/MsgCustomSampleImgList";
	}
	
	/**
	* @Method Name : selectMsgCustomImgList
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 :
	*/
	@RequestMapping("/uss/ion/custom/selectMsgCustomImgList.do")
	public String selectMsgCustomImgList(@ModelAttribute("searchVO") FileVO fileVO
			, @RequestParam Map<String, Object> commandMap
			, ModelMap model) throws Exception {
		String atchFileId = (String) commandMap.get("param_atchFileId");
		String fileType = (String) commandMap.get("fileType");
		String customPaymentYn = (String) commandMap.get("customPaymentYn");
		
		fileVO.setAtchFileId(atchFileId);
		List<FileVO> result = fileService.selectFileInfs(fileVO);
		model.addAttribute("fileList", result);
		model.addAttribute("updateFlag", "N");
		model.addAttribute("fileListCnt", result.size());
		model.addAttribute("atchFileId", atchFileId);
		model.addAttribute("fileType", fileType);
		model.addAttribute("customPaymentYn", customPaymentYn);

		return "/uss/ion/custom/MsgCustomImgList";
	}
	
	/** 등록*/
	/**
	* @Method Name : insertMsgCustomInfoAjax
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 : 관리자 맞춤문자 등록
	*/
	@RequestMapping(value = {"/uss/ion/msg/insertMsgCustomInfoAjax.do"})
	public ModelAndView insertMsgCustomInfoAjax(final MultipartHttpServletRequest multiRequest
			, MjonMsgCustomVO mjonMsgCustomVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String atchFileId = "";
		final Map<String, MultipartFile> files = multiRequest.getFileMap();
		if (!files.isEmpty()) {
			List<FileVO> result = fileUtil.parseFileInf(files, "CUSTOM_", 0, "", "", "");
			atchFileId = fileMngService.insertFileInfs(result);
			mjonMsgCustomVO.setCustomChoiceImg(atchFileId);
		}
		
		mjonMsgCustomVO.setFrstRegisterId(user.getId());
		mjonMsgCustomVO.setLastUpdusrId(user.getId());
		mjonMsgCustomService.insertMjonMsgCustomInfo(mjonMsgCustomVO);
		modelAndView.addObject("result", "success");
		return modelAndView;
	}
	
	/** 수정*/
	/**
	* @Method Name : updateMsgCustomInfoAjax
	* @작성일 : 2022. 10. 4.
	* @작성자 :  WYH
	* @Method 설명 : 관리자 맞춤문자 수정
	*/
	@RequestMapping(value = {"/uss/ion/msg/updateMsgCustomInfoAjax.do"})
	public ModelAndView updateMsgCustomInfoAjax(final MultipartHttpServletRequest multiRequest
			, MjonMsgCustomVO mjonMsgCustomVO
			, RedirectAttributes redirectAttributes
			, HttpServletRequest request) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String atchFileId = mjonMsgCustomVO.getCustomResultImg();
		final Map<String, MultipartFile> files = multiRequest.getFileMap();
		if (!files.isEmpty()) {
			String imagePath = "";
			Date now = new Date();
			SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMdd");
			String fdlDate = formatDate.format(now);
			
			//로컬 과 개발서버의 이미지 저장 경로 분기처리
			if(request.getServerName().equals("localhost")) {
				
				imagePath = fileSaveDir+"src/main/webapp/MMS/" + fdlDate;
				
			}else {
				/*imagePath = "usr/local/tomcat_mjon/webapps/mjon/MMS/" + fdlDate;*/
				imagePath = fileSaveDir+"/file/MMS/" + fdlDate;
				
			}
			
			if ("".equals(atchFileId)) {
				List<FileVO> result = fileUtil.parseImageFileInf(files, "CUSTOM_", 0, "", imagePath, "");
				atchFileId = fileMngService.insertFileInfs(result);
				mjonMsgCustomVO.setCustomResultImg(atchFileId);
			}else {
				FileVO fileVO = new FileVO();
				fileVO.setAtchFileId(atchFileId);
				int cnt = fileMngService.getMaxFileSN(fileVO);
				List<FileVO> fileResult = fileUtil.parseImageFileInf(files, "CUSTOM_", cnt, atchFileId, imagePath, "");
				fileMngService.updateFileInfs(fileResult);
			}
		}
		
		mjonMsgCustomVO.setLastUpdusrId(user.getId());
		mjonMsgCustomService.updateMjonMsgCustomInfo(mjonMsgCustomVO);
		
		modelAndView.addObject("result", "success");
		return modelAndView;
	}
	
	@RequestMapping(value = {"/uss/ion/msg/deletMsgCustomInfoAjax.do"})
	public ModelAndView deletMsgCustomInfoAjax(
			@ModelAttribute("mjonMsgCustomVO") MjonMsgCustomVO mjonMsgCustomVO) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		mjonMsgCustomVO.setLastUpdusrId(user.getId());
		mjonMsgCustomService.updateMjonMsgCustomInfo(mjonMsgCustomVO);

		//문자 발송 캐시 차감 해주기
		MjonPayVO mjonPayVO = new MjonPayVO();
		mjonPayVO.setUserId(mjonMsgCustomVO.getUserId());
		mjonPayVO.setCash(Float.parseFloat(mjonMsgCustomVO.getCustomAmount()));
		mjonPayVO.setFrstRegisterId(mjonMsgCustomVO.getUserId());
		mjonPayVO.setMemo("맞춤문자 취소");
		mjonPayVO.setOrderId(mjonMsgCustomVO.getCustomId());
		mjonPayService.insertCash(mjonPayVO); //캐시차감 
				
		modelAndView.addObject("result", "success");
		return modelAndView;
	}
	
	//제작완료 항목 첨부파일 삭제
	@RequestMapping(value = {"/uss/ion/msg/updateMsgCustomFileNullAjax.do"})
	public ModelAndView updateMsgCustomFileNullAjax(
			@ModelAttribute("mjonMsgCustomVO") MjonMsgCustomVO mjonMsgCustomVO) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		mjonMsgCustomVO.setLastUpdusrId(user.getId());
		mjonMsgCustomService.updateMsgCustomFileNullAjax(mjonMsgCustomVO);
		
		modelAndView.addObject("result", "success");
		return modelAndView;
	}
}
