package com.tiesheng.core.config.operation;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.tiesheng.annotation.operation.OperationLog;
import com.tiesheng.core.config.token.TokenParse;
import com.tiesheng.core.config.token.bean.TokenBean;
import com.tiesheng.core.service.CoreLogService;
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 java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * @author hao
 * @ProjectName CmccSpring
 * @Copyright Hangzhou ShuoChuang Technology Co.,Ltd All Right Reserved
 * @Description 这里是对文件的描述
 * @data 2019-07-15
 * @note 这里写文件的详细功能和改动
 * @note
 */
@Aspect
@Component
public class OperationAspect {

    @Autowired
    CoreLogService coreLogService;


    @Pointcut("@annotation(com.tiesheng.annotation.operation.OperationLog)")
    public void methodArgs() {

    }


    /**
     * 获取操作日志说明
     *
     * @param joinPoint
     */
    @Around("methodArgs()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperationLog operationLog = method.getAnnotation(OperationLog.class);
        String subject = operationLog.subject();
        String insertKey = operationLog.insertKey();

        Object reqObj = null;
        Map<String, Object> allParams = new HashMap<>(16);
        if (joinPoint.getArgs().length > 0) {
            reqObj = joinPoint.getArgs()[0];
            allParams.putAll(BeanUtil.beanToMap(reqObj));
        }

        Object response = joinPoint.proceed(joinPoint.getArgs());
        allParams.putAll(BeanUtil.beanToMap(response));

        if (!StrUtil.isEmpty(subject)) {

            // 添加、编辑关键字处理
            if (!StrUtil.isEmpty(insertKey)) {
                String insertVal = MapUtil.getStr(allParams, insertKey);
                subject = (StrUtil.isEmpty(insertVal) ? "添加" : "编辑") + subject;
            }

            // 占位符处理
            subject = StrUtil.format(subject, allParams);
        }

        coreLogService.addOperationLog(operationLog.title(), subject, reqObj);

        return response;
    }


}
