package kcg.faics.fa.web;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;

import kcg.faics.cmmn.bbs.PageType;
import kcg.faics.cmmn.excel.ExcelExporter;
import kcg.faics.cmmn.service.CodeService;
import kcg.faics.cmmn.vo.CodeVO;
import kcg.faics.fa.service.EduService;
import kcg.faics.fa.vo.EduSearchVO;
import kcg.faics.fa.vo.EduVO;
import kcg.faics.sec.LoginUserVO;
import kcg.faics.sec.UserUtil;
import kcg.faics.tg.vo.DivMngSearchVO;
import kcg.faics.tg.vo.DivMngVO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;

/**
 * 교육현황 컨트롤러.
 * 
 * @author kimnomin
 *
 */
@Controller
@RequestMapping("/fa/edu")
public class EduController {

	/**
	 * Validator - 유효성 검사.
	 **/
	@Resource(name = "beanValidator")
	private DefaultBeanValidator beanValidator;
	
	/**
	 * message.properties의 값을 가져오는 인터페이스.
	 */
	@Autowired
	private MessageSource messageSource;
	
	/**
	 * 코드관련 정보 인터페이스.
	 */
	@Resource(name = "codeService")
	private CodeService codeService;
	
	/**
	 * 교육현황 서비스.
	 */
	@Resource(name = "eduService")
	private EduService eduService;
	
	/**
	 * Redirect URI를 조합하여 반환한다.
	 * 
	 * @param pageType
	 *            화면구분
	 * @param vo
	 *            데이터 VO
	 * @return Redirect URI
	 */
	private String makeRedirectUri(final PageType pageType, final EduVO vo) {
		String uri = "redirect:/fa/edu";
		
		switch (pageType) {
		case Upd:
			uri = String.format("%s/update.do", uri);
			break;
		case List:
			uri = String.format("%s/list.do", uri);
			break;
		default:
			break;
		}
		
		return uri;
	}
	
