package com.zhentao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.dto.MatchmakerQueryDTO;
import com.zhentao.entity.Matchmaker;
import com.zhentao.service.MatchmakerService;
import com.zhentao.vo.MatchmakerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

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

/**
 * 红娘控制器
 */
@RestController
@RequestMapping("/api/matchmaker")
@CrossOrigin(origins = "*")
public class MatchmakerController {
    
    @Autowired
    private MatchmakerService matchmakerService;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    // websocket 服务的 IM 接口地址
    private static final String IM_SERVICE_URL = "http://localhost:1004/api/im";
    
    /**
     * 分页查询红娘列表
     * 
     * @param queryDTO 查询条件
     * @return 分页数据
     */
    @PostMapping("/list")
    public Result<Page<MatchmakerVO>> getMatchmakerList(@RequestBody(required = false) MatchmakerQueryDTO queryDTO) {
        try {
            // 如果queryDTO为null，创建默认对象
            if (queryDTO == null) {
                queryDTO = new MatchmakerQueryDTO();
            }
            
            // 设置默认值
            if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1) {
                queryDTO.setPageNum(1);
            }
            if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1) {
                queryDTO.setPageSize(10);
            }
            
            // 调试日志：打印接收到的参数
            System.out.println("📥 接收到的查询参数: matchmakerType=" + queryDTO.getMatchmakerType() 
                    + ", level=" + queryDTO.getLevel() 
                    + ", keyword=" + queryDTO.getKeyword()
                    + ", pageNum=" + queryDTO.getPageNum()
                    + ", pageSize=" + queryDTO.getPageSize());
            
