package com.madeu.service.web.webgroup.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.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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.webgroup.WebGroupSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.service.web.webgroup.WebGroupService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("WebGroupService")
public class WebGroupServiceImpl implements WebGroupService {
	
	@Autowired
	private WebGroupSqlMapDAO webGroupSqlMapDAO;
	
	@Autowired
	private WebMemberSqlMapDAO webMemberSqlMapDAO;
	
	@Autowired
	private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
	
	/**
	 * 조직 리스트 조회 (List, option)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListGroupOption(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebGroupServiceImpl selectListGroupOption 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;
			
			if(true == check){
				List<Map<String, Object>> listMap = webGroupSqlMapDAO.selectListGroupOption(paramMap);

				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebGroupServiceImpl selectListGroupOption END");
		return map;
	}
	
	/**
	 * 조직 리스트 화면으로 이동.
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListGroupIntro(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebGroupServiceImpl selectListGroupIntro 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("WebGroupServiceImpl selectListGroupIntro END");
		return map;
	}
	
	/**
	 * 조직 리스트 조회
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListGroup(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebGroupServiceImpl selectListGroup START");

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		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){
				List<Map<String, Object>> totalCountListMap = webGroupSqlMapDAO.selectTotalGroupCount(paramMap);
				int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));
				
				if(0 < totalCount) {
					// 리스트 조회
					listMap = webGroupSqlMapDAO.selectListGroup(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("WebGroupServiceImpl selectListGroup END");
		return map;
	}
	
	/**
	 * 조직 정보 상세 조회 (one)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectGroup(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebGroupServiceImpl selectGroup START");

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

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

		try{
			boolean check  = true;
			String muGroupId    = String.valueOf(paramMap.get("muGroupId"));
			
			// 정렬
			if(true != ValidationCheckUtil.emptyCheck(muGroupId)){
				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){
				List<Map<String, Object>> listMap = webGroupSqlMapDAO.selectGroup(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebGroupServiceImpl selectGroup END");
		return map;
	}
	
	/**
	 * 조직 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertGroup(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebGroupServiceImpl insertGroup START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("groupName           :"+paramMap.get("groupName"));
		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 groupName      = String.valueOf(paramMap.get("groupName"));
			String etc            = String.valueOf(paramMap.get("etc"));
			
			if(true != ValidationCheckUtil.emptyCheck(groupName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","조직명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(groupName,35)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","조직명 정보는 35자를 넘을 수 없습니다.");
				}
			}
			
			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 muGroupId = ("G").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muGroupId",muGroupId);
				paramMap.put("muMemberId", paramMap.get("loginMemberId"));
				webGroupSqlMapDAO.insertGroup(paramMap);
				log.debug("muGroupId :"+paramMap.get("id"));
				paramMap.put("muGroupId", paramMap.get("id"));
				map.put("muGroupId", paramMap.get("muGroupId"));

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

	/**
	 * 조직 정보 수정
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> updateGroup(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebGroupServiceImpl updateGroup START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muGroupId           :"+paramMap.get("muGroupId"));
		log.debug("groupName           :"+paramMap.get("groupName"));
		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 muGroupId      = String.valueOf(paramMap.get("muGroupId"));
			String groupName      = String.valueOf(paramMap.get("groupName"));
			String etc            = String.valueOf(paramMap.get("etc"));

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

			if(true != ValidationCheckUtil.emptyCheck(groupName)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","조직명 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(groupName,35)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","조직명 정보는 35자를 넘을 수 없습니다.");
				}
			}

			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){
				webGroupSqlMapDAO.updateGroup(paramMap);
				map.put("muGroupId", paramMap.get("muGroupId"));
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "수정되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebGroupServiceImpl updateGroup END");
		return map;
	}

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

		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muGroupId           :"+paramMap.get("muGroupId"));
		
		try{
			boolean check  = true;
			JSONParser jsonParser = new JSONParser();
			JSONArray jsonArray = (JSONArray) jsonParser.parse(String.valueOf(paramMap.get("deleteDataList")));
			if(0==jsonArray.size()){
				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){

				for(Object object:jsonArray) {
					JSONObject jsonObject = (JSONObject) object;
					String muGroupId = (String) jsonObject.get("muGroupId");
					HashMap<String, Object> removeDataMap = new HashMap<String, Object>();
					removeDataMap.put("muGroupId", muGroupId);
					removeDataMap.put("modId", paramMap.get("modId"));
					webGroupSqlMapDAO.deleteGroup(removeDataMap);
				}
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "삭제 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebGroupServiceImpl deleteGroup END");
		return map;
	}
}
