package cn.iocoder.yudao.module.server.utils;

import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import java.util.Random;

/**
 * 数学表达式验证码文本生成器
 * 生成如 "1+2=?" 这样的数学计算题
 */
public class MathTextCreator extends DefaultTextCreator {
    
    private static final Random RANDOM = new Random();
    
    @Override
    public String getText() {
        // 生成简单的数学表达式
        int a = RANDOM.nextInt(10) + 1;  // 1-10
        int b = RANDOM.nextInt(10) + 1;  // 1-10
        
        // 随机选择运算符
        String operator;
        int result;
        
        int opType = RANDOM.nextInt(3);
        switch (opType) {
            case 0: // 加法
                operator = "+";
                result = a + b;
                break;
            case 1: // 减法（确保结果不为负数）
                operator = "-";
                if (a < b) {
                    int temp = a;
                    a = b;
                    b = temp;
                }
                result = a - b;
                break;
            case 2: // 乘法
                operator = "×";
                result = a * b;
                break;
            default:
                operator = "+";
                result = a + b;
        }
        
        // 格式：如 "3+4=?"
        return a + operator + b + "=?";
    }
    
    /**
     * 从数学表达式中提取正确答案
     */
    public static int extractAnswer(String expression) {
        try {
            // 去掉问号
            expression = expression.replace("=?", "");
            
            if (expression.contains("+")) {
                String[] parts = expression.split("\\+");
                return Integer.parseInt(parts[0]) + Integer.parseInt(parts[1]);
            } else if (expression.contains("-")) {
                String[] parts = expression.split("-");
                return Integer.parseInt(parts[0]) - Integer.parseInt(parts[1]);
            } else if (expression.contains("×")) {
                String[] parts = expression.split("×");
                return Integer.parseInt(parts[0]) * Integer.parseInt(parts[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}