package com.chaozhanggui.admin.system.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.admin.system.annotation.OpLog;
import com.chaozhanggui.common.system.config.RespBody;
import com.chaozhanggui.common.system.util.IPUtil;
import com.chaozhanggui.dao.system.dao.TbPlussAdminRecodeMapper;
import com.chaozhanggui.dao.system.entity.TbPlussAdminRecodeWithBLOBs;
import com.chaozhanggui.dao.system.entity.TbPlussOperationRecord;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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 org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Slf4j
@Aspect
@Component
public class OpLogAspect {

    @Autowired
    TbPlussAdminRecodeMapper tbPlussAdminRecodeMapper;

    @Pointcut("execution(* com.chaozhanggui.admin.system.controller..*.*(..)) && @annotation(com.chaozhanggui.admin.system.annotation.OpLog))")
    public void executionService() {
    }


    @AfterReturning(returning="rvt", value = "executionService()")
    public void after(JoinPoint point, Object rvt) {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        if (attributes != null) {
            request = ((ServletRequestAttributes) attributes).getRequest();
        } else {
            log.warn("未获取到request");
            return;
        }

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        OpLog annotation = method.getAnnotation(OpLog.class);

        String loginName=request.getHeader("loginName");
        String token=request.getHeader("token");
        String userId=request.getHeader("userId");
        if(ObjectUtil.isEmpty(loginName)||ObjectUtil.isEmpty(token)||ObjectUtil.isEmpty(userId)){
            log.error("token 信息不存在");
            return;
        }

        String body=processInputArg(point.getArgs());

        TbPlussAdminRecodeWithBLOBs tbPlussAdminRecodeWithBLOBs=new TbPlussAdminRecodeWithBLOBs();

        tbPlussAdminRecodeWithBLOBs.setUserId(Integer.valueOf(userId));
        tbPlussAdminRecodeWithBLOBs.setOperationCode(annotation.opCode());
        tbPlussAdminRecodeWithBLOBs.setRemark(annotation.opDetail());
        tbPlussAdminRecodeWithBLOBs.setIp(IPUtil.getIpAddress(request));
        tbPlussAdminRecodeWithBLOBs.setReqBody(body);

        if (rvt instanceof RespBody) {
            try {
                JSONObject jsonObject = (JSONObject) JSON.toJSON(rvt);
                tbPlussAdminRecodeWithBLOBs.setResponseBody("返回结果:"+jsonObject.toString());
            } catch (Exception e) {
            }
        }
        tbPlussAdminRecodeWithBLOBs.setCreateTime(new Date());
        tbPlussAdminRecodeMapper.insert(tbPlussAdminRecodeWithBLOBs);
    }


    private String processInputArg(Object[] args) {
        StringBuffer sb=new StringBuffer();
        sb.append("请求参数:");
        if(ObjectUtil.isNotEmpty(args)||args.length>0){
            Arrays.stream(args).forEach(it->{
                if(it instanceof String||it instanceof Integer||it instanceof Long){
                    sb.append(it);
                    sb.append("&");
                }else if(it instanceof Object){
                    sb.append(JSONUtil.toJsonStr(it));
                    sb.append("&");
                }

            });
        }
        return sb.substring(0,sb.length()-1).toString();

    }
}
