package com.dhcc.finance.ibatis;

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

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Intercepts({
	@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="update", args={MappedStatement.class, Object.class}), 
	@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="query", args={MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
@Component
public class SQLCostStatisticsInterceptor implements Interceptor {
  
  	public Object intercept(Invocation paramInvocation) {
	  return _intercept(paramInvocation);
  	}
  
  	public Object _intercept(Invocation paramInvocation) {
	    Object localObject = null;
	    long start = System.currentTimeMillis();
	    try {
			localObject = paramInvocation.proceed();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	    long end = System.currentTimeMillis();
	    long cost = end - start;
	    MappedStatement localMappedStatement = (MappedStatement)paramInvocation.getArgs()[0];
	    StringBuffer localStringBuffer = new StringBuffer(localMappedStatement.getId());
	    localStringBuffer.append(" >> 耗时");
	    localStringBuffer.append(cost);
	    localStringBuffer.append("毫秒");
	    log.info(localStringBuffer.toString());
	    localStringBuffer = null;
	    localMappedStatement = null;
	    return localObject;
  	}
  
  	public Object plugin(Object paramObject) {
  		return Plugin.wrap(paramObject, this);
  	}
  
  	public void setProperties(Properties paramProperties) {
  		
  	}
}

