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

import java.text.SimpleDateFormat;
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.webloghistory.WebLogHistorySqlMapDAO;
import com.madeu.service.web.webloghistory.WebLogHistoryService;
import com.madeu.util.ValidationCheckUtil;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service("WebLogHistoryService")
public class WebLogHistoryServiceImpl implements WebLogHistoryService{

	@Autowired
	private WebLogHistorySqlMapDAO webLogHistorySqlMapDAO;
	
	/**
	 * 오류 로그 정보 리스트 조회 (List)
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	public HashMap<String, Object> selectListLogHistory(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebLogHistoryServiceImpl selectListLogHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("muMemberId              :"+paramMap.get("muMemberId"));
		
		log.debug("selectParam             :"+paramMap.get("selectParam"));
		log.debug("keywordParam            :"+paramMap.get("keywordParam"));
		log.debug("sort                    :"+paramMap.get("sort"));
		log.debug("start                   :"+paramMap.get("start"));
		log.debug("limit                   :"+paramMap.get("limit"));
		log.debug("sort                    :"+paramMap.get("sort"));
		log.debug("dir                     :"+paramMap.get("dir"));
		log.debug("currentPage             :"+paramMap.get("currentPage"));
		
		log.debug("searchStartDate         :"+paramMap.get("searchStartDate"));
		log.debug("searchEndDate           :"+paramMap.get("searchEndDate"));
		log.debug("searchDateType          :"+paramMap.get("searchDateType"));

		log.debug("searchCategoryItemId    :"+paramMap.get("searchCategoryItemId"));

		try{
			// 정렬 
			if(null==paramMap.get("dir")||("").equals(paramMap.get("dir"))){
				
			}
			else{
				String dir = String.valueOf(paramMap.get("dir"));
				if(("A").equals(dir)){
					paramMap.put("dir", "DESC");
				}
				else if(("B").equals(dir)){
					paramMap.put("dir", "ASC");
				}
				else {
					paramMap.put("dir", "DESC");
				}
			}
			
			paramMap.put("useYn", "Y");
			
			List<Map<String, Object>> totalCountListMap = webLogHistorySqlMapDAO.selectTotalLogHistoryCount(paramMap);
			List<Map<String, Object>> listMap = webLogHistorySqlMapDAO.selectListLogHistory(paramMap);

			map.put("msgCode", Constants.OK);
			map.put("success","true");
			map.put("totalCount",totalCountListMap.get(0).get("totalCount"));
			map.put("rows",listMap);
			
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebLogHistoryServiceImpl selectListLogHistory END");
		return map;
	}
	
	/**
	 * 오류 로그 정보 상세 조회 (one)
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	public HashMap<String, Object> selectLogHistory(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebLogHistoryServiceImpl selectLogHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("muMemberId          :"+paramMap.get("muMemberId"));
		
		log.debug("muLogHistoryId      :"+paramMap.get("muLogHistoryId"));
		
		try{
			boolean check  = true;
			
			if(true == check){
				List<Map<String, Object>> listMap = webLogHistorySqlMapDAO.selectLogHistory(paramMap);
				
				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
				
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		log.debug("WebLogHistoryServiceImpl selectLogHistory END");
		return map;
	}
	
	/**
	 * 오류 로그 정보 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> insertLogHistory(
			HashMap<String, Object> paramMap, HashMap<String, Object> visitLogParamMap) throws Exception{
		log.debug("WebLogHistoryServiceImpl insertLogHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		log.debug("muMemberId      	: "+paramMap.get("muMemberId"));

		log.debug("url              : "+paramMap.get("url"));
		log.debug("func             : "+paramMap.get("func"));
		log.debug("service          : "+paramMap.get("service"));
		log.debug("requestValue     : "+paramMap.get("requestValue"));
		log.debug("responseValue    : "+paramMap.get("responseValue"));
		log.debug("tId              : "+paramMap.get("tId"));
		log.debug("resultCode       : "+paramMap.get("resultCode"));
		log.debug("resultMsg        : "+paramMap.get("resultMsg"));

		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());

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

			paramMap.put("visitIp", visitLogParamMap.get("visitIp"));
			paramMap.put("visitOriginAgent", visitLogParamMap.get("visitOriginAgent"));
			paramMap.put("visitAgent", visitLogParamMap.get("visitAgent"));
			paramMap.put("visitOs", visitLogParamMap.get("visitOs"));
			paramMap.put("regId", "SYSTEM");
			paramMap.put("modId", "SYSTEM");

			if(true == check){
				paramMap.put("tDate", tDate);
				paramMap.put("tId", tId);
				
				String muLogHistoryId = ("H").concat(String.valueOf(System.currentTimeMillis()));
				paramMap.put("muLogHistoryId",muLogHistoryId);
				paramMap.put("muMemberId", paramMap.get("muMemberId"));
				webLogHistorySqlMapDAO.insertLogHistory(paramMap);
				log.debug("muLogHistoryId :"+paramMap.get("id"));
				paramMap.put("muLogHistoryId", paramMap.get("id"));
				map.put("muLogHistoryId", paramMap.get("muLogHistoryId"));

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

	/**
	 * 오류 로그 정보 수정
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> updateLogHistory(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebLogHistoryServiceImpl updateLogHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("muMemberId       :"+paramMap.get("muMemberId"));
		
		log.debug("muLogHistoryId   :"+paramMap.get("muLogHistoryId"));
		
		log.debug("etCategoryItemId :"+paramMap.get("etCategoryItemId"));
		log.debug("title            :"+paramMap.get("title"));
		log.debug("content          :"+paramMap.get("content"));
		log.debug("writeName        :"+paramMap.get("writeName"));
		log.debug("writeDate        :"+paramMap.get("writeDate"));

		log.debug("deleteFileId     :"+paramMap.get("deleteFileId"));

		try{
			boolean check  = true;

			String muLogHistoryId       = String.valueOf(paramMap.get("muLogHistoryId"));
			String etCategoryItemId = String.valueOf(paramMap.get("etCategoryItemId"));
			String title            = String.valueOf(paramMap.get("title"));
			String content          = String.valueOf(paramMap.get("content"));
			String writeName        = String.valueOf(paramMap.get("writeName"));
			String writeDate        = String.valueOf(paramMap.get("writeDate"));

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

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

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

			if(true != ValidationCheckUtil.emptyCheck(content)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","내용 정보가 없습니다.");
			}

			if(true != ValidationCheckUtil.emptyCheck(writeName)){

			}
			else{
				if(true != ValidationCheckUtil.lengthCheck(writeName,255)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","작성자 정보는 255자를 넘을 수 없습니다.");
				}
			}

			if(true != ValidationCheckUtil.emptyCheck(writeDate)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","작성일자 정보가 없습니다.");
			}
			else{
				if(true != ValidationCheckUtil.dateCheck(writeDate)){
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","작성일자 정보가 YYYY-MM-DD 형식에 맞지 않습니다.");
				}
			}
			
			if(true == check){
				webLogHistorySqlMapDAO.updateLogHistory(paramMap);
				map.put("muLogHistoryId", paramMap.get("muLogHistoryId"));

				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "수정되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebLogHistoryServiceImpl updateLogHistory END");
		return map;
	}

	/**
	 * 오류 로그 정보 삭제
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception 
	 */
	@Override
	@Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
	public HashMap<String, Object> deleteLogHistory(
			HashMap<String, Object> paramMap) throws Exception{
		log.debug("WebLogHistoryServiceImpl deleteLogHistory START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("muMemberId      :"+paramMap.get("muMemberId"));
		
		// ,로 구분
		log.debug("selectId        :"+paramMap.get("selectId"));
		
		try{
			boolean check  = true;
			
			if(null== paramMap.get("selectId") || ("").equals(paramMap.get("selectId"))){
				check = false;
			}
			
			if(true == check){
				String selectId = String.valueOf(paramMap.get("selectId"));
				StringTokenizer selectData = new StringTokenizer(selectId, ",");
				while(selectData.hasMoreTokens()){//토큰이 계속 있을때 까지
					String muLogHistoryId = selectData.nextToken();
					
					HashMap<String, Object> deleteParamMap = new HashMap<String, Object>();
					deleteParamMap.put("muLogHistoryId", muLogHistoryId);
					deleteParamMap.put("modId", paramMap.get("muMemberId"));
					webLogHistorySqlMapDAO.deleteLogHistory(deleteParamMap);
				}
				
				map.put("msgCode", Constants.OK);
				map.put("msgDesc", "삭제 되었습니다.");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		log.debug("WebLogHistoryServiceImpl deleteLogHistory END");
		return map;
	}
}
