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

import com.alibaba.druid.sql.ast.SQLLimit;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
import com.baomidou.mybatisplus.core.MybatisParameterHandler;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.zaxxer.hikari.pool.ProxyStatement;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.StatementType;
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.springframework.core.Ordered;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author yanglin
 */
@Slf4j
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class})})
public class BeautifulPaginationInterceptor implements Interceptor, Ordered {

    private final PaginationInterceptor delegate = new CustomPaginationInterceptor();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (SqlCommandType.SELECT != mappedStatement.getSqlCommandType()
                || StatementType.CALLABLE == mappedStatement.getStatementType()) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        SQLStatement selectStmt = new MySqlStatementParser(boundSql.getSql()).parseSelect();
        AtomicBoolean limitPresent = new AtomicBoolean(false);
        selectStmt.accept(new SQLASTVisitor() {
            @Override
            public boolean visit(SQLLimit x) {
                limitPresent.set(true);
                return false;
            }
        });
        if (limitPresent.get())
            return invocation.proceed();
        else {
            Object result = delegate.intercept(invocation);
            if (result == null)
                CollectSQLInterceptor.maybeBuildSqlSelf(() -> tryBuildSql(invocation));
            return result;
        }
    }

    private static String tryBuildSql(Invocation invocation) {
        Connection connection = (Connection) (invocation.getArgs()[0]);
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        try (PreparedStatement statement = connection.prepareStatement(boundSql.getSql())) {
            if (!(statement instanceof ProxyStatement))
                return null;
            MybatisParameterHandler parameterHandler = new MybatisParameterHandler(
                    mappedStatement, boundSql.getParameterObject(), boundSql);
            parameterHandler.setParameters(statement);
            return SQLAccessor.getSql((ProxyStatement) statement);
        } catch (Exception e) {
            log.warn("error - tryBuildSql", e);
            return null;
        }
    }

    private static class CustomPaginationInterceptor extends PaginationInterceptor {

        public CustomPaginationInterceptor() {
            limit = 5000;
        }

    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
