package com.example.struts2;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * AJAX演示Action - 展示Struts2处理异步请求
 * 
 * 学习点：
 * - 返回JSON数据
 * - 处理AJAX请求
 * - 前后端分离交互
 */
public class AjaxDemoAction extends ActionSupport {
    
    private String username;
    private String email;
    private Integer age;
    private Long userId;
    
    // Gson用于JSON序列化
    private static final Gson gson = new Gson();
    
    /**
     * 检查用户名是否可用（AJAX验证）
     */
    public String checkUsername() {
        Map<String, Object> result = new HashMap<>();
        
        // 模拟数据库检查
        boolean available = !"admin".equals(username) && !"root".equals(username);
        
        result.put("available", available);
        result.put("message", available ? "用户名可用" : "用户名已被占用");
        result.put("username", username);
        
        writeJsonResponse(result);
        return NONE;
    }
    
    /**
     * 获取用户统计信息
     */
    public String getStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalUsers", 156);
        stats.put("activeUsers", 89);
        stats.put("newUsersToday", 12);
        stats.put("timestamp", System.currentTimeMillis());
        
        writeJsonResponse(stats);
        return NONE;
    }
    
    /**
     * 模拟保存用户（AJAX提交）
     */
    public String saveUser() {
        Map<String, Object> result = new HashMap<>();
        
        // 模拟验证
        if (username == null || username.trim().isEmpty()) {
            result.put("success", false);
            result.put("error", "用户名不能为空");
        } else if (email == null || !email.contains("@")) {
            result.put("success", false);
            result.put("error", "邮箱格式不正确");
        } else {
            // 模拟保存成功
            result.put("success", true);
            result.put("message", "用户保存成功");
            result.put("userId", System.currentTimeMillis());
            result.put("username", username);
        }
        
        writeJsonResponse(result);
        return NONE;
    }
    
    /**
     * 获取实时数据（模拟）
     */
    public String getRealtimeData() {
        Map<String, Object> data = new HashMap<>();
        data.put("serverTime", new java.util.Date().toString());
        data.put("requestsPerSecond", Math.random() * 100);
        data.put("memoryUsage", Runtime.getRuntime().totalMemory() / 1024 / 1024);
        data.put("activeSessions", (int)(Math.random() * 50) + 10);
        
        writeJsonResponse(data);
        return NONE;
    }
    
    /**
     * 辅助方法：写入JSON响应
     */
    private void writeJsonResponse(Map<String, Object> data) {
        try {
            ServletActionContext.getResponse().setContentType("application/json;charset=UTF-8");
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.print(gson.toJson(data));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // Getters and Setters
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
    
    public Long getUserId() { return userId; }
    public void setUserId(Long userId) { this.userId = userId; }
}
