package kcg.imis.report.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import kcg.imis.member.vo.MemberVO;
import kcg.imis.report.mapper.ReportJudgeMapper;
import kcg.imis.report.vo.ReportJudgeVO;
import kcg.imis.report.vo.ReportSearchVO;
import kcg.imis.report.vo.ReportVO;
import kcg.imis.report.web.ReportCommon;
import kcg.imis.sec.LoginUserVO;
import kcg.imis.sec.UserUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import egovframework.rte.psl.dataaccess.util.EgovMap;

/**
  * @FileName : ReportJudgeServiceImpl.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 29. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 :
 */
@Service("reportJudgeService")
public class ReportJudgeServiceImpl extends EgovAbstractServiceImpl implements ReportJudgeService {

	/**
	 * 견문 관련 인터페이스
	 */
	@Resource(name = "reportService")
	private ReportService reportService;

	/**
	 * 견문 평가 맵퍼
	 */
	@Resource(name = "reportJudgeMapper")
	private ReportJudgeMapper reportJudgeMapper;

	
	/**
	 * 견문 평가 정보를 반환한다.
	 */
	@Override
	public ReportJudgeVO selectOne(final int juseq) throws Exception {
		return reportJudgeMapper.selectOne(juseq);
	}

	@Override
	public String getJudgeStr(final int judgeCode) throws Exception {
		return reportJudgeMapper.getJudgeName(judgeCode);
	}

	@Override
	public int insert(final ReportJudgeVO reportJudgeVO) throws Exception {
		return reportJudgeMapper.insert(reportJudgeVO);
	}
	
	
	@Override
	public MemberVO selectApprove() throws Exception {
		LoginUserVO loginUserVO = UserUtil.getMemberInfo();
		int myDutiesCode = ReportCommon.getDutiesCodeForApprove(loginUserVO.getDuties());
		String usrLv = "";
		if(myDutiesCode == 2 ) usrLv = "4";
		if(myDutiesCode == 3 ) usrLv = "3";
		return reportJudgeMapper.selectApprove(usrLv);
	}

