package com.ruoyi.framework.aspectj;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

/**
 * AOP 拦截SQL处理
 *
 * @author hzh
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();
        // 修改SQL语句
        String modifiedSql = BeforeSQL(sql);
        // 将修改后的SQL语句设置回StatementHandler
        ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", modifiedSql);
        invocation.proceed();
        ReflectUtils.setFieldValue(statementHandler.getBoundSql(), "sql", sql);
        return invocation.proceed();
    }

    // 根据类型设置不同的选择数据源格式
    private String modifySql(String sql) {
        try {
            SecurityUtils.getDatabaseType();
        } catch (Exception e) {
            return sql;
        }
        if (SecurityUtils.getDatabaseType().equals("sqlserver"))
            return "USE `" + SecurityUtils.getDatabaseName() + "`; " + sql;
        if (SecurityUtils.getDatabaseType().equals("dm"))
            return "set schema " + SecurityUtils.getDatabaseName() + "; " + sql;
        if (SecurityUtils.getDatabaseType().equals("mysql"))
            return "USE `" + SecurityUtils.getDatabaseName() + "`; " + sql;
        return sql;
    }

    // 根据类型设置不同的选择数据源格式
    private String BeforeSQL(String sql) {
        try {
            SecurityUtils.getDatabaseType();
        } catch (Exception e) {
            return sql;
        }
        if (SecurityUtils.getDatabaseType().equals("sqlserver"))
            return "USE `" + SecurityUtils.getDatabaseName() + "`; ";
        if (SecurityUtils.getDatabaseType().equals("dm"))
            return "set schema " + SecurityUtils.getDatabaseName() + "; ";
        if (SecurityUtils.getDatabaseType().equals("mysql"))
            return "USE `" + SecurityUtils.getDatabaseName() + "`; ";
        return sql;
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}