package kcg.faics.fa.web;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import kcg.faics.cmmn.file.FileUploadUtil;
import kcg.faics.cmmn.service.CodeService;
import kcg.faics.member.service.MemberService;
import kcg.faics.member.vo.ExMemberVO;
import kcg.faics.member.vo.MemberSearchVO;
import kcg.faics.member.vo.MemberVO;
import kcg.faics.susa.vo.IncidentVO;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

/**
 * 과거외사경찰 컨트롤러.
 * 
 * @author kimnomin
 *
 */
@Controller
@RequestMapping("/fa")
public class ExMemberController {
	
	/**
	 * Properties 서비스 객체.
	 */
	@Resource(name = "propertiesService")
	private EgovPropertyService propertiesService;	

	/**
	 * 사용자 서비스 객체.
	 */
	@Resource(name = "memberService")
	private MemberService memberService;
	
	/**
	 * 코드관련 서비스 객체.
	 */
	@Resource(name = "codeService")
	private CodeService codeService;
	
	/**
	 * Validator - 유효성 검사.
	 **/
	@Resource(name = "beanValidator")
	private DefaultBeanValidator beanValidator;	
	
	/**
	 * 과거외사경찰 조회화면을 반환한다.
	 * 
	 * @param vo
	 *            조회할 과거외사경찰 VO
	 * @param model
	 *            Model 객체
	 * @return 과거외사경찰 조회화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping("/exmemberView.do")
	public String exmemberView(final ExMemberVO vo, final Model model) throws Exception {
		ExMemberVO exMemeberVO = memberService.selectExMember(vo);
		model.addAttribute("memberVO", exMemeberVO);
		
		return "fa/exmemberView.tiles";
	}	
	
	/**
	 * 과거외사경찰 목록화면를 반환한다.
	 *
	 * @param searchVO 검색조건 VO.
	 * @param model 모델 객체
	 * @return 과거외사경찰 목록 화면
	 * @throws Exception 기본 예외 처리
	 */
	@RequestMapping("/exmemberList.do")
	public String exmemberList(final MemberSearchVO searchVO, final Model model) throws Exception {
		
		try {
			/* 페이징 처리 정보 */
			searchVO.setPageUnit(propertiesService.getInt("pageUnit"));
			searchVO.setPageSize(propertiesService.getInt("pageSize"));
			
			/* 페이징 처리 */
			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());
			
			int totSearchCnt = memberService.selectExmemberListCnt(searchVO);
			paginationInfo.setTotalRecordCount(totSearchCnt);
			model.addAttribute("paginationInfo", paginationInfo);
			
			/* 게시판 상단 페이지 및 게시물 정보 표현을 위한 데이터 */
			int totCnt = memberService.selectExmemberTotalCnt(searchVO);
			model.addAttribute("totalCnt", totCnt);
			
			List<ExMemberVO> resultList = memberService.exmemberVoList(searchVO);
			
			model.addAttribute("resultList", memberService.exmemberVoList(searchVO));
			model.addAttribute("place1List", codeService.getPlace1List(false));
			model.addAttribute("positionList", codeService.getPositionList());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "fa/exmemberList.tiles";
	}
	
	/**
	 * 과거외사경찰 수정 화면을 반환한다.
	 * 
	 * @param searchVO
	 *            과거외사경찰 VO
	 * @param model
	 *            Model 객체
	 * @return 과거외사경찰 수정 화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping("/exmemberUpdate.do")
	public String exmemberUpdate(final ExMemberVO searchVO, final Model model) throws Exception {
		ExMemberVO vo = memberService.selectExMember(searchVO);
		model.addAttribute("exmemberVO", vo);
		model.addAttribute("registerFlag", "modify");
		
		model.addAttribute("place1List", codeService.getPlace1List(false));
		model.addAttribute("positionList", codeService.getPositionList());
		model.addAttribute("dutiesList", codeService.getDutiesList());
		model.addAttribute("jobTypeList", codeService.getJobTypeList());
		model.addAttribute("scholarshipList", codeService.getScholarshipList());
		model.addAttribute("authList", codeService.getAuthList());
		
		return "fa/exmemberAdd.tiles";
	}
	
	/**
	 * 과거외사경찰 정보를 수정한다.
	 * 
	 * @param multiRequest
	 *            mutipartform 객체
	 * @param exmemberVO
	 *            과거외사경찰 VO
	 * @param bindingResult
	 *            유효성 검사결과 객체
	 * @param model
	 *            모델 객체
	 * @param status
	 *            SessionStatus 객체
	 * @return 과거외사경찰 조회화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/exmemberUpdate.do", method = RequestMethod.POST)
	public String exmemberUpdate(final MultipartHttpServletRequest multiRequest,
			@Valid @ModelAttribute("exmemberVO") final ExMemberVO exmemberVO,
			final BindingResult bindingResult, final Model model,
			final SessionStatus status) throws Exception {
		
		// 사용자 인증 검사
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
		if (isAuthenticated) {
			// 유효성 검사
			beanValidator.validate(exmemberVO, bindingResult);
			if (bindingResult.hasErrors()) {
				model.addAttribute("exmemberVO", exmemberVO);
				return exmemberUpdate(exmemberVO, model);
			}
						
			HashMap<String, Object> resultMap = memberService.updateExMember(exmemberVO);
			int result = (Integer) resultMap.get("result"); 
			if (result == 1) {
				return "redirect:/fa/exmemberList.do";
			}
		}
		
		return "error/bizError";
	}
	
	/**
	 * 요청 파라미터 바인딩 확장 메소드.
	 * 
	 * @param binder
	 *            WebDataBinder 객체
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@InitBinder
	public void initBinder(final WebDataBinder binder) throws Exception {
	    binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

	        public void setAsText(final String text) throws IllegalArgumentException {
	            try {
	                setValue(new SimpleDateFormat("yyyy-MM-dd").parse(text));
	            } catch (ParseException e) {
	                setValue(null);
	            }
	        }
	    });
	}
}
