package com.crm.rely.backend.aspect;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.EmptyInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author houn
 * @Date 2024/12/24 17:43
 * @PackageName:com.crm.rely.backend.aspect
 * @ClassName: HibernateQueryInterceptor
 * @Description: TODO
 */
@Slf4j
@Component
public class HibernateQueryInterceptor extends EmptyInterceptor {
    @Value("${spring.jpa.hibernate.interceptor.enableDeleteCondition:false}")
    private boolean enableDeleteCondition;

    @Override
    public String onPrepareStatement(String sql) {
        if (!enableDeleteCondition) {
            return sql;
        }
        // 检查是否已经包含 delete 条件
        if (!sql.toLowerCase().contains("delete = 0")) {
            // 修改 SQL，添加 delete 条件
            sql = modifySqlWithDeleteCondition(sql);
        }

        log.debug("拦截并修改 SQL: {}", sql);
        return super.onPrepareStatement(sql);
    }

    private String modifySqlWithDeleteCondition(String sql) {
        if (sql.trim().toLowerCase().startsWith("select")) {
            return handleSelectSql(sql);
        } else if (sql.trim().toLowerCase().startsWith("update")) {
            return handleUpdateSql(sql);
        }
        // 不处理其他类型的 SQL
        return sql;
    }

    private String handleSelectSql(String sql) {
        // 匹配 SELECT 查询中的 WHERE 子句
        String regex = "(?i)(\\bfrom\\b.*?\\bwhere\\b)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String fromClause = matcher.group(1); // 获取匹配的 "FROM ... WHERE" 部分

            // 提取表别名
            String tableAliasRegex = "(?i)(\\bfrom\\b\\s+[^\\s]+\\s+(\\w+))";
            Pattern aliasPattern = Pattern.compile(tableAliasRegex);
            Matcher aliasMatcher = aliasPattern.matcher(fromClause);

            if (aliasMatcher.find()) {
                String alias = aliasMatcher.group(2); // 获取表别名
                return sql.replaceFirst("(?i)where", "WHERE " + alias + ".`delete` = 0 AND ");
            } else {
                // 如果没有别名，直接添加 delete 条件
                return sql.replaceFirst("(?i)where", "WHERE `delete` = 0 AND ");
            }
        } else {
            // 如果没有 WHERE 子句，直接添加 WHERE 和条件
            return sql + " WHERE `delete` = 0";
        }
    }

    private String handleUpdateSql(String sql) {
        // 检查是否已经存在 WHERE 子句
        if (sql.toLowerCase().contains(" where ")) {
            // 在 WHERE 子句前添加 delete 条件
            return sql.replaceFirst("(?i)where", "WHERE `delete` = 0 AND ");
        } else {
            // 如果没有 WHERE 子句，直接添加条件
            return sql + " WHERE `delete` = 0";
        }
    }
}