package kcg.imis.report.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

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

import kcg.imis.cmmn.CommConstants;
import kcg.imis.cmmn.excel.ExcelExporter;
import kcg.imis.cmmn.service.CodeService;
import kcg.imis.cmmn.vo.CodeVO;
import kcg.imis.report.service.ReportJudgeService;
import kcg.imis.report.vo.ReportSearchVO;
import kcg.imis.sec.UserUtil;

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.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;
import org.springmodules.validation.commons.DefaultBeanValidator;

/**
  * @FileName : ReportStatsController.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
@Controller
@RequestMapping("/report")
public class ReportStatsController {	
	/**
	 * Validator - 유효성 검사
	 **/
	@Resource(name = "beanValidator")
	private DefaultBeanValidator beanValidator;

	/**
	 * 견문 결재 인터페이스 
	 */
	@Resource(name = "reportJudgeService")
	private ReportJudgeService judgeService;

	/**
	 * 코드 인터페이스
	 */
	@Resource(name = "codeService")
	private CodeService codeService;

	/**
	 * message.properties의 값을 가져오는 인터페이스.
	 */
	@Autowired
	private MessageSource messageSource;

	/**
	 * 견문 통계 검색 화면을 반환한다.
	 * @param reportSearchVO 견문 검색 객체
	 * @param model 모델 객체
	 * @return 견문 통계 검색 화면
	 */
	@RequestMapping(value = "/statistics.do")
	public String statistics(final ReportSearchVO reportSearchVO, final Model model) {
		try {			
			//분류 1,2,3,4
			model.addAttribute("category1", codeService.getCodeMap(CommConstants.CODE_CATE1));
			model.addAttribute("category2", codeService.getCodeMap(CommConstants.CODE_CATE2));

			int myGroupCode = ReportCommon.getMyGroupCode();
			model.addAttribute("myGroupCode", myGroupCode);
			
			switch (myGroupCode) {
			case 3:
				model.addAttribute("placeList", codeService.getCodeList(CommConstants.CODE_PLACE1));
				break;
			case 2:
				model.addAttribute("placeList", codeService.getPlace1SubListWithMain(UserUtil.getMemberInfo().getPlace1()));
				break;
			default:
				model.addAttribute("myPlaceCode", UserUtil.getMemberInfo().getPlace1());
				model.addAttribute("myPlaceName", UserUtil.getMemberInfo().getPlace1Str());
				break;
			}
			
			model.addAttribute("judgeList", codeService.getCodeList(CommConstants.CODE_JUDGE));
			
			model.addAttribute("reportSearchVO", reportSearchVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "report/statistics.tiles";
	}
	
	/**
	 * 견문 통계 결과 화면을 반환한다.
	 * 
	 * @param reportSearchVO 견문 검색 객체
	 * @param model model 객체
	 * @param request request 객체
	 * @param status session 객체
	 * @throws Exception 기본예외처리
	 * @return 견문 통계 결과 화면
	 */
	@RequestMapping(value = "/statsResult.do")
	public String statsResult(@ModelAttribute final ReportSearchVO reportSearchVO, final Model model,
			final HttpServletRequest request, final SessionStatus status) throws Exception {
		//분류 1,2,3,4
		model.addAttribute("category1", codeService.getCodeMap(CommConstants.CODE_CATE1));
		model.addAttribute("category2", codeService.getCodeMap(CommConstants.CODE_CATE2));
		
		//model.addAttribute("placeList", codeService.getPlace1List(false));
		model.addAttribute("placeList", codeService.getCodeList(CommConstants.CODE_PLACE1));
		model.addAttribute("judgeList", codeService.getCodeList(CommConstants.CODE_JUDGE));

		model.addAttribute("myGroupCode", ReportCommon.getMyGroupCode());
		model.addAttribute("reportSearchVO", reportSearchVO);

		try {
			ReportSearchVO searchVO = (ReportSearchVO) reportSearchVO.clone();
			searchVO = ReportCommon.setSearchUserInfo(searchVO);
			
			// 소속 선택하지 않은 경우 모두 세팅
			if (searchVO.getPlaces() == null || searchVO.getPlaces().length == 0) {
				List<String> placeList = new ArrayList<String>();
				for (CodeVO code : codeService.getCodeList(CommConstants.CODE_PLACE1)) {
					placeList.add(code.getCode());
				}
				searchVO.setPlaces(placeList.toArray(new String[placeList.size()]));
			}

			// 분야별 통계
			if ("C".equals(searchVO.getStatsType())) {

				// 분류 아무것도 선택하지 않은 경우 모두 세팅
				if (searchVO.isSearchCate1() && (searchVO.getCategory1() == null || searchVO.getCategory1().length == 0)) {
					HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE1);
					searchVO.setCategory1(category.keySet().toArray(new String[category.size()]));
				}
				if (searchVO.isSearchCate2() && (searchVO.getCategory2() == null || searchVO.getCategory2().length == 0)) {
					HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE2);
					searchVO.setCategory2(category.keySet().toArray(new String[category.size()]));
				}
				
				model.addAttribute("statistics", judgeService.statsCategory(searchVO));	
			
			} else if ("J".equals(searchVO.getStatsType())) {
				
				if ((searchVO.getJudges() == null || searchVO.getJudges().length == 0)) {
					HashMap<String, String>  judge = codeService.getCodeMap(CommConstants.CODE_JUDGE);
					searchVO.setJudges( judge.keySet().toArray(new String[ judge.size()]));
				}
				
				// 평가별 통계
				model.addAttribute("statistics", judgeService.statsJudge(searchVO));
			}
			
			model.addAttribute("searchVO", searchVO);
			return "report/statsResult.tiles";
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error/bizError";
	}

	/**
	 * 견문 통계 결과를 엑셀 문서로 반환한다.
	 * 
	 * @param reportSearchVO 견문 검색 객체
	 * @param model model 객체
	 * @param locale Locale 객체
	 * @throws Exception 기본예외처리
	 * @return 견문 통계 결과 화면
	 */
	@RequestMapping(value = "/statsExcel")
	public String statsExcel(@ModelAttribute final ReportSearchVO reportSearchVO, final Model model, final Locale locale) throws Exception {
		LinkedHashMap<String, String> header = new LinkedHashMap<String, String>();

		
		// 분야별 통계
		if ("C".equals(reportSearchVO.getStatsType())) {
			
			if (reportSearchVO.getCategory1() == null || reportSearchVO.getCategory1().length == 0) {
				HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE1);
				reportSearchVO.setCategory1(category.keySet().toArray(new String[category.size()]));
			}
			if (reportSearchVO.getCategory2() == null || reportSearchVO.getCategory2().length == 0) {
				HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE2);
				reportSearchVO.setCategory2(category.keySet().toArray(new String[category.size()]));
			}
			
			ReportSearchVO searchVO = (ReportSearchVO) reportSearchVO.clone();
			searchVO = ReportCommon.setSearchUserInfo(searchVO);
			
			header.put("PLACE_NAME", messageSource.getMessage("report.view.division", null, locale));
			header.put("TOTAL", messageSource.getMessage("report.stats.total", null, locale));
			
		
			
			
			for (String category : reportSearchVO.getCategory1()) {
				header.put(category + "_1", codeService.getCode(CommConstants.CODE_CATE1, category).getName());
			}
			for (String category : reportSearchVO.getCategory2()) {
				header.put(category + "_2", codeService.getCode(CommConstants.CODE_CATE2, category).getName());
			}
			
			try {
				Date d = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String title = String.format("%s_%s", messageSource.getMessage("report.title", null, locale), sdf.format(d));
				
				// 소속 선택하지 않은 경우 모두 세팅
				if (searchVO.getPlaces() == null || searchVO.getPlaces().length == 0) {
					List<String> placeList = new ArrayList<String>();
					for (CodeVO code : codeService.getCodeList(CommConstants.CODE_PLACE1)) {
						placeList.add(code.getCode());
					}
					searchVO.setPlaces(placeList.toArray(new String[placeList.size()]));
				}

				// 분류 아무것도 선택하지 않은 경우 모두 세팅
				if (searchVO.isSearchCate1() && searchVO.getCategory1().length == 0) {
					HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE1);
					
					searchVO.setCategory1(category.keySet().toArray(new String[category.size()]));
				}
				if (searchVO.isSearchCate2() && searchVO.getCategory2().length == 0) {
					HashMap<String, String> category = codeService.getCodeMap(CommConstants.CODE_CATE2);
					searchVO.setCategory2(category.keySet().toArray(new String[category.size()]));
				}
				
				List<HashMap<String, String>> list = judgeService.statsCategory(searchVO);

				model.addAttribute("excel", new ExcelExporter<HashMap<String, String>>(header, list, title));
				model.addAttribute("filename", title);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("J".equals(reportSearchVO.getStatsType())) {
			
			if ((reportSearchVO.getJudges() == null || reportSearchVO.getJudges().length == 0)) {
				HashMap<String, String>  judge = codeService.getCodeMap(CommConstants.CODE_JUDGE);
				reportSearchVO.setJudges( judge.keySet().toArray(new String[ judge.size()]));
			}
			
			
			ReportSearchVO searchVO = (ReportSearchVO) reportSearchVO.clone();
			searchVO = ReportCommon.setSearchUserInfo(searchVO);
			
			header.put("PLACE_NAME", messageSource.getMessage("report.view.division", null, locale));
			
			header.put("C01", messageSource.getMessage("report.type.newsflash", null, locale));
			header.put("C02", messageSource.getMessage("report.type.judge", null, locale));
			header.put("C03", messageSource.getMessage("report.type.middle", null, locale));
			header.put("C04", messageSource.getMessage("report.type.notice", null, locale));
			header.put("C05", messageSource.getMessage("report.type.record", null, locale));
			header.put("C06", messageSource.getMessage("report.type.survey", null, locale));
			header.put("C07", messageSource.getMessage("report.type.reference", null, locale));

			header.put("AG", messageSource.getMessage("report.stats.AGrade", null, locale));
			header.put("BG", messageSource.getMessage("report.stats.BGrade", null, locale));
			header.put("CG", messageSource.getMessage("report.stats.CGrade", null, locale));
			header.put("DG", messageSource.getMessage("report.stats.DGrade", null, locale));
			
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String title = String.format("%s_%s", messageSource.getMessage("report.title", null, locale), sdf.format(d));
			
			List<HashMap<String, String>> list = judgeService.statsJudge(searchVO);

			model.addAttribute("excel", new ExcelExporter<HashMap<String, String>>(header, list, title));
			model.addAttribute("filename", title);
		}
		
		return "excelView";
	}
}
