package interceptor;

import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;

@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})})
public class MyBatisLogInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        // MetaObject 是 Mybatis 提供的一个用于访问对象属性的对象
        MetaObject metaObject = SystemMetaObject.forObject(invocation);
        
        BoundSql boundSql = (BoundSql)metaObject.getValue("target.delegate.boundSql");
        
        String sql = boundSql.getSql().toLowerCase();
        
        Map<?, ?> map = (Map<?, ?>)boundSql.getParameterObject();
        
        System.out.println(map);
        
        List<ParameterMapping> keyList = boundSql.getParameterMappings();
        
        if(keyList != null && !keyList.isEmpty()){
            for(int i = 0; i < keyList.size(); i++){
                ParameterMapping pm = keyList.get(i);
                sql = formatterSql(sql, map.get(pm.getProperty()));
            }
        }
        
        
        System.out.println(sql);

        return invocation.proceed();
    }
    
    private String formatterSql(String sql, Object parameter){
        return sql.replaceFirst("\\?", "'" + Matcher.quoteReplacement(parameter.toString()) + "'");
    }
}
