package cn.axzo.msg.center.message.service.todo.mybatis;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
import lombok.RequiredArgsConstructor;
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.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
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.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.util.ReflectionUtils;

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

/**
 * @author yanglin
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class}),
        @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 ReplaceInterceptor implements Interceptor {

    private static final ThreadLocal<Replacement> LOCAL = new ThreadLocal<>();

    public static void enable(Replacement replacement) {
        LOCAL.set(replacement);
    }

    public static void disable() {
        LOCAL.remove();
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Replacement replacement = LOCAL.get();
        if (replacement == null)
            return invocation.proceed();
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        SqlCommandType commandType = ms.getSqlCommandType();
        BoundSql boundSql = ms.getBoundSql(args[1]);
        SQLStatement stmt;
        MySqlStatementParser parser = new MySqlStatementParser(boundSql.getSql());
        if (commandType == SqlCommandType.UPDATE) {
            stmt = parser.parseUpdateStatement();
        } else if (commandType == SqlCommandType.SELECT) {
            stmt = parser.parseSelect();
        } else if (commandType == SqlCommandType.INSERT) {
            stmt = parser.parseInsert();
        } else if (commandType == SqlCommandType.DELETE) {
            stmt = parser.parseDeleteStatement();
        } else {
            return invocation.proceed();
        }
        if (stmt instanceof MySqlInsertStatement && replacement.isInsertPreserveId()) {
            maybeInsertPreserveId((MySqlInsertStatement) stmt, boundSql.getParameterObject());
        }
        stmt.accept(new ReplaceVisitor(replacement));
        String newSql = stmt.toString();
        args[0] = copyMappedStatement(ms, parameterObject -> new CustomBoundSql(
                ms.getConfiguration(), newSql, boundSql.getParameterMappings(), parameterObject, boundSql));
        return invocation.proceed();
    }

    private void maybeInsertPreserveId(MySqlInsertStatement stmt, Object parameterObject) {
        if (stmt.getColumns().isEmpty() || stmt.getValues() == null) {
            return;
        }
        List<SQLExpr> columns = stmt.getColumns();
        String idColumn = columns.stream()
                .filter(column -> column instanceof SQLIdentifierExpr)
                .map(SQLIdentifierExpr.class::cast)
                .map(SQLIdentifierExpr::getName)
                .filter(name -> name.equals("id"))
                .findFirst()
                .orElse(null);
        if (idColumn != null) return;
        Number idValue = getIdValue(parameterObject);
        if (idValue == null) return;
        columns.add(new SQLIdentifierExpr("id"));
        stmt.getValues().addValue(idValue.longValue());
    }

    private Number getIdValue(Object parameterObject) {
        Field field = ReflectionUtils.findField(parameterObject.getClass(), "id");
        if (field == null) return null;
        field.setAccessible(true);
        Object value = ReflectionUtils.getField(field, parameterObject);
        return value instanceof Number ? (Number) value : null;
    }

    @RequiredArgsConstructor
    private static class ReplaceVisitor implements SQLASTVisitor {

        final Replacement replacement;

        @Override
        public boolean visit(SQLExprTableSource x) {
            SQLExpr expr = x.getExpr();
            if (expr instanceof SQLIdentifierExpr) {
                String tableName = ((SQLIdentifierExpr) expr).getName();
                if (tableName.equals(replacement.getSrcTable())) {
                    x.replace(expr, new SQLIdentifierExpr(replacement.getDestTable()));
                }
            }
            return false;
        }

    }

    private static class CustomBoundSql extends BoundSql {

        final BoundSql delegate;

        CustomBoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings,
                       Object parameterObject, BoundSql delegate) {
            super(configuration, sql, parameterMappings, parameterObject);
            this.delegate = delegate;
        }

        @Override
        public boolean hasAdditionalParameter(String name) {
            if (super.hasAdditionalParameter(name))
                return true;
            return delegate.hasAdditionalParameter(name);
        }

        @Override
        public Object getAdditionalParameter(String name) {
            Object parameter = super.getAdditionalParameter(name);
            if (parameter != null)
                return parameter;
            return delegate.getAdditionalParameter(name);
        }

    }

    private MappedStatement copyMappedStatement(MappedStatement ms, SqlSource sqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), sqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

}