package com.madeu.service.web.webwork.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.madeu.constants.Constants;
import com.madeu.dao.web.webauthmenurelation.WebAuthMenuRelationSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.dao.web.webwork.WebWorkSqlMapDAO;
import com.madeu.service.web.webwork.WebWorkService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("WebWorkService")
public class WebWorkServiceImpl implements WebWorkService {
	
	@Autowired
	private WebWorkSqlMapDAO webWorkSqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	/**
	 * 근무설정 리스트 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListWorkIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebWorkServiceImpl selectListWorkIntro START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		try{
			boolean check  = true;
			
			String menuClass    = String.valueOf(paramMap.get("menuClass"));
			
			// 정렬
			if(true != ValidationCheckUtil.emptyCheck(menuClass)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","메뉴 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					map.put("msgCode", Constants.OK);
					map.put("success","true");
					
					map.put("selectUseYn", authMenuRelationlistMap.get(0).get("selectUseYn"));
					map.put("insertUseYn", authMenuRelationlistMap.get(0).get("insertUseYn"));
					map.put("updateUseYn", authMenuRelationlistMap.get(0).get("updateUseYn"));
					map.put("deleteUseYn", authMenuRelationlistMap.get(0).get("deleteUseYn"));
					map.put("downloadUseYn", authMenuRelationlistMap.get(0).get("downloadUseYn"));
				}
				else {
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebWorkServiceImpl selectListWorkIntro END");
		return map;
	}
	
	/**
	 * 근무설정 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListWork(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebWorkServiceImpl selectListWork START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("workSearchKeywordParam  :"+paramMap.get("workSearchKeywordParam"));
		log.debug("workStart               :"+paramMap.get("workStart"));
		log.debug("workLimit               :"+paramMap.get("workLimit"));
		log.debug("workSort                :"+paramMap.get("workSort"));
		log.debug("workDir                 :"+paramMap.get("workDir"));
		
		log.debug("workSearchGroupId       :"+paramMap.get("workSearchGroupId"));
		log.debug("workSearchDutyId        :"+paramMap.get("workSearchDutyId"));

		List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
		
		try{
			boolean check  = true;
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

				if(1==authMenuRelationlistMap.size()){

					if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "조회 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}

			if(true == check){
				// 정렬 
				if(null==paramMap.get("workDir")||("").equals(paramMap.get("workDir"))){
					
				}
				else{
					String dir = String.valueOf(paramMap.get("dir"));
					if(("A").equals(dir)){
						paramMap.put("workDir", "DESC");
					}
					else if(("B").equals(dir)){
						paramMap.put("workDir", "ASC");
					}
					else {
						paramMap.put("workDir", "DESC");
					}
				}
				
				paramMap.put("useYn", "Y");
				
				List<Map<String, Object>> totalCountListMap = webWorkSqlMapDAO.selectTotalWorkCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webWorkSqlMapDAO.selectListWork(paramMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("totalCount", totalCount);
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebWorkServiceImpl selectListWork END");
		return map;
	}
	
	/**
	 * 근무설정 정보 상세 조회 (one)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectWork(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebWorkServiceImpl selectWork START");

		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muWorkId            :"+paramMap.get("muWorkId"));

		try{
			boolean check  = true;
			String muWorkId    = String.valueOf(paramMap.get("muWorkId"));
			
			// 정렬
			if(true != ValidationCheckUtil.emptyCheck(muWorkId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","근무설정 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}

			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

				if(1==authMenuRelationlistMap.size()){

					if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "조회 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
			if(true == check){
				List<Map<String, Object>> listMap = webWorkSqlMapDAO.selectWork(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}

		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}

		log.debug("WebWorkServiceImpl selectWork END");
		return map;
	}
	
	/**
	 * 근무설정 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertWork(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebWorkServiceImpl insertWork START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("workName            :"+paramMap.get("workName"));
		log.debug("startTime           :"+paramMap.get("startTime"));
		log.debug("endTime             :"+paramMap.get("endTime"));
		log.debug("muGroupId           :"+paramMap.get("muGroupId"));
		log.debug("muDutyId            :"+paramMap.get("muDutyId"));
		log.debug("etc                 :"+paramMap.get("etc"));

		try{
			boolean check  = true;
			String tId = String.valueOf(System.currentTimeMillis());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar c1 = Calendar.getInstance();
			String tDate = sdf.format(c1.getTime());

			String workName        = String.valueOf(paramMap.get("workName"));
			String startTime       = String.valueOf(paramMap.get("startTime"));
			String endTime         = String.valueOf(paramMap.get("endTime"));
			String muGroupId       = String.valueOf(paramMap.get("muGroupId"));
			String muDutyId        = String.valueOf(paramMap.get("muDutyId"));
			String etc             = String.valueOf(paramMap.get("etc"));
			
			if(true != ValidationCheckUtil.emptyCheck(workName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","근무일정명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(workName,255)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","근무일정명 정보는 100자를 넘을 수 없습니다.");
				}
			}

			if(true != ValidationCheckUtil.emptyCheck(startTime)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","시작시간 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(endTime)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","종료시간 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(muGroupId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","조직 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(muDutyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","직무 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					
					if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "등록 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
			
			if(true == check){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				
				String muWorkId = ("W").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muWorkId",muWorkId);
				paramMap.put("muMemberId", paramMap.get("loginMemberId"));
				webWorkSqlMapDAO.insertWork(paramMap);
				log.debug("muWorkId :"+paramMap.get("id"));
				paramMap.put("muWorkId", paramMap.get("id"));
				map.put("muWorkId", paramMap.get("muWorkId"));

				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "등록되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebWorkServiceImpl insertWork END");
		return map;
	}

	/**
	 * 근무설정 정보 수정
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> updateWork(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebWorkServiceImpl updateWork START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muWorkId            :"+paramMap.get("muWorkId"));

		log.debug("workName            :"+paramMap.get("workName"));
		log.debug("startTime           :"+paramMap.get("startTime"));
		log.debug("endTime             :"+paramMap.get("endTime"));
		log.debug("muGroupId           :"+paramMap.get("muGroupId"));
		log.debug("muDutyId            :"+paramMap.get("muDutyId"));
		log.debug("etc                 :"+paramMap.get("etc"));

		try{
			boolean check  = true;

			String muWorkId        = String.valueOf(paramMap.get("muWorkId"));
			String workName        = String.valueOf(paramMap.get("workName"));
			String startTime       = String.valueOf(paramMap.get("startTime"));
			String endTime         = String.valueOf(paramMap.get("endTime"));
			String muGroupId       = String.valueOf(paramMap.get("muGroupId"));
			String muDutyId        = String.valueOf(paramMap.get("muDutyId"));
			String etc             = String.valueOf(paramMap.get("etc"));

			if(true != ValidationCheckUtil.emptyCheck(muWorkId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","근무설정 식별자 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(workName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","근무일정명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(workName,255)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","근무일정명 정보는 100자를 넘을 수 없습니다.");
				}
			}

			if(true != ValidationCheckUtil.emptyCheck(startTime)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","시작시간 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(endTime)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","종료시간 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(muGroupId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","조직 정보가 없습니다.");
			}
			
			if(true != ValidationCheckUtil.emptyCheck(muDutyId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","직무 정보가 없습니다.");
			}

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					
					if(("Y").equals(authMenuRelationlistMap.get(0).get("updateUseYn"))) {
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "수정 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
			
			if(true == check){
				webWorkSqlMapDAO.updateWork(paramMap);
				map.put("muWorkId", paramMap.get("muWorkId"));
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "수정되었습니다.");
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebWorkServiceImpl updateWork END");
		return map;
	}

	/**
	 * 근무설정 정보 삭제
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> deleteWork(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebWorkServiceImpl deleteWork START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		// ,로 구분
		log.debug("selectId            :"+paramMap.get("selectId"));
		
		try{
			boolean check  = true;
			
			if(null== paramMap.get("selectId") || ("").equals(paramMap.get("selectId"))){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc", "삭제 대상이 없습니다.");
			}

			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1==userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
			
			if(true == check){
				// 권한 조회
				HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
				authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
				authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
				List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
				int authMenuRelationlistMapSize = authMenuRelationlistMap.size();
				
				if(1==authMenuRelationlistMapSize){
					
					if(("Y").equals(authMenuRelationlistMap.get(0).get("deleteUseYn"))) {
						
					}
					else {
						check = false;
						map.put("msgCode", Constants.FAIL);
						map.put("msgDesc", "삭제 권한 정보가 없습니다.");
					}
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "권한 정보가 없습니다.");
				}
			}
			
			if(true == check){
				String selectId = String.valueOf(paramMap.get("selectId"));
				StringTokenizer selectData = new StringTokenizer(selectId, ",");
				while(selectData.hasMoreTokens()){//토큰이 계속 있을때 까지
					String muWorkId = selectData.nextToken();
					
					HashMap<String, Object> deleteParamMap = new HashMap<String, Object>();
					deleteParamMap.put("muWorkId", muWorkId);
					deleteParamMap.put("modId", paramMap.get("loginMemberId"));
					webWorkSqlMapDAO.deleteWork(deleteParamMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "삭제 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebWorkServiceImpl deleteWork END");
		return map;
	}
}
