package com.sckw.transport.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @desc: 自动填充
 * @author: Lt
 * @date: 2024-05-15
 */
@Intercepts(
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
)
@Component
public class Myplugin implements Interceptor {
    //获取到拦截的对象，底层也是通过代理来实现的，实际上是拿到一个目标的代理对象
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    //获取配置文件中设置的阈值等参数
    @Override
    public void setProperties(Properties properties) {

    }
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
        //获取操作类型，crud
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //获取参数
        Object parameter = invocation.getArgs()[1];
        Field[]fields = parameter.getClass().getDeclaredFields();


        for(Field field: fields){
            //注入对应的属性值
            if ("createBy".equals(field.getName())&&SqlCommandType.INSERT.equals(sqlCommandType)){
                field.setAccessible(true);
                field.set(parameter,"admin");
            }
            if ("updateBy".equals(field.getName())&&SqlCommandType.UPDATE.equals(sqlCommandType)){
                field.setAccessible(true);
                field.set(parameter,"admin");
            }
        }

        return invocation.proceed();
    }
}
