package com.platform.interceptor;

import java.util.HashMap;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
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.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * 自定义拦截器方法，处理模糊查询中包含特殊字符（_、%、\）
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
public class EscapeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // TODO Auto-generated method stub
        // 拦截sql
        Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        // 请求参数对象
        Object parameterObject = args[1];

        // 获取 SQL
        SqlCommandType sqlCommandType = statement.getSqlCommandType();
        if (SqlCommandType.SELECT.equals(sqlCommandType)) {
            if (parameterObject instanceof HashMap) {
                // 调用特殊字符处理方法
                HashMap hash = (HashMap) parameterObject;
                hash.forEach((k, v) -> {
                    // 仅拦截字符串类型且值不为空
                    if (v != null && v instanceof String) {
                        String value = (String) v;
                        value = value.replaceAll("\\\\", "\\\\\\\\");
                        value = value.replaceAll("%", "\\\\%");
                        // 请求参数对象HashMap重新赋值转义后的值
                        hash.put(k, value);
                    }
                });

            }
        }
        // 返回
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // TODO Auto-generated method stub
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

}