            Page<MatchmakerVO> page = matchmakerService.getMatchmakerPage(queryDTO);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("❌ 查询红娘列表异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询红娘列表失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }
    
    /**
     * 获取红娘详情
     * 
     * @param matchmakerId 红娘ID
     * @return 红娘详情
     */
    @GetMapping("/detail/{matchmakerId}")
    public Result<MatchmakerVO> getMatchmakerDetail(@PathVariable Integer matchmakerId) {
        try {
            MatchmakerVO matchmakerVO = matchmakerService.getMatchmakerDetail(matchmakerId);
            if (matchmakerVO == null) {
                return Result.error("红娘不存在或已离职");
            }
            return Result.success(matchmakerVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询红娘详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录红娘的信息（通过 userId 查询）
     * 
     * @param userId 用户ID
     * @return 红娘信息
     */
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentMatchmaker(@RequestParam Integer userId) {
        try {
            Matchmaker matchmaker = matchmakerService.getMatchmakerByUserId(userId);
            if (matchmaker == null) {
                return Result.error("该用户不是红娘");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("matchmakerId", matchmaker.getMatchmakerId());
            result.put("realName", matchmaker.getRealName());
            result.put("avatarUrl", matchmaker.getAvatarUrl());
            result.put("userId", userId);
            result.put("imUserId", "m_" + matchmaker.getMatchmakerId());  // IM 用户 ID
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取红娘信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取全职红娘列表（首页展示）
     * 
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 全职红娘列表
     */
    @GetMapping("/formal")
    public Result<Page<MatchmakerVO>> getFormalMatchmakers(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            Page<MatchmakerVO> page = matchmakerService.getFormalMatchmakers(pageNum, pageSize);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询全职红娘列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建红娘
     * 
     * @param matchmaker 红娘信息
     * @return 创建结果
     */
    @PostMapping("/create")
    public Result<Matchmaker> createMatchmaker(@RequestBody Matchmaker matchmaker) {
        try {
            // 如果没有提供username，使用手机号作为用户名
            if (matchmaker.getUsername() == null || matchmaker.getUsername().isEmpty()) {
                matchmaker.setUsername(matchmaker.getPhone());
            }
            
            // 如果没有提供密码，设置默认密码（建议首次登录时强制修改）
            if (matchmaker.getPassword() == null || matchmaker.getPassword().isEmpty()) {
                matchmaker.setPassword("123456"); // 默认密码，实际应该加密
            }
            
            // 如果没有提供状态，设置默认状态为正常
            if (matchmaker.getStatus() == null) {
                matchmaker.setStatus(1); // 1-正常
            }

            if (matchmaker.getGender()== 1){
                matchmaker.setAvatarUrl("http://115.190.125.125:9000/dynamic-comments/dynamics/5c645152-9940-41d3-83a9-69ee6e0c0aaa.png");
            }

            if (matchmaker.getGender()== 2){
                matchmaker.setAvatarUrl("http://115.190.125.125:9000/dynamic-comments/dynamics/c7fb04d7-ee4d-4b3d-bcef-f246da9c841f.png");
            }
            
            // 保存红娘到数据库
            boolean success = matchmakerService.save(matchmaker);
            if (success) {
                // 导入红娘到腾讯云 IM（使用 m_ + matchmaker_id）
                String imUserId = "m_" + matchmaker.getMatchmakerId();
                try {
                    // 调用 websocket 服务的 IM 导入接口
                    Map<String, String> imParams = new HashMap<>();
                    imParams.put("userId", imUserId);
                    imParams.put("nickname", matchmaker.getRealName());
                    if (matchmaker.getAvatarUrl() != null && !matchmaker.getAvatarUrl().isEmpty()) {
                        imParams.put("faceUrl", matchmaker.getAvatarUrl());
                    }
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, String>> request = new HttpEntity<>(imParams, headers);
                    
                    restTemplate.postForObject(IM_SERVICE_URL + "/importUser", request, Map.class);
                    System.out.println("✅ 红娘已导入到腾讯云 IM: matchmakerId=" + matchmaker.getMatchmakerId() + ", imUserId=" + imUserId);
                } catch (Exception e) {
                    System.err.println("❌ 导入红娘到 IM 失败: " + e.getMessage());
                    e.printStackTrace();
                    // 导入失败不影响红娘创建，只记录日志
                }
                
                // 清除列表缓存
                matchmakerService.clearMatchmakerCache(null);
                return Result.success(matchmaker);
            } else {
                return Result.error("创建红娘失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建红娘失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新红娘信息
     * 
     * @param matchmakerId 红娘ID
     * @param matchmaker 红娘信息
     * @return 更新结果
     */
    @PutMapping("/update/{matchmakerId}")
    public Result<Matchmaker> updateMatchmaker(
            @PathVariable Integer matchmakerId,
            @RequestBody Matchmaker matchmaker) {
        try {
            matchmaker.setMatchmakerId(matchmakerId);
            boolean success = matchmakerService.updateById(matchmaker);
            if (success) {
                // 清除相关缓存
                matchmakerService.clearMatchmakerCache(matchmakerId);
                return Result.success(matchmaker);
            } else {
                return Result.error("更新红娘信息失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新红娘信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除红娘
     * 
     * @param matchmakerId 红娘ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{matchmakerId}")
    public Result<Void> deleteMatchmaker(@PathVariable Integer matchmakerId) {
        try {
            // 先查询红娘信息（用于后续删除 IM 账号）
            Matchmaker matchmaker = matchmakerService.getById(matchmakerId);
            if (matchmaker == null) {
                return Result.error("红娘不存在");
            }
            
            // 删除数据库记录
            boolean success = matchmakerService.removeById(matchmakerId);
            if (success) {
                // 从腾讯云 IM 删除红娘账号（使用 m_ + matchmaker_id）
                String imUserId = "m_" + matchmakerId;
                try {
                    // 调用 websocket 服务的 IM 删除接口
                    restTemplate.delete(IM_SERVICE_URL + "/deleteAccount?userId=" + imUserId);
                    System.out.println("✅ 已从腾讯云 IM 删除红娘账号: matchmakerId=" + matchmakerId + ", imUserId=" + imUserId);
                } catch (Exception e) {
                    System.err.println("❌ 从 IM 删除账号失败: " + e.getMessage());
                    e.printStackTrace();
                    // 删除失败不影响数据库删除，只记录日志
                }
                
                // 清除相关缓存
                matchmakerService.clearMatchmakerCache(matchmakerId);
                return Result.success(null);
            } else {
                return Result.error("删除红娘失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除红娘失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据userId查询红娘信息
     * 
     * @param userId 用户ID
     * @return 红娘信息
     */
    @GetMapping("/by-user/{userId}")
    public Result<MatchmakerVO> getMatchmakerByUserId(@PathVariable Long userId) {
        try {
            MatchmakerVO matchmakerVO = matchmakerService.getMatchmakerByUserId(userId);
            if (matchmakerVO == null) {
                return Result.error("红娘不存在");
            }
            return Result.success(matchmakerVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询红娘信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取红娘排行榜（总排行榜）
     * 
     * @param limit 返回数量限制，默认20
     * @return 红娘排行榜列表
     */
    @GetMapping("/ranking")
    public Result<List<MatchmakerVO>> getRankingList(
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        try {
            List<MatchmakerVO> rankingList = matchmakerService.getRankingList(limit);
            return Result.success(rankingList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取排行榜失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取本周红娘排行榜（按点赞数和成功人数的平均数排名）
     * 
     * @param limit 返回数量限制，默认20
     * @param userId 当前用户ID（可选，用于判断是否已点赞）
     * @return 红娘排行榜列表
     */
    @GetMapping("/weekly-ranking")
    public Result<List<MatchmakerVO>> getWeeklyRankingList(
            @RequestParam(value = "limit", defaultValue = "20") Integer limit,
            @RequestParam(value = "userId", required = false) Long userId) {
        try {
            List<MatchmakerVO> rankingList = matchmakerService.getWeeklyRankingList(limit);
            
            // 如果传入了userId，标记用户是否已点赞
            if (userId != null) {
                for (MatchmakerVO vo : rankingList) {
                    boolean hasLiked = matchmakerService.hasLikedThisWeek(userId, vo.getMatchmakerId().longValue());
                    vo.setHasLiked(hasLiked);
                }
            }
            
            return Result.success(rankingList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取本周排行榜失败：" + e.getMessage());
        }
    }
    
    /**
     * 给红娘点赞（一周只能给同一红娘点赞一次）
     * 
     * @param userId 用户ID
     * @param matchmakerId 红娘ID
     * @return 点赞结果
     */
    @PostMapping("/like")
    public Result<Map<String, Object>> likeMatchmaker(
            @RequestParam Long userId,
            @RequestParam Long matchmakerId) {
        try {
            // 检查是否给自己点赞
            Matchmaker selfMatchmaker = matchmakerService.getMatchmakerByUserId(userId.intValue());
            if (selfMatchmaker != null && selfMatchmaker.getMatchmakerId().equals(matchmakerId.intValue())) {
                return Result.error("不能给自己点赞哦");
            }
            
            // 检查是否已点赞
            if (matchmakerService.hasLikedThisWeek(userId, matchmakerId)) {
                return Result.error("本周已给该红娘点赞，下周再来吧");
            }
            
            boolean success = matchmakerService.likeMatchmaker(userId, matchmakerId);
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("liked", true);
                return Result.success("点赞成功", data);
            } else {
                return Result.error("点赞失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("点赞失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查用户是否已给某红娘点赞（本周）
     * 
     * @param userId 用户ID
     * @param matchmakerId 红娘ID
     * @return 是否已点赞
     */
    @GetMapping("/check-like")
    public Result<Map<String, Object>> checkLikeStatus(
            @RequestParam Long userId,
            @RequestParam Long matchmakerId) {
        try {
            boolean hasLiked = matchmakerService.hasLikedThisWeek(userId, matchmakerId);
            Map<String, Object> data = new HashMap<>();
            data.put("hasLiked", hasLiked);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查点赞状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量查询红娘信息
     * 
     * @param matchmakerIds 红娘ID列表，逗号分隔（例如：22,23,24）
     * @return 红娘信息列表
     */
    @GetMapping("/batch")
    public Result<List<MatchmakerVO>> batchGetMatchmakers(@RequestParam String matchmakerIds) {
        try {
            if (matchmakerIds == null || matchmakerIds.trim().isEmpty()) {
                return Result.success(Collections.emptyList());
            }
            
            // 解析ID列表
            String[] idArray = matchmakerIds.split(",");
            List<Integer> ids = new java.util.ArrayList<>();
            for (String id : idArray) {
                try {
                    ids.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    System.err.println("⚠️ 无效的红娘ID: " + id);
                }
            }
            
            if (ids.isEmpty()) {
                return Result.success(Collections.emptyList());
            }
            
            // 批量查询
            List<MatchmakerVO> matchmakers = matchmakerService.batchGetMatchmakers(ids);
            return Result.success(matchmakers);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量查询红娘信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量导入现有红娘到腾讯云 IM（一次性任务）
     * 
     * @return 导入结果
     */
    @PostMapping("/batch-import-to-im")
    public Result<Map<String, Object>> batchImportMatchmakersToIM() {
        try {
            List<Matchmaker> matchmakers = matchmakerService.list();
            
            int successCount = 0;
            int failCount = 0;
            StringBuilder failedIds = new StringBuilder();
            
            for (Matchmaker matchmaker : matchmakers) {
                String imUserId = "m_" + matchmaker.getMatchmakerId();
                try {
                    // 调用 websocket 服务的 IM 导入接口
                    Map<String, String> imParams = new HashMap<>();
                    imParams.put("userId", imUserId);
                    imParams.put("nickname", matchmaker.getRealName());
                    if (matchmaker.getAvatarUrl() != null && !matchmaker.getAvatarUrl().isEmpty()) {
                        imParams.put("faceUrl", matchmaker.getAvatarUrl());
                    }
                    
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, String>> request = new HttpEntity<>(imParams, headers);
                    
                    restTemplate.postForObject(IM_SERVICE_URL + "/importUser", request, Map.class);
                    successCount++;
                    System.out.println("✅ 导入成功: matchmakerId=" + matchmaker.getMatchmakerId() + ", imUserId=" + imUserId);
                    
                    // 避免请求过快
                    Thread.sleep(100);
                } catch (Exception e) {
                    failCount++;
                    failedIds.append(matchmaker.getMatchmakerId()).append(",");
                    System.err.println("❌ 导入失败: matchmakerId=" + matchmaker.getMatchmakerId() + ", error=" + e.getMessage());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", matchmakers.size());
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            if (failCount > 0) {
                result.put("failedIds", failedIds.toString());
            }
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量导入失败：" + e.getMessage());
        }
    }
}

