package com.jay.monitor.data.client.interceptor;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.jay.monitor.data.client.MonitorSendProducer;
import com.jay.monitor.data.client.api.DefaultIdSupplier;
import com.jay.monitor.data.client.config.props.MonitorProperties;
import com.jay.monitor.data.client.config.props.SQLMonitorProperties;
import com.jay.monitor.data.core.model.serializable.SQLMonitorDTO;
import com.jay.monitor.data.core.utils.JsonHelper;
import com.jay.monitor.data.core.utils.ObjectHelper;
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.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;

import java.text.DateFormat;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@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 JaySqlInterceptor implements Interceptor {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private Properties properties;

    private SQLMonitorProperties sqlMonitorProperties;

    public JaySqlInterceptor(MonitorProperties monitorProperties) {
        this.sqlMonitorProperties = monitorProperties != null ? monitorProperties.getSql() : new SQLMonitorProperties();
    }

    @Autowired(required = false)
    private Supplier<String> supplier = new DefaultIdSupplier();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //begin cat transaction
        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
        Object returnValue = null;
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            returnValue = invocation.proceed();
            stopWatch.stop();
            invokeSuccessMetric(invocation, stopWatch, returnValue);
        } catch (Throwable e) {
            invokeErrorMetric(invocation, e);
            throw e;
        }
        return returnValue;
    }

    private void invokeErrorMetric(Invocation invocation, Throwable e) {
        SQLMonitorDTO sqlMonitorDTO = new SQLMonitorDTO();
        try {
            sqlMonitorDTO.setRequestTime(-1L);
            sqlMonitorDTO.setStatus(-1);
            sqlMonitorDTO.setResult(e.getMessage());
            sqlMonitorDTO.setErrorMessage(e.getMessage());
            sqlMonitorDTO.setCreateDate(new Date());
            sqlMonitorDTO.setLogId(supplier.get());
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
            String sqlTypeName = mappedStatement.getSqlCommandType().name();
            sqlMonitorDTO.setCommandType(sqlTypeName);
            sqlMonitorDTO.setSqlId(mappedStatement.getId());
            String sql = getSql(invocation, mappedStatement);
            sqlMonitorDTO.setSql(sql);
            sqlMonitorDTO.setTable(getTableName(sql));
            sqlMonitorDTO.setJsonContent(sql);
            String errorStackTrace = ObjectHelper.errorToString(e);
            sqlMonitorDTO.setErrorStackTrace(errorStackTrace);
        } catch (Exception ex) {
            logger.warn("SQL收集异常", ex);
        } finally {
            MonitorSendProducer.sendMsg(sqlMonitorDTO);
        }
    }

    private void invokeSuccessMetric(Invocation invocation, StopWatch stopWatch, Object returnValue) {

        try {
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];

            String sqlTypeName = mappedStatement.getSqlCommandType().name();

            long totalTimeMillis = stopWatch.getTotalTimeMillis();

            // 查询的频率过高，没必要每个查询SQL都收集。
            if (skipCollect(mappedStatement, returnValue, totalTimeMillis)) {
                return;
            }

            SQLMonitorDTO sqlMonitorDTO = new SQLMonitorDTO();
            String sql = getSql(invocation, mappedStatement);
            sqlMonitorDTO.setLogId(supplier.get());
            sqlMonitorDTO.setCreateDate(new Date());
            sqlMonitorDTO.setCommandType(sqlTypeName);
            sqlMonitorDTO.setRequestTime(totalTimeMillis);
            sqlMonitorDTO.setSqlId(mappedStatement.getId());
            sqlMonitorDTO.setSql(sql);
            sqlMonitorDTO.setTable(getTableName(sql));
            sqlMonitorDTO.setJsonContent(sql);

            if (SqlCommandType.UPDATE == mappedStatement.getSqlCommandType() || SqlCommandType.DELETE == mappedStatement
                .getSqlCommandType()) {
                if (returnValue instanceof Number) {
                    sqlMonitorDTO.setAffectedRows(((Number)returnValue).intValue());
                }
            } else if (SqlCommandType.INSERT == mappedStatement.getSqlCommandType()) {
                sqlMonitorDTO.setAffectedRows(1);
                sqlMonitorDTO.setDataId(returnValue.toString());
            } else if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
                if (returnValue instanceof Collection) {
                    int size = ((Collection<?>)returnValue).size();
                    sqlMonitorDTO.setResult(size);
                } else {
                    sqlMonitorDTO.setResult(returnValue);
                }
            }
            sqlMonitorDTO.setStatus(1);
            MonitorSendProducer.sendMsg(sqlMonitorDTO);
        } catch (Exception e) {
            logger.warn("SQL收集异常", e);
            invokeErrorMetric(invocation, e);
        }
    }

    /**
     * 跳过一些不必要的收集内容
     *
     * @param mappedStatement
     * @param returnValue
     * @param totalTimeMillis
     * @return
     */
    private boolean skipCollect(MappedStatement mappedStatement, Object returnValue, long totalTimeMillis) {
        Long longRow = this.sqlMonitorProperties.getLongRow();
        Long longTime = this.sqlMonitorProperties.getLongTime();
        if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
            if (longTime < totalTimeMillis) {
                return true;
            }
            if (returnValue instanceof Collection) {
                int size = ((Collection<?>)returnValue).size();
                // 如果查询超过设定的SQL,还是得要关注一下.
                if (size > longRow) {
                    return true;
                }
            }
        }
        return false;
    }

    private String getMethodName(MappedStatement mappedStatement) {
        String[] strArr = mappedStatement.getId().split("\\.");
        return strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
    }

    private String getSql(Invocation invocation, MappedStatement mappedStatement) {
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        return showSql(configuration, boundSql);
    }

    private static String getParameterValue(Object obj) {
        StringBuilder retStringBuilder = new StringBuilder();
        if (obj instanceof String) {
            retStringBuilder.append("'").append(obj).append("'");
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            retStringBuilder.append("'").append(formatter.format(new Date())).append("'");
        } else {
            retStringBuilder.append("'").append(obj == null ? "" : obj).append("'");
        }
        return retStringBuilder.toString();
    }

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        StringBuilder sqlBuilder = new StringBuilder(sql);
        if (parameterMappings.size() > 0 && parameterObject != null) {
            int start = sqlBuilder.indexOf("?");
            int end = start + 1;

            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sqlBuilder.replace(start, end, getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sqlBuilder.replace(start, end, getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sqlBuilder.replace(start, end, getParameterValue(obj));
                    }

                    start = sqlBuilder.indexOf("?");
                    end = start + 1;
                }
            }
        }
        return sqlBuilder.toString();
    }

    public String getTableName(String sql) {
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, "Mysql");
        for (SQLStatement stmt : stmtList) {
            PGSchemaStatVisitor visitor = new PGSchemaStatVisitor();
            stmt.accept(visitor);
            Map<TableStat.Name, TableStat> tables = visitor.getTables();
            if (tables.size() > 0) {
                List<String> tableNameList =
                    tables.keySet().stream().map(TableStat.Name::getName).collect(Collectors.toList());
                if (tableNameList.size() == 1) {
                    return tableNameList.get(0);
                } else {
                    return JsonHelper.toJsonString(tableNameList);
                }
            }
        }
        return null;
    }

    public String getConditionalFiledValue(String sql, String filed) {
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, "Mysql");
        for (SQLStatement stmt : stmtList) {
            PGSchemaStatVisitor visitor = new PGSchemaStatVisitor();
            stmt.accept(visitor);
            List<TableStat.Condition> conditions = visitor.getConditions();
            if (conditions.size() > 0) {
                TableStat.Condition condition =
                    conditions.stream().filter(var -> var.getColumn().getName().equals(filed)).findFirst().orElse(null);

                if (condition != null) {
                    TableStat.Column column = condition.getColumn();
                    String name = column.getName();
                } else {
                    //                    return JsonHelper.toJsonString(tableNameList);
                }
            }
        }
        return null;
    }

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

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

}