	@Override
	public HashMap<String, Object> approve(final ReportVO reportVO) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String errorMsg = "";
		try {
			List<ReportVO> list = new ArrayList<ReportVO>(); 
			if (reportVO.getReportList() == null && reportVO.getInSeq() > 0) {
				list.add(0, reportVO);
			} else if (reportVO.getReportList() != null && reportVO.getReportList().size() > 0) {
				list = reportVO.getReportList();
			} else {
				map.put("result", -1);
				map.put("msg", "결재할 견문이 없습니다.");
				return map;
			}
			
	
			LoginUserVO loginUserVO = UserUtil.getMemberInfo();
			int myGroupCode = ReportCommon.getMyGroupCode();
			int myDutiesCode = ReportCommon.getDutiesCodeForApprove(loginUserVO.getDuties());
			
			MemberVO reportApproveVO = selectApprove();
			
			if (myDutiesCode == 2 && reportApproveVO == null) {
				map.put("result", -1);
				map.put("msg", "국제법규정보팀장 정보가 없습니다. 권한 설정에서 계장을 선택하십시오.");
				return map;
			} else if (reportApproveVO == null && myDutiesCode == 3) {
				map.put("result", -1);
				map.put("msg", "국제법규정보담당관 정보가 없습니다. 권한 설정에서 과장을 선택하십시오.");
				return map;
			}
			
			// 견문 평가 객체를 생성한다.
			ReportJudgeVO reportJudgeVO = new ReportJudgeVO();
			reportJudgeVO.setJuGroupCode(myGroupCode);
			reportJudgeVO.setJuPlace1(reportApproveVO.getPlace1Str());
			reportJudgeVO.setJuPlace2(reportApproveVO.getPlace2Str());
			reportJudgeVO.setJuDuty(reportApproveVO.getDutyStr());
			reportJudgeVO.setJuName(reportApproveVO.getName());
			reportJudgeVO.setJuUserid(reportApproveVO.getUserid());
			reportJudgeVO.setJuProxyId(loginUserVO.getUserid());
			reportJudgeVO.setJuDutyCode(String.valueOf(myDutiesCode));
			
			int cnt = 1;
			int mgcHead = 0;
			int mgcSection = 0;
			ReportVO tempVO = new ReportVO();
			for (ReportVO vo : list) {
				if (vo.getInSeq() <= 0) {
					continue;
				}
				tempVO = reportService.select(vo);
				
				if (StringUtils.isNotBlank(vo.getInStateCode())) {
					tempVO.setInCategory1(vo.getInCategory1()); 
					tempVO.setInCategory2(vo.getInCategory2());
					tempVO.setInSubject(vo.getInSubject());
					
					String infoDate = vo.getStrInfodate().toString();
					tempVO.setInInfoYear(Integer.valueOf(infoDate.split("-")[0]));
					tempVO.setInInfoMonth(Integer.valueOf(infoDate.split("-")[1]));
					tempVO.setInInfoDay(Integer.valueOf(infoDate.split("-")[2]));
					
					tempVO.setInStateCode(vo.getInStateCode());
				}
				
				if (vo.getInJudge() > 0) {
					tempVO.setInJudge(vo.getInJudge());
				}
	
				tempVO.setJuMsg(vo.getJuMsg());
				
				if (tempVO.equals(null)) {
					 errorMsg += String.valueOf(cnt) + "번째 견문은 이미 삭제된 견문입니다.\n";
					 continue;
				} else {
					
					mgcHead = tempVO.getInJuseqHead();
					mgcSection = tempVO.getInJuseqSection();

					
					if (mgcHead > 0 && mgcSection > 0) {
						errorMsg += String.valueOf(cnt) + "번째 견문은 이미 결재된 견문입니다.\n";
						continue;
					}
					if (myDutiesCode == 2 && mgcSection > 0) {
						errorMsg += String.valueOf(cnt) + "번째 견문은 이미 결재된 견문입니다.\n";
						continue;
					}
					if (myDutiesCode == 3 && mgcHead > 0) {
						errorMsg += String.valueOf(cnt) + "번째 견문은 이미 결재된 견문입니다.\n";
						continue;
					}
				}
				String postState = "";
				if ((myDutiesCode == 2 && mgcHead > 0) || (myDutiesCode == 3 && mgcSection > 0) || loginUserVO.getAuthProxyHead() > 0) {
					postState = "4";
				} else {
					postState = String.valueOf(myDutiesCode);
				}
				
				// 상태코드 설정
				String newStateCode = String.valueOf(myGroupCode) + postState;
				
				tempVO.setInStateCode(newStateCode);
				if (Character.getNumericValue(newStateCode.charAt(1)) == 4) {
					tempVO.setInComplete("1");
				}
				
				// 견문 평가 객체를 생성한다.
				reportJudgeVO.setJuInseq(vo.getInSeq());
				reportJudgeVO.setJuJudge(vo.getInJudge());
				reportJudgeVO.setJuMessage(tempVO.getJuMsg());

				/**
				 * 견문 결제 
				 */
				int juSeq = insert(reportJudgeVO);
				
				if (myDutiesCode == 2) {
					tempVO.setInJuseqSection(juSeq);
					
				} else {
					tempVO.setInJudge(vo.getInJudge());
					tempVO.setInJuseqHead(juSeq);
				}
				
				HashMap<String, Object> result = reportService.update(tempVO, null, null);

				if (Integer.parseInt(result.get("result").toString()) > 0) {
					errorMsg = "";
				}
				
				cnt++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		map.put("msg", errorMsg);
		
		return map;
	}
	
	@Override
	public int update(final ReportJudgeVO reportJudgeVO) throws Exception {
		return reportJudgeMapper.update(reportJudgeVO);
	}

	@Override
	public List<ReportVO> selectWaitList(final ReportSearchVO reportSearchVO) {
		return reportJudgeMapper.selectWaitList(reportSearchVO);
	}

	@Override
	public List<ReportVO> selectWaitListAll(final ReportSearchVO reportSearchVO) {
		return reportJudgeMapper.selectWaitListAll(reportSearchVO);
	}

	@Override
	public int selectWaitListCnt(final ReportSearchVO reportSearchVO) {
		return reportJudgeMapper.selectWaitListCnt(reportSearchVO);
	}
	
	@Override
	public List<ReportVO> selectApproveList(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectApproveList(reportSearchVO);
	}
	
	@Override
	public int selectApproveListCnt(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectApproveListCnt(reportSearchVO);
	}

	@Override
	public List<ReportVO> selectApproveListAll(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectApproveListAll(reportSearchVO);
	}

	@Override
	public List<ReportVO> selectMyList(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectMyList(reportSearchVO);
	}
	
	@Override
	public int selectMyListCnt(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectMyListCnt(reportSearchVO);
	}

	@Override
	public List<ReportVO> selectMyListAll(final ReportSearchVO reportSearchVO) throws Exception {
		return reportJudgeMapper.selectMyListAll(reportSearchVO);
	}


	@Override
	public List<HashMap<String, String>> statsCategory(ReportSearchVO reportSearchVO) throws Exception {
		reportSearchVO.setCategoryType(1);
		List<HashMap<String, String>> cateList1 =  reportJudgeMapper.statsCategory(reportSearchVO);
		reportSearchVO.setCategoryType(2);
		List<HashMap<String, String>> cateList2=  reportJudgeMapper.statsCategory(reportSearchVO);
		List<HashMap<String, String>> placeList=  reportJudgeMapper.selectPlace(reportSearchVO);
		
		for(HashMap<String, String> place : placeList){
			String name = (String)place.get("PLACE");
			for(HashMap<String, String> cateMap : cateList1){
				if(name.equals((String)cateMap.get("IN_PLACE"))){
					place.put(cateMap.get("IN_CATEGORY1") + "_1", String.valueOf(cateMap.get("CNT")));
				}
			}
			
			for(HashMap<String, String> cateMap : cateList2){
				if(name.equals((String)cateMap.get("IN_PLACE"))){
					place.put(cateMap.get("IN_CATEGORY2") + "_2", String.valueOf(cateMap.get("CNT")));
				}
			}
		}
		
		for(HashMap<String, String> place : placeList) {
			int total = 0;
			for (String mapKey : place.keySet()) {
				if(!"PLACE_NAME".equals(mapKey) && !"PLACE".equals(mapKey)){
					total += Integer.parseInt(place.get(mapKey));				}
			}
			place.put("TOTAL", String.valueOf(total));
		}
		
		for(HashMap<String, String> place : placeList) {
			for(String cate : reportSearchVO.getCategory1()){
				String key = cate  + "_1";
				if(place.get(key) == null){
					place.put(key, "0"); 
				}
			}
			for(String cate : reportSearchVO.getCategory2()){
				if(place.get(cate + "_2") == null){
					place.put(cate + "_2", "0"); 
				}
			}
		}
		
		if (placeList.size() > 0) {
			HashMap<String, String> totalMap = new HashMap<String, String>();
			totalMap.put("PLACE_NAME", "누계");
			
			for (String key : placeList.get(0).keySet()) {
				if (key.equals("PLACE_NAME") || key.equals("PLACE")) {
					continue;
				}
				int tt = 0;
				for (HashMap<String, String> hashMap : placeList) {
					tt = tt + Integer.parseInt(hashMap.get(key));
				}
				totalMap.put(key, String.valueOf(tt));
			}
			
			placeList.add(placeList.size(), totalMap);	
		}
		
		return placeList;
	}
	
	

	@Override
	public List<HashMap<String, String>> statsJudge(final ReportSearchVO reportSearchVO) throws Exception {
		reportSearchVO.setCategoryType(3);
		List<HashMap<String, String>> cateList1 =  reportJudgeMapper.statsCategory(reportSearchVO);
		
		List<HashMap<String, String>> placeList=  reportJudgeMapper.selectPlace(reportSearchVO);
		
		for(HashMap<String, String> place : placeList){
			String name = (String)place.get("PLACE");
			for(HashMap<String, String> cateMap : cateList1){
				if(name.equals((String)cateMap.get("IN_PLACE"))){
					place.put("C0" + String.valueOf(cateMap.get("IN_JUDGE")), String.valueOf(cateMap.get("CNT")));
				}
			}
			
		}
		
		
		for(HashMap<String, String> place : placeList) {
			int total = 0;
			for (String mapKey : place.keySet()) {
				if(!"PLACE_NAME".equals(mapKey) && !"PLACE".equals(mapKey)){
					total += Integer.parseInt(place.get(mapKey));				}
			}
			place.put("TOTAL", String.valueOf(total));
		}
		for(HashMap<String, String> place : placeList) {
			for(String cate : reportSearchVO.getJudges()){
				String key = "C" + cate;
				if(place.get(key) == null){
					place.put(key, "0"); 
				}
			}
		}
		
		for(HashMap<String, String> place : placeList) {
			int ju1 = Integer.parseInt(place.get("C01"));
			int ju2 = Integer.parseInt(place.get("C02"));
			int ju3 = Integer.parseInt(place.get("C03"));
			int ju4 = Integer.parseInt(place.get("C04"));
			int ju5 = Integer.parseInt(place.get("C05"));
			int ju6 = Integer.parseInt(place.get("C06"));
			int ju7 = Integer.parseInt(place.get("C07"));
			
			place.put("AG", String.valueOf(ju1 + ju2));
			place.put("BG", String.valueOf(ju3 + ju4));
			place.put("CG", String.valueOf(ju5 + ju6));
			place.put("DG", String.valueOf(ju7));
		}
		
		if (placeList.size() > 0) {
			HashMap<String, String> totalMap = new HashMap<String, String>();
			totalMap.put("PLACE_NAME", "누계");
			
			for (String key : placeList.get(0).keySet()) {
				if (key.equals("PLACE_NAME") || key.equals("PLACE")) {
					continue;
				}
				int tt = 0;
				for (HashMap<String, String> hashMap : placeList) {
					tt = tt + Integer.parseInt(hashMap.get(key));
				}
				totalMap.put(key, String.valueOf(tt));
			}
			
			placeList.add(placeList.size(), totalMap);	
		}
		
		return placeList;
	}
	
}