	/**
	 * 교육현황 입력화면을 반환한다.
	 * 
	 * @param model
	 *            Model 객체
	 * @param eduVO
	 *            교육현황 VO
	 * @return 교육현황 입력화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/add.do")
	public String add(final Model model, final EduVO eduVO)
			throws Exception {
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();

		if (isAuthenticated && UserUtil.isAdmin()) {
			LoginUserVO loginUserVO = UserUtil.getMemberInfo();
			model.addAttribute("loginUserVO", loginUserVO);
			model.addAttribute("registerFlag", "create");

			// 교육과정 목록
			List<CodeVO> eduCourseList = codeService.getEduCourse(false);
			model.addAttribute("eduCourseList", eduCourseList);
			
			// 교육기관 목록
			List<CodeVO> eduPlaceList = codeService.getEduPlace(false);
			model.addAttribute("eduPlaceList", eduPlaceList);
			
			// 계급 목록
			List<CodeVO> positionList = codeService.getPositionList();
			model.addAttribute("positionList", positionList);
			
			// 소속1 목록
			List<CodeVO> placeList = codeService.getPlace1List(false, false);
			model.addAttribute("placeList", placeList);
			// 소속2 목록
			CodeVO place2SearchVO = new CodeVO();
			place2SearchVO.setCode1(placeList.get(0).getCode2());
			List<CodeVO> place2List = codeService.getPlace2List(place2SearchVO);
			model.addAttribute("place2List", place2List);
			
			// 직별 목록
			List<CodeVO> jobtypeList = codeService.getJobTypeList();
			model.addAttribute("jobtypeList", jobtypeList);
			
			// 최종학력 목록
			List<CodeVO> scholarshipList = codeService.getScholarshipList();
			model.addAttribute("scholarshipList", scholarshipList);					
			
			eduVO.setWriter(loginUserVO.getUserid());
			
			return "/fa/eduAdd.tiles";
		} else {
			return makeRedirectUri(PageType.List, eduVO);
		}
	}
	
	/**
	 * 교육현황 정보를 입력한다.
	 * 
	 * @param eduVO
	 *            입력할 데이터 VO
	 * @param bindingResult
	 *            BindingResult 객체
	 * @param model
	 *            Model 객체
	 * @param status
	 *            SessionStatus 객체
	 * @return 교육현황 목록 화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	public String add(@ModelAttribute("eduVO") final EduVO eduVO,
			final BindingResult bindingResult, final Model model,
			final SessionStatus status) throws Exception {
		// 사용자 인증 검사
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();		
		if (isAuthenticated && UserUtil.isAdmin()) {
			// 유효성 검사
			beanValidator.validate(eduVO, bindingResult);
			if (bindingResult.hasErrors()) {
				return add(model, eduVO);
			}

			HashMap<String, Object> resultMap = eduService.insert(eduVO, null);
			
			if ((Integer) resultMap.get("result") == 1) {
				status.setComplete();
				return makeRedirectUri(PageType.List, eduVO);
			}
		}
		return "error/bizError";
	}
	
	/**
	 * 교육현황 목록화면을 반환한다.
	 * 
	 * @param model
	 *            Model 객체
	 * @param locale
	 *            Locale 객체
	 * @param searchVO
	 *            검색조건 VO            
	 * @return 외사분실운영현황 목록화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/list.do")
	public String list(final Model model, final Locale locale,
			@ModelAttribute("searchVO") final EduSearchVO searchVO)
			throws Exception {
		LoginUserVO loginUserVO = UserUtil.getMemberInfo();
		model.addAttribute("loginUserVO", loginUserVO);
		
		List<CodeVO> eduCourseList = codeService.getEduCourse(true);
		model.addAttribute("eduCourseList", eduCourseList);
		
		List<CodeVO> placeList = codeService.getPlace1List(false, true);
		model.addAttribute("placeList", placeList);
		
		List<EduVO> eduList = eduService.selectList(searchVO);
		model.addAttribute("eduList", eduList);
		
		return "/fa/eduList.tiles";
	}
	
	/**
	 * 교육현황 목록을 엑셀로 반환한다.
	 * 
	 * @param model
	 *            Model 객체
	 * @param locale
	 *            Locale 객체
	 * @param searchVO
	 *            검색조건 VO
	 * @return 교육현황 목록 엑셀
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/listtoexcel.do")
	public String listToExcel(final Model model, final Locale locale,
			@ModelAttribute("searchVO") final EduSearchVO searchVO)
			throws Exception {
		String title = messageSource.getMessage("fa.edu", null, locale);
		
		// 엑셀 헤더 생성
		LinkedHashMap<String, String> header = new LinkedHashMap<String, String>();
		header.put("eduCourseStr", messageSource.getMessage("fa.edu.eduCourse", null, locale));
		header.put("scholarshipStr", messageSource.getMessage("fa.edu.scholarship", null, locale));
		header.put("positionStr", messageSource.getMessage("fa.edu.position", null, locale));
		header.put("name", messageSource.getMessage("fa.edu.name", null, locale));
		header.put("eduTerm", messageSource.getMessage("fa.edu.eduTerm", null, locale));
		header.put("comment", messageSource.getMessage("fa.edu.comment", null, locale));
		
		// 데이터 생성
		List<EduVO> eduList = eduService.selectList(searchVO);
		
		// Export
		model.addAttribute("excel", new ExcelExporter<EduVO>(header, eduList, title));
		model.addAttribute("filename", title);
		
		return "excelView";
	}
	
	/**
	 * 교육현황 수정화면을 반환한다.
	 * 
	 * @param eduVO
	 *            교육현황 VO
	 * @param model
	 *            Model 객체
	 * @return 교육현황 수정화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/update.do")
	public String update(final EduVO eduVO, final Model model) throws Exception {
		LoginUserVO loginUserVO = UserUtil.getMemberInfo();
		model.addAttribute("loginUserVO", loginUserVO);
		model.addAttribute("registerFlag", "modify");

		// 저장된 데이터
		EduVO vo = eduService.select(eduVO);
		model.addAttribute("eduVO", vo);
		
		// 교육과정 목록
		List<CodeVO> eduCourseList = codeService.getEduCourse(false);
		model.addAttribute("eduCourseList", eduCourseList);
		
		// 교육기관 목록
		List<CodeVO> eduPlaceList = codeService.getEduPlace(false);
		model.addAttribute("eduPlaceList", eduPlaceList);
		
		// 계급 목록
		List<CodeVO> positionList = codeService.getPositionList();
		model.addAttribute("positionList", positionList);
		
		// 소속1 목록
		List<CodeVO> placeList = codeService.getPlace1List(false, false);
		model.addAttribute("placeList", placeList);
		// 소속2 목록
		CodeVO place2SearchVO = new CodeVO();
		if (StringUtils.isNotBlank(vo.getPlace1())) {
			place2SearchVO.setCode1(vo.getPlace1());
		} else {
			place2SearchVO.setCode1(placeList.get(0).getCode2());	
		}
		
		List<CodeVO> place2List = codeService.getPlace2List(place2SearchVO);
		model.addAttribute("place2List", place2List);
		
		// 직별 목록
		List<CodeVO> jobtypeList = codeService.getJobTypeList();
		model.addAttribute("jobtypeList", jobtypeList);
		
		// 최종학력 목록
		List<CodeVO> scholarshipList = codeService.getScholarshipList();
		model.addAttribute("scholarshipList", scholarshipList);			
		
		return "/fa/eduAdd.tiles";
	}
	
	/**
	 * 교육현황 정보를 수정한다.
	 * 
	 * @param eduVO
	 *            교육현황 VO
	 * @param bindingResult
	 *            BindingResult 객체
	 * @param model
	 *            Model 객체
	 * @param status
	 *            SessionStatus 객체
	 * @return 교육현황 목록화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/update.do", method = RequestMethod.POST)
	public String update(@ModelAttribute("eduVO") final EduVO eduVO,
			final BindingResult bindingResult, final Model model,
			final SessionStatus status) throws Exception {
		// 사용자 인증 검사
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
		if (isAuthenticated && UserUtil.isAdmin()) {
			// 유효성 검사
			beanValidator.validate(eduVO, bindingResult);
			if (bindingResult.hasErrors()) {
				return update(eduVO, model);
			}
			
			HashMap<String, Object> resultMap = eduService.update(eduVO, null, null);
			
			if ((Integer) resultMap.get("result") > 0) {
				status.setComplete();
				return makeRedirectUri(PageType.List, eduVO);
			}
		}
		
		return update(eduVO, model);
	}
	
	/**
	 * 교육현황 정보를 삭제한다.
	 * 
	 * @param eduVO
	 *            교육현황 VO
	 * @param model
	 *            Model 객체
	 * @param status
	 *            SessionStatus 객체
	 * @return 교육현황 목록 화면
	 * @throws Exception
	 *             기본 예외 처리
	 */
	@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
	public String delete(final EduVO eduVO, final Model model,
			final SessionStatus status) throws Exception {

		if (UserUtil.isAdmin()) {
			EduVO vo = eduService.select(eduVO);
			if (vo != null) {
				HashMap<String, Object> map = eduService.delete(vo);
				if ((Integer) map.get("result") > 0) {
					return makeRedirectUri(PageType.List, vo);
				}
			}
		}
		
		return makeRedirectUri(PageType.Upd, eduVO);
	}
}
