/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.common.aspect;

import com.google.gson.Gson;

import io.jsonwebtoken.Claims;
import io.renren.common.annotation.MemberLog;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.modules.admin.entity.MemberLogEntity;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.service.MemberLogService;
import io.renren.modules.admin.service.MemberService;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.utils.JwtUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 系统日志，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class MemberLogAspect {
	@Autowired
    private JwtUtils jwtUtils;
	@Autowired
	private MemberLogService memberLogService;
	@Autowired
	private MemberService memberService;
	
	@Pointcut("@annotation(io.renren.common.annotation.MemberLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		//保存日志
		saveMemberLog(point, time);

		return result;
	}

	private void saveMemberLog(ProceedingJoinPoint joinPoint, long time) {
		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		
		//获取用户凭证
		String token = request.getHeader("token");
		if(StringUtils.isBlank(token)){
			token = request.getParameter("token");
		} 
		// 有登陆token则记录日志, 无则不记录
		if (StringUtils.isNotBlank(token)) {
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			Method method = signature.getMethod();
	
			MemberLogEntity memberLogEntity = new MemberLogEntity();
			MemberLog memberLog = method.getAnnotation(MemberLog.class);
			if(memberLog != null){
				//注解上的描述
				memberLogEntity.setOperation(memberLog.value());
			}
	
			//请求的方法名
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = signature.getName();
			memberLogEntity.setMethod(className + "." + methodName + "()");
	
			//请求的参数
			Object[] args = joinPoint.getArgs();
			try{
				String params = new Gson().toJson(args);
				memberLogEntity.setParams(params);
			}catch (Exception e){
	
			}
	
			memberLogEntity.setIp(IPUtils.getIpAddr(request));
			// id、姓名
			System.out.println(token);
			Claims claims = jwtUtils.getClaimByToken(token);
			// System.out.println(Long.parseLong(claims.getSubject()));
			Long userId = Long.parseLong(claims.getSubject());
			MemberEntity member = memberService.getById(userId);
	
			memberLogEntity.setMemberId(member.getUserId());
			memberLogEntity.setUsername(member.getUsername());
	
			memberLogEntity.setTime(time);
			memberLogEntity.setCreateDate(new Date());
			//保存系统日志
			memberLogService.save(memberLogEntity);
		}
	}
}
