package com.seer.teach.common.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

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


/**
 * <p>
 *
 * </p >
 *
 * @author Captain
 * @since 2025-08-12 14:42
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class UpdateTimePlugin implements Interceptor, InnerInterceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();

        // 拿到原始 SQL
        String originalSql = statementHandler.getBoundSql().getSql();

        // 如果是 UPDATE 且没包含 update_time 字段，则拼接
        if (originalSql.trim().toUpperCase().startsWith("UPDATE")
                && !originalSql.toLowerCase().contains("update_time")) {
            // 替换 SET 为 SET update_time = NOW(),
            String newSql = originalSql.replaceFirst("(?i)SET", "SET update_time = NOW(),");
            // 用反射把新SQL写回去
            java.lang.reflect.Field field = statementHandler.getBoundSql().getClass().getDeclaredField("sql");
            field.setAccessible(true);
            field.set(statementHandler.getBoundSql(), newSql);
        }

        return invocation.proceed();
    }

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

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