package com.zhentao.controller;

import com.zhentao.utils.TIMUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 腾讯云 IM 控制器
 */
@RestController
@RequestMapping("/api/im")
@CrossOrigin(origins = "*")
public class TIMController {
    
    @Autowired
    private TIMUtils timUtils;
    
    @Value("${tim.sdkappid}")
    private long sdkAppId;
    
    /**
     * 获取 UserSig
     * GET /api/im/getUserSig?userId=1
     */
    @GetMapping("/getUserSig")
    public Map<String, Object> getUserSig(@RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String userSig = timUtils.generateUserSig(String.valueOf(userId));
            
            Map<String, String> data = new HashMap<>();
            data.put("userSig", userSig);
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", data);
            
            System.out.println("✅ 生成 UserSig 成功，userId: " + userId);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "生成 UserSig 失败: " + e.getMessage());
            System.err.println("❌ 生成 UserSig 失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 导入单个用户到腾讯云IM
     * POST /api/im/importUser
     * @param params 包含 userId, nickname, faceUrl 的参数对象
     */
    @PostMapping("/importUser")
    public Map<String, Object> importUser(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String userId = params.get("userId");
            String nickname = params.get("nickname");
            String faceUrl = params.get("faceUrl");
            
            if (userId == null || userId.isEmpty()) {
                result.put("code", 400);
                result.put("message", "userId 不能为空");
                return result;
            }
            
            // 生成管理员 UserSig（用于调用REST API）
            String adminUserSig = timUtils.generateUserSig("administrator", 24 * 3600);
            
            // 构建请求URL
            String url = String.format(
                "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=%d&identifier=administrator&usersig=%s&random=%d&contenttype=json",
                sdkAppId,
                adminUserSig,
                System.currentTimeMillis()
            );
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("UserID", userId);
            if (nickname != null && !nickname.isEmpty()) {
                requestBody.put("Nick", nickname);
            }
            if (faceUrl != null && !faceUrl.isEmpty()) {
                requestBody.put("FaceUrl", faceUrl);
            }
            
            // 发送请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            @SuppressWarnings("unchecked")
            Map<String, Object> response = restTemplate.postForObject(url, entity, Map.class);
            
            System.out.println("✅ 导入用户成功: " + userId);
            System.out.println("   响应: " + response);
            
            result.put("code", 200);
            result.put("message", "导入用户成功");
            result.put("data", response);
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("❌ 导入用户失败: " + e.getMessage());
            result.put("code", 500);
            result.put("message", "导入用户失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 批量导入用户
     * POST /api/im/importUsers
     * @param userIds 用户ID列表（逗号分隔）
     */
    @PostMapping("/importUsers")
    public Map<String, Object> importUsers(@RequestParam String userIds) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String[] ids = userIds.split(",");
            int successCount = 0;
            int failCount = 0;
            
            for (String userId : ids) {
                try {
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", userId.trim());
                    importUser(params);
                    successCount++;
                    
                    // 避免请求过快
                    Thread.sleep(100);
                    
                } catch (Exception e) {
                    failCount++;
                    System.err.println("导入用户失败: " + userId + ", 错误: " + e.getMessage());
                }
            }
            
            result.put("code", 200);
            result.put("message", "批量导入完成");
            
            Map<String, Integer> data = new HashMap<>();
            data.put("total", ids.length);
            data.put("success", successCount);
            data.put("fail", failCount);
            result.put("data", data);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "批量导入失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 快速批量导入常用用户
     * GET /api/im/importCommonUsers
     * 导入用户1-20（常用测试用户）
     */
    @GetMapping("/importCommonUsers")
    public Map<String, Object> importCommonUsers() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            int successCount = 0;
            int failCount = 0;
            List<String> errors = new ArrayList<>();
            
            // 导入用户 1-20
            for (int i = 1; i <= 20; i++) {
                try {
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", String.valueOf(i));
                    params.put("nickname", "用户" + i);
                    
                    Map<String, Object> importResult = importUser(params);
                    
                    if ((int)importResult.get("code") == 200) {
                        successCount++;
                        System.out.println("✅ 导入用户成功: " + i);
                    } else {
                        failCount++;
                        errors.add("用户" + i + ": " + importResult.get("message"));
                        System.err.println("❌ 导入用户失败: " + i);
                    }
                    
                    // 避免请求过快
                    Thread.sleep(100);
                    
                } catch (Exception e) {
                    failCount++;
                    errors.add("用户" + i + ": " + e.getMessage());
                    System.err.println("❌ 导入用户失败: " + i + ", 错误: " + e.getMessage());
                }
            }
            
            result.put("code", 200);
            result.put("message", "批量导入完成");
            
            Map<String, Object> data = new HashMap<>();
            data.put("total", 20);
            data.put("success", successCount);
            data.put("fail", failCount);
            data.put("errors", errors);
            result.put("data", data);
            
            System.out.println("🎉 批量导入完成: 成功 " + successCount + " 个，失败 " + failCount + " 个");
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "批量导入失败: " + e.getMessage());
        }
        
        return result;
    }
}
