package com.example.struts2;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 计算器 Action - 表单处理示例
 * 
 * 学习点：
 * - Action 接收表单参数（通过 setter）
 * - 数据验证（validate 方法）
 * - 结果类型
 */
public class CalculatorAction extends ActionSupport {
    
    private Double num1;
    private Double num2;
    private String operator;
    private Double result;
    
    // 默认执行方法
    public String execute() {
        return SUCCESS;
    }
    
    // 计算方法
    public String calculate() {
        if (num1 == null || num2 == null || operator == null) {
            return INPUT;
        }
        
        switch (operator) {
            case "+":
                result = num1 + num2;
                break;
            case "-":
                result = num1 - num2;
                break;
            case "*":
                result = num1 * num2;
                break;
            case "/":
                if (num2 == 0) {
                    addFieldError("num2", "除数不能为0");
                    return INPUT;
                }
                result = num1 / num2;
                break;
            default:
                return INPUT;
        }
        return SUCCESS;
    }
    
    // 验证方法
    @Override
    public void validate() {
        if (num1 == null) {
            addFieldError("num1", "请输入第一个数字");
        }
        if (num2 == null) {
            addFieldError("num2", "请输入第二个数字");
        }
    }
    
    // Getter and Setter（Struts2 通过这些接收参数）
    public Double getNum1() { return num1; }
    public void setNum1(Double num1) { this.num1 = num1; }
    
    public Double getNum2() { return num2; }
    public void setNum2(Double num2) { this.num2 = num2; }
    
    public String getOperator() { return operator; }
    public void setOperator(String operator) { this.operator = operator; }
    
    public Double getResult() { return result; }
    public void setResult(Double result) { this.result = result; }
}