package kcg.imis.cmmn.aop;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

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

import kcg.imis.cmmn.service.LogService;
import kcg.imis.cmmn.service.MenuService;
import kcg.imis.cmmn.vo.MenuVO;
import kcg.imis.sec.LoginUserVO;
import kcg.imis.sec.UserUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import egovframework.rte.psl.dataaccess.util.EgovMap;

/**
  * @FileName : CommonAop.java
  * @Project : 국제해양프로젝트
  * @Date : 2018. 3. 21. 
  * @작성자 : Moon
  * @변경이력 : 
  * @프로그램 설명 : 공통AOP 객체
 */
@Aspect
@Component
public class CommonAop {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CommonAop.class);

	@Resource(name = "menuService")
	MenuService menuService;

	@Resource(name = "logService")
	LogService logService;

	@Around("execution(* kcg.imis..*Controller.*(..))")
	public Object menuGenerator(final ProceedingJoinPoint thisJoinPoint) throws Throwable {

		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String[] excludeUrls = {"/loginView.do","/member/regist.json","/code/codeList.json", "/member/checkId.json"};
		String loginUrl = "/loginView.do";
		String url = req.getRequestURI();

		for(String excludeUrl : excludeUrls){
			if(excludeUrl.endsWith(url)){
				return thisJoinPoint.proceed();	
			}
		}
		
		LoginUserVO loginUserVO = null;
		try {
			loginUserVO = UserUtil.getMemberInfo();
		} catch (Exception e) {
			// 세션정보가 없을 경우 로그인 페이지로 이동.
			if (loginUserVO == null) {
				return "redirect:" + loginUrl;
			}
		}
		try {
			for (Object obj : thisJoinPoint.getArgs()) {
				if (obj instanceof Model) {
					Model model = (Model) obj;

					MenuVO menuVO = new MenuVO();
					menuVO.setRoleLevel(loginUserVO.getRolelevel());
					List<MenuVO> mainMenuList = menuService.selectMainMenu(menuVO);
					model.addAttribute("mainMenuList", mainMenuList);
					model.addAttribute("topMenu", menuService.getTopMenu());
					HashMap<String, Object> menu = new HashMap<String, Object>();

					String subStr = url.substring(1);
					String boardId = "";
					String group = subStr.split("/")[0];
					String onlyUrl = subStr;
					String qryCate = "";
					if (onlyUrl.indexOf("/") > -1) {
						onlyUrl = subStr.substring(onlyUrl.indexOf("/"));
					} else {
						return thisJoinPoint.proceed();
					}
					url = onlyUrl;

					if (req.getParameter("bbsId") != null) {
						boardId = req.getParameter("bbsId");
					}

					if(req.getParameter("ct") != null && !req.getParameter("ct").equals("")){
						qryCate = "ct=" + req.getParameter("ct");
						model.addAttribute("worlddb", req.getParameter("ct"));
					}
					if(req.getParameter("seq") != null){
						qryCate = "seq=" + req.getParameter("seq");
						model.addAttribute("worlddb", req.getParameter("seq"));
					}
					menu.put("url", url);
					menu.put("group", group);
					menu.put("boardId", boardId);
					menu.put("query", qryCate);

					EgovMap menuInfo = menuService.getMenuInfo(menu);
					menuInfo.put("userId", loginUserVO.getUserid());
					model.addAttribute("menu", menuInfo);
					
					List<MenuVO> subMenuList = menuService.getSubMenu(menuInfo);
					
					model.addAttribute("subMenu", subMenuList);
					
					 ((BigDecimal) menuInfo.get("depth")).intValue();
					 
					List<EgovMap>  currAndHigherMenuList = menuService.selectListWithHigher(menuInfo.get("id").toString());
					model.addAttribute("currAndHigherMenuList", currAndHigherMenuList);
					
					addUserLog(req, menuInfo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Object proc = thisJoinPoint.proceed();
		return proc;
	}
	
	
	private void addUserLog(final HttpServletRequest req, EgovMap menu) {
		
		try {
			LoginUserVO user = (LoginUserVO) req.getSession().getAttribute("userVO");
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userid", user.getUserid());
			paramMap.put("name", user.getName());
			paramMap.put("userip", req.getRemoteAddr());
			paramMap.put("place1", user.getPlace1());
			paramMap.put("place2", user.getPlace2());
			paramMap.put("position", user.getDuties());
	
			paramMap.put("menuid", menu.get("id"));
			paramMap.put("location", req.getRequestURI());

			logService.insertUserLog(paramMap);
		} catch (Exception e) {
			LOGGER.error("fail log insert...............");
			LOGGER.error(e.getMessage());
		}
		
	}
	
}
