package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.MyResource;
import com.zhentao.entity.User;
import com.zhentao.mapper.UserMapper;
import com.zhentao.service.MyResourceService;
import com.zhentao.service.MatchmakerService;
import com.zhentao.entity.Matchmaker;
import com.zhentao.vo.MyResourceVO;
import com.zhentao.vo.ClientDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 我的资源控制器
 */
@RestController
@RequestMapping("/api/my-resource")
public class MyResourceController {
    
    @Autowired
    private MyResourceService myResourceService;
    
    @Autowired
    private com.zhentao.service.UserFollowUpService userFollowUpService;
    
    @Autowired
    private com.zhentao.service.FollowUpStatisticsService followUpStatisticsService;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MatchmakerService matchmakerService;

    /**
     * 添加资源信息
     * 
     * @param requestBody 请求体，包含资源信息和标签ID列表
     * @param currentUserId 当前登录用户的用户ID（将作为红娘ID）
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result<java.util.Map<String, Object>> addResource(
            @RequestBody java.util.Map<String, Object> requestBody,
            @RequestParam(required = false) Integer currentUserId) {
        try {
            // 从请求体中提取资源信息和标签ID列表
            MyResource myResource = new MyResource();
            
            // 使用ObjectMapper转换资源信息
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            try {
                // 先创建一个Map，排除tagIds、resourceId、resource_id字段（确保使用数据库自增）
                java.util.Map<String, Object> resourceMap = new java.util.HashMap<>(requestBody);
                resourceMap.remove("tagIds");
                resourceMap.remove("resourceId");  // 移除 resourceId，确保使用数据库自增
                resourceMap.remove("resource_id"); // 移除 resource_id，确保使用数据库自增
                myResource = objectMapper.convertValue(resourceMap, MyResource.class);
                // 显式清除 resourceId，确保使用数据库自增机制
                myResource.setResourceId(null);
            } catch (Exception e) {
                System.err.println("转换资源信息失败，使用手动设置: " + e.getMessage());
                // 如果转换失败，手动设置字段
                if (requestBody.containsKey("name")) myResource.setName((String) requestBody.get("name"));
                if (requestBody.containsKey("age")) myResource.setAge(requestBody.get("age") != null ? Integer.valueOf(requestBody.get("age").toString()) : null);
                if (requestBody.containsKey("gender")) myResource.setGender(requestBody.get("gender") != null ? Integer.valueOf(requestBody.get("gender").toString()) : null);
                if (requestBody.containsKey("constellation")) myResource.setConstellation((String) requestBody.get("constellation"));
                if (requestBody.containsKey("height")) myResource.setHeight(requestBody.get("height") != null ? Integer.valueOf(requestBody.get("height").toString()) : null);
                if (requestBody.containsKey("weight")) myResource.setWeight(requestBody.get("weight") != null ? Integer.valueOf(requestBody.get("weight").toString()) : null);
                if (requestBody.containsKey("marrStatus")) myResource.setMarrStatus(requestBody.get("marrStatus") != null ? Integer.valueOf(requestBody.get("marrStatus").toString()) : null);
                if (requestBody.containsKey("diploma")) myResource.setDiploma((String) requestBody.get("diploma"));
                if (requestBody.containsKey("income")) myResource.setIncome((String) requestBody.get("income"));
                if (requestBody.containsKey("address")) myResource.setAddress((String) requestBody.get("address"));
                if (requestBody.containsKey("domicile")) myResource.setDomicile((String) requestBody.get("domicile"));
                if (requestBody.containsKey("occupation")) myResource.setOccupation((String) requestBody.get("occupation"));
                if (requestBody.containsKey("house")) myResource.setHouse(requestBody.get("house") != null ? Integer.valueOf(requestBody.get("house").toString()) : null);
                if (requestBody.containsKey("car")) myResource.setCar(requestBody.get("car") != null ? Integer.valueOf(requestBody.get("car").toString()) : null);
                if (requestBody.containsKey("phone")) myResource.setPhone((String) requestBody.get("phone"));
                if (requestBody.containsKey("backupPhone")) myResource.setBackupPhone((String) requestBody.get("backupPhone"));
                if (requestBody.containsKey("mateSelectionCriteria")) myResource.setMateSelectionCriteria((String) requestBody.get("mateSelectionCriteria"));
            }
            
            // 提取标签ID列表
            java.util.List<Integer> tagIds = null;
            if (requestBody.containsKey("tagIds") && requestBody.get("tagIds") != null) {
                Object tagIdsObj = requestBody.get("tagIds");
                if (tagIdsObj instanceof java.util.List) {
                    tagIds = new java.util.ArrayList<>();
                    for (Object item : (java.util.List<?>) tagIdsObj) {
                        if (item != null) {
                            tagIds.add(Integer.valueOf(item.toString()));
                        }
                    }
                }
            }
            
            // 打印接收到的数据，用于调试
            System.out.println("=== 接收到的资源数据 ===");
            System.out.println("resourceId: " + myResource.getResourceId() + " (应该为null，使用数据库自增)");
            System.out.println("姓名: " + myResource.getName());
            System.out.println("手机号: " + myResource.getPhone());
            System.out.println("婚姻状况(marrStatus): " + myResource.getMarrStatus() + " (0-未婚, 1-离异, 2-丧偶)");
            System.out.println("备用手机号(backupPhone): " + myResource.getBackupPhone());
            System.out.println("择偶标准(mateSelectionCriteria): " + myResource.getMateSelectionCriteria());
            System.out.println("标签ID列表: " + tagIds);
            
            // 验证手机号是否为空
            if (myResource.getPhone() == null || myResource.getPhone().trim().isEmpty()) {
                return Result.error("手机号不能为空");
            }
            
            // 检查手机号是否已在资源表中存在（检查整个my_resource表，不限制红娘）
            String phone = myResource.getPhone().trim();
            String backupPhone = myResource.getBackupPhone() != null ? myResource.getBackupPhone().trim() : null;

            System.out.println("=== 开始检查手机号重复 ===");
            System.out.println("主手机号: " + phone);
            System.out.println("备用手机号: " + backupPhone);

            // 检查主手机号是否已存在（使用count更可靠）
            QueryWrapper<MyResource> phoneQueryWrapper = new QueryWrapper<>();
            phoneQueryWrapper.eq("phone", phone);
            long phoneCount = myResourceService.count(phoneQueryWrapper);
            System.out.println("主手机号查询结果数量: " + phoneCount);
            if (phoneCount > 0) {
                MyResource existingResourceByPhone = myResourceService.getOne(phoneQueryWrapper);
                System.out.println("找到重复的主手机号，资源名称: " + (existingResourceByPhone != null ? existingResourceByPhone.getName() : "未知"));
                return Result.error("手机号 " + phone + " 已被资源\"" + (existingResourceByPhone != null && existingResourceByPhone.getName() != null ? existingResourceByPhone.getName() : "未知") + "\"使用，不能重复添加");
            }

            // 检查主手机号是否作为其他资源的备用手机号存在
            QueryWrapper<MyResource> phoneAsBackupQueryWrapper = new QueryWrapper<>();
            phoneAsBackupQueryWrapper.eq("backup_phone", phone);
            long phoneAsBackupCount = myResourceService.count(phoneAsBackupQueryWrapper);
            System.out.println("主手机号作为备用手机号查询结果数量: " + phoneAsBackupCount);
            if (phoneAsBackupCount > 0) {
                MyResource existingResourceByPhoneAsBackup = myResourceService.getOne(phoneAsBackupQueryWrapper);
                System.out.println("找到重复的主手机号（作为备用手机号），资源名称: " + (existingResourceByPhoneAsBackup != null ? existingResourceByPhoneAsBackup.getName() : "未知"));
                return Result.error("手机号 " + phone + " 已被资源\"" + (existingResourceByPhoneAsBackup != null && existingResourceByPhoneAsBackup.getName() != null ? existingResourceByPhoneAsBackup.getName() : "未知") + "\"作为备用手机号使用，不能重复添加");
            }

            // 检查备用手机号是否已存在（如果提供了备用手机号）
            if (backupPhone != null && !backupPhone.isEmpty()) {
                // 检查备用手机号是否作为主手机号存在
                QueryWrapper<MyResource> backupPhoneAsMainQueryWrapper = new QueryWrapper<>();
                backupPhoneAsMainQueryWrapper.eq("phone", backupPhone);
                long backupPhoneAsMainCount = myResourceService.count(backupPhoneAsMainQueryWrapper);
                System.out.println("备用手机号作为主手机号查询结果数量: " + backupPhoneAsMainCount);
                if (backupPhoneAsMainCount > 0) {
                    MyResource existingResourceByBackupAsMain = myResourceService.getOne(backupPhoneAsMainQueryWrapper);
                    System.out.println("找到重复的备用手机号（作为主手机号），资源名称: " + (existingResourceByBackupAsMain != null ? existingResourceByBackupAsMain.getName() : "未知"));
                    return Result.error("备用手机号 " + backupPhone + " 已被资源\"" + (existingResourceByBackupAsMain != null && existingResourceByBackupAsMain.getName() != null ? existingResourceByBackupAsMain.getName() : "未知") + "\"作为主手机号使用，不能重复添加");
                }

                // 检查备用手机号是否作为备用手机号存在
                QueryWrapper<MyResource> backupPhoneQueryWrapper = new QueryWrapper<>();
                backupPhoneQueryWrapper.eq("backup_phone", backupPhone);
                long backupPhoneCount = myResourceService.count(backupPhoneQueryWrapper);
                System.out.println("备用手机号查询结果数量: " + backupPhoneCount);
                if (backupPhoneCount > 0) {
                    MyResource existingResourceByBackup = myResourceService.getOne(backupPhoneQueryWrapper);
                    System.out.println("找到重复的备用手机号，资源名称: " + (existingResourceByBackup != null ? existingResourceByBackup.getName() : "未知"));
                    return Result.error("备用手机号 " + backupPhone + " 已被资源\"" + (existingResourceByBackup != null && existingResourceByBackup.getName() != null ? existingResourceByBackup.getName() : "未知") + "\"使用，不能重复添加");
                }
            }

            System.out.println("=== 手机号检查通过，没有重复 ===");

            // 根据手机号查询用户表中是否存在该用户
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("phone", myResource.getPhone());
            User user = userMapper.selectOne(userQueryWrapper);
            
            // 根据用户是否存在，设置is_user和user_id字段
            if (user != null) {
                // 用户存在，设置is_user=1，user_id=user.getUserId()
                myResource.setIsUser(1);
                myResource.setUserId(user.getUserId());
                System.out.println("用户存在，设置is_user=1, user_id=" + user.getUserId());
            } else {
                // 用户不存在，设置is_user=0，user_id=null
                myResource.setIsUser(0);
                myResource.setUserId(null);
                System.out.println("用户不存在，设置is_user=0, user_id=null");
            }
            
            // 确保关键字段被明确设置（即使为null也要设置，确保MyBatis-Plus能够识别）
            // 如果marrStatus为null，确保它被明确设置为null（而不是未设置）
            if (myResource.getMarrStatus() == null) {
                System.out.println("警告：marrStatus为null，但字段会被保存为null");
            }
            // 如果backupPhone为null，确保它被明确设置为null
            if (myResource.getBackupPhone() == null) {
                System.out.println("信息：backupPhone为null，字段会被保存为null");
            }
            // 如果mateSelectionCriteria为null，确保它被明确设置为null
            if (myResource.getMateSelectionCriteria() == null) {
                System.out.println("信息：mateSelectionCriteria为null，字段会被保存为null");
            }
            
            // 如果matchmakerId为空，根据当前登录用户的userId从matchmakers表中查询对应的matchmaker_id
            if (myResource.getMatchmakerId() == null) {
                if (currentUserId != null) {
                    // 根据user_id从matchmakers表中查询对应的红娘信息
                    QueryWrapper<Matchmaker> matchmakerQueryWrapper = new QueryWrapper<>();
                    matchmakerQueryWrapper.eq("user_id", currentUserId);
                    Matchmaker matchmaker = matchmakerService.getOne(matchmakerQueryWrapper);

                    if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
                        // 查询到红娘信息，设置matchmaker_id
                        myResource.setMatchmakerId(matchmaker.getMatchmakerId());
                        System.out.println("根据user_id=" + currentUserId + "查询到matchmaker_id=" + matchmaker.getMatchmakerId());
                    } else {
                        // 未查询到红娘信息，返回错误
                        return Result.error("无法根据当前用户ID查询到对应的红娘信息，请确认该用户是否为红娘");
                    }
                } else {
                    return Result.error("无法获取当前登录用户ID");
                }
            }
            
            // 设置默认审核状态为0（待审核）
            if (myResource.getStatus() == null) {
                myResource.setStatus(0);
                System.out.println("设置默认审核状态: 0 (待审核)");
            }

            // 判断资源类型（根据isUser字段：1是资源，0是线索）
            String resourceType = (myResource.getIsUser() != null && myResource.getIsUser() == 1) ? "资源" : "线索";
            System.out.println("资源类型: " + resourceType + " (isUser=" + myResource.getIsUser() + ")");

            // 保存资源信息和标签关联
            boolean success = myResourceService.addResource(myResource, tagIds);
            if (success) {
                // 构建返回数据，包含资源类型信息
                java.util.Map<String, Object> resultData = new java.util.HashMap<>();
                resultData.put("resource", myResource);
                resultData.put("resourceType", resourceType);
                resultData.put("isUser", myResource.getIsUser());

                String successMessage = "资源信息添加成功";
                if (resourceType.equals("线索")) {
                    successMessage = "线索信息添加成功";
                }

                return Result.success(successMessage, resultData);
            } else {
                return Result.error("资源信息添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("资源信息添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询资源列表（包含用户头像）
     * 
     * @param matchmakerId 红娘ID（可选，如果为空则根据currentUserId从matchmakers表查询）
     * @param currentUserId 当前登录用户的用户ID（如果matchmakerId为空，则根据此值从matchmakers表查询对应的matchmaker_id）
     * @param keyword 搜索关键词（可选）
     * @param isUser 用户注册状态筛选（可选）：1-已注册用户，0-未注册用户（线索），null-全部
     * @param pageNum 页码（默认1）
     * @param pageSize 每页大小（默认10）
     * @return 分页数据（包含头像）
     */
    @GetMapping("/list")
    public Result<Page<MyResourceVO>> getResourceList(
            @RequestParam(value = "matchmakerId", required = false) Integer matchmakerId,
            @RequestParam(value = "currentUserId", required = false) Integer currentUserId,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "isUser", required = false) Integer isUser,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            // 如果matchmakerId为空，根据currentUserId从matchmakers表中查询对应的matchmaker_id
            if (matchmakerId == null) {
                if (currentUserId != null) {
                    // 根据user_id从matchmakers表中查询对应的红娘信息
                    QueryWrapper<Matchmaker> matchmakerQueryWrapper = new QueryWrapper<>();
                    matchmakerQueryWrapper.eq("user_id", currentUserId);
                    Matchmaker matchmaker = matchmakerService.getOne(matchmakerQueryWrapper);
                    
                    if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
                        // 查询到红娘信息，使用查询到的matchmaker_id
                        matchmakerId = matchmaker.getMatchmakerId();
                        System.out.println("根据user_id=" + currentUserId + "查询到matchmaker_id=" + matchmakerId);
                    } else {
                        // 未查询到红娘信息，返回错误
                        return Result.error("无法根据当前用户ID查询到对应的红娘信息，请确认该用户是否为红娘");
                    }
                } else {
                    return Result.error("无法获取当前登录用户ID或红娘ID");
                }
            }
            
            Page<MyResourceVO> page = myResourceService.getResourceListWithAvatar(matchmakerId, keyword, isUser, pageNum, pageSize);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询资源列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询资源详情
     * 
     * @param resourceId 资源ID
     * @return 资源详情
     */
    @GetMapping("/detail/{resourceId}")
    public Result<MyResource> getResourceDetail(@PathVariable Integer resourceId) {
        try {
            MyResource myResource = myResourceService.getById(resourceId);
            if (myResource == null) {
                return Result.error("资源不存在");
            }
            return Result.success(myResource);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询资源详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据资源ID获取客户详情（包含择偶要求）
     * 
     * @param resourceId 资源ID
     * @return 客户详情
     */
    @GetMapping("/client-detail/{resourceId}")
    public Result<ClientDetailVO> getClientDetail(@PathVariable Integer resourceId) {
        try {
            System.out.println("=== 获取客户详情 ===");
            System.out.println("接收到的resourceId: " + resourceId + " (类型: " + resourceId.getClass().getName() + ")");
            
            ClientDetailVO clientDetail = myResourceService.getClientDetail(resourceId);
            if (clientDetail == null) {
                System.out.println("资源不存在，resourceId: " + resourceId);
                return Result.error("资源不存在");
            }
            
            System.out.println("查询成功，返回的resourceId: " + clientDetail.getResourceId());
            System.out.println("姓名: " + clientDetail.getName());
            System.out.println("头像URL: " + clientDetail.getAvatarUrl());
            System.out.println("备用手机号: " + clientDetail.getBackupPhone());
            System.out.println("择偶要求 - 年龄范围: " + clientDetail.getMinAge() + "-" + clientDetail.getMaxAge());
            System.out.println("择偶要求 - 身高: " + clientDetail.getMinHeight() + "cm以上");
            System.out.println("择偶要求 - 其他: " + clientDetail.getOtherRequirements());
            
            return Result.success(clientDetail);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询客户详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新资源信息
     * 
     * @param resourceId 资源ID
     * @param myResource 资源信息
     * @return 更新结果
     */
    @PutMapping("/update/{resourceId}")
    public Result<MyResource> updateResource(
            @PathVariable Integer resourceId,
            @RequestBody java.util.Map<String, Object> requestBody) {
        try {
            // 从请求体中提取资源信息和标签ID列表
            MyResource myResource = new MyResource();
            
            // 使用ObjectMapper转换资源信息
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            try {
                // 先创建一个Map，排除tagIds字段
                java.util.Map<String, Object> resourceMap = new java.util.HashMap<>(requestBody);
                resourceMap.remove("tagIds");
                myResource = objectMapper.convertValue(resourceMap, MyResource.class);
            } catch (Exception e) {
                System.err.println("转换资源信息失败，使用手动设置: " + e.getMessage());
                // 如果转换失败，手动设置字段
                if (requestBody.containsKey("name")) myResource.setName((String) requestBody.get("name"));
                if (requestBody.containsKey("age")) myResource.setAge(requestBody.get("age") != null ? Integer.valueOf(requestBody.get("age").toString()) : null);
                if (requestBody.containsKey("gender")) myResource.setGender(requestBody.get("gender") != null ? Integer.valueOf(requestBody.get("gender").toString()) : null);
                if (requestBody.containsKey("constellation")) myResource.setConstellation((String) requestBody.get("constellation"));
                if (requestBody.containsKey("height")) myResource.setHeight(requestBody.get("height") != null ? Integer.valueOf(requestBody.get("height").toString()) : null);
                if (requestBody.containsKey("weight")) myResource.setWeight(requestBody.get("weight") != null ? Integer.valueOf(requestBody.get("weight").toString()) : null);
                if (requestBody.containsKey("marrStatus")) myResource.setMarrStatus(requestBody.get("marrStatus") != null ? Integer.valueOf(requestBody.get("marrStatus").toString()) : null);
                if (requestBody.containsKey("diploma")) myResource.setDiploma((String) requestBody.get("diploma"));
                if (requestBody.containsKey("income")) myResource.setIncome((String) requestBody.get("income"));
                if (requestBody.containsKey("address")) myResource.setAddress((String) requestBody.get("address"));
                if (requestBody.containsKey("domicile")) myResource.setDomicile((String) requestBody.get("domicile"));
                if (requestBody.containsKey("occupation")) myResource.setOccupation((String) requestBody.get("occupation"));
                if (requestBody.containsKey("house")) myResource.setHouse(requestBody.get("house") != null ? Integer.valueOf(requestBody.get("house").toString()) : null);
                if (requestBody.containsKey("car")) myResource.setCar(requestBody.get("car") != null ? Integer.valueOf(requestBody.get("car").toString()) : null);
                if (requestBody.containsKey("phone")) myResource.setPhone((String) requestBody.get("phone"));
                if (requestBody.containsKey("backupPhone")) myResource.setBackupPhone((String) requestBody.get("backupPhone"));
                if (requestBody.containsKey("mateSelectionCriteria")) myResource.setMateSelectionCriteria((String) requestBody.get("mateSelectionCriteria"));
            }
            
            // 设置资源ID和更新时间
            myResource.setResourceId(resourceId);
            myResource.setUpdateTime(new java.util.Date());
            
            // 提取标签ID列表
            java.util.List<Integer> tagIds = null;
            if (requestBody.containsKey("tagIds") && requestBody.get("tagIds") != null) {
                Object tagIdsObj = requestBody.get("tagIds");
                if (tagIdsObj instanceof java.util.List) {
                    tagIds = new java.util.ArrayList<>();
                    for (Object item : (java.util.List<?>) tagIdsObj) {
                        if (item != null) {
                            tagIds.add(Integer.valueOf(item.toString()));
                        }
                    }
                }
            }
            
            System.out.println("=== 更新资源数据 ===");
            System.out.println("资源ID: " + resourceId);
            System.out.println("标签ID列表: " + tagIds);
            
            // 调用Service方法更新资源（包括标签）
            boolean success = myResourceService.updateResource(myResource, tagIds);
            if (success) {
                return Result.success("资源信息更新成功", myResource);
            } else {
                return Result.error("资源信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("资源信息更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除资源
     * 
     * @param resourceId 资源ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{resourceId}")
    public Result<Void> deleteResource(@PathVariable Integer resourceId) {
        try {
            boolean success = myResourceService.removeById(resourceId);
            if (success) {
                return Result.success("资源删除成功", null);
            } else {
                return Result.error("资源删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("资源删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 精准匹配
     * 根据资源用户的择偶要求，匹配推荐异性用户
     * 
     * @param resourceId 资源ID
     * @return 匹配结果列表（最多3个）
     */
    @GetMapping("/precise-match/{resourceId}")
    public Result<java.util.List<com.zhentao.vo.MatchResultVO>> preciseMatch(@PathVariable Integer resourceId) {
        try {
            System.out.println("=== 精准匹配请求 ===");
            System.out.println("资源ID: " + resourceId);
            
            java.util.List<com.zhentao.vo.MatchResultVO> matchResults = myResourceService.preciseMatch(resourceId);
            
            if (matchResults == null || matchResults.isEmpty()) {
                return Result.success("未找到匹配的用户", new java.util.ArrayList<>());
            }
            
            // 验证返回数据中的 originalPhone 字段
            System.out.println("=== Controller返回数据验证 ===");
            for (int i = 0; i < matchResults.size() && i < 3; i++) {
                com.zhentao.vo.MatchResultVO result = matchResults.get(i);
                System.out.println("匹配结果 " + i + ":");
                System.out.println("  - userId: " + result.getUserId());
                System.out.println("  - nickname: " + result.getNickname());
                System.out.println("  - phone: " + result.getPhone());
                System.out.println("  - originalPhone: " + result.getOriginalPhone());
                System.out.println("  - originalPhone是否为null: " + (result.getOriginalPhone() == null));
                System.out.println("  - originalPhone是否为空字符串: " + (result.getOriginalPhone() != null && result.getOriginalPhone().isEmpty()));
            }
            
            System.out.println("匹配成功，返回 " + matchResults.size() + " 个结果");
            return Result.success(matchResults);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("精准匹配失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新跟进信息（保存到跟进表）
     * 
     * @param resourceId 资源ID
     * @param requestBody 请求体，包含followType、followProgress、isMatch、isInvitation、invitationTime、remark
     * @return 更新结果
     */
    @PutMapping("/update-follow/{resourceId}")
    public Result<Void> updateFollow(
            @PathVariable Integer resourceId,
            @RequestBody java.util.Map<String, Object> requestBody) {
        try {
            System.out.println("=== 保存跟进信息到跟进表 ===");
            System.out.println("资源ID: " + resourceId);
            System.out.println("请求数据: " + requestBody);
            
            // 获取资源信息
            MyResource resource = myResourceService.getById(resourceId);
            if (resource == null) {
                return Result.error("资源不存在");
            }
            
            // 获取当前登录的红娘ID（这里需要从session或token中获取，暂时使用resource的matchmakerId）
            Integer matchmakerId = resource.getMatchmakerId();
            if (matchmakerId == null) {
                // 如果资源没有红娘ID，尝试从请求参数获取
                if (requestBody.containsKey("matchmakerId")) {
                    matchmakerId = Integer.valueOf(requestBody.get("matchmakerId").toString());
                } else {
                    return Result.error("无法获取红娘ID");
                }
            }
            
            // 创建跟进记录
            com.zhentao.entity.UserFollowUp followUp = new com.zhentao.entity.UserFollowUp();
            followUp.setResourceId(resourceId);
            followUp.setUserId(resource.getUserId());
            followUp.setMatchmakerId(matchmakerId);
            
            // 跟进方式（1-电话，2-面谈，3-其他）
            if (requestBody.containsKey("followType")) {
                Object followTypeObj = requestBody.get("followType");
                if (followTypeObj != null) {
                    String followTypeStr = followTypeObj.toString();
                    // 将字符串转换为数字：phone->1, face->2, other->3
                    int followType = 1; // 默认电话
                    if ("face".equals(followTypeStr)) {
                        followType = 2;
                    } else if ("other".equals(followTypeStr)) {
                        followType = 3;
                    } else if (followTypeStr.matches("\\d+")) {
                        followType = Integer.parseInt(followTypeStr);
                    }
                    followUp.setFollowType(followType);
                }
            } else {
                followUp.setFollowType(1); // 默认电话
            }
            
            // 跟进进度（1-已匹配，2-未见面，3-沟通中）
            if (requestBody.containsKey("progress")) {
                Object progressObj = requestBody.get("progress");
                if (progressObj != null) {
                    String progressStr = progressObj.toString();
                    int followProgress = 1; // 默认已匹配
                    if ("notMet".equals(progressStr)) {
                        followProgress = 2;
                    } else if ("communicating".equals(progressStr)) {
                        followProgress = 3;
                    } else if ("matched".equals(progressStr)) {
                        followProgress = 1;
                    } else if (progressStr.matches("\\d+")) {
                        followProgress = Integer.parseInt(progressStr);
                    }
                    followUp.setFollowProgress(followProgress);
                }
            }
            
            // 匹配状态（0-未匹配，1-已匹配）
            if (requestBody.containsKey("matchStatus")) {
                Object matchStatusObj = requestBody.get("matchStatus");
                Integer isMatch = matchStatusObj != null ? Integer.valueOf(matchStatusObj.toString()) : 0;
                followUp.setIsMatch(isMatch);
                System.out.println("设置isMatch: " + isMatch);
            } else {
                followUp.setIsMatch(0); // 默认未匹配
            }
            
            // 邀约状态（0-未邀约，1-已邀约）
            if (requestBody.containsKey("invitationStatus")) {
                Object invitationStatusObj = requestBody.get("invitationStatus");
                Integer isInvitation = invitationStatusObj != null ? Integer.valueOf(invitationStatusObj.toString()) : 0;
                followUp.setIsInvitation(isInvitation);
                System.out.println("设置isInvitation: " + isInvitation);
            } else {
                followUp.setIsInvitation(0); // 默认未邀约
            }
            
            // 邀约时间
            if (requestBody.containsKey("invitationTime") || requestBody.containsKey("inviteDate")) {
                Object invitationTimeObj = requestBody.get("invitationTime");
                if (invitationTimeObj == null) {
                    invitationTimeObj = requestBody.get("inviteDate");
                }
                if (invitationTimeObj != null && !invitationTimeObj.toString().trim().isEmpty()) {
                    try {
                        // 解析日期字符串 (格式: YYYY-MM-DD)
                        String dateStr = invitationTimeObj.toString().trim();
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                        java.util.Date invitationTime = sdf.parse(dateStr);
                        followUp.setInvitationTime(invitationTime);
                        System.out.println("设置invitationTime: " + invitationTime);
                    } catch (Exception e) {
                        System.err.println("解析邀约时间失败: " + e.getMessage());
                        followUp.setInvitationTime(null);
                    }
                } else {
                    followUp.setInvitationTime(null);
                }
            }
            
            // 跟进备注
            if (requestBody.containsKey("remark")) {
                Object remarkObj = requestBody.get("remark");
                if (remarkObj != null) {
                    String remark = remarkObj.toString().trim();
                    // 如果备注不为空，则设置；如果为空字符串，设置为null
                    followUp.setRemark(remark.isEmpty() ? null : remark);
                    System.out.println("设置remark: " + (remark.isEmpty() ? "null" : remark));
                } else {
                    followUp.setRemark(null);
                }
            } else {
                // 如果没有remark字段，设置为null（不更新现有备注）
                // 注意：这里不设置，让Service层处理
            }
            
            // 保存或更新跟进记录
            boolean success = userFollowUpService.saveOrUpdateFollowUp(followUp);
            if (success) {
                System.out.println("✅ 跟进信息保存成功");
                
                // 更新统计数据
                try {
                    followUpStatisticsService.updateStatistics(resourceId, matchmakerId);
                    System.out.println("✅ 统计数据更新成功");
                } catch (Exception e) {
                    System.err.println("⚠️ 统计数据更新失败: " + e.getMessage());
                    e.printStackTrace();
                    // 统计数据更新失败不影响跟进信息保存
                }
                
                return Result.success("跟进信息保存成功", null);
            } else {
                System.out.println("❌ 跟进信息保存失败");
                return Result.error("跟进信息保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存跟进信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取跟进统计数据
     * 
     * @param resourceId 资源ID
     * @return 统计数据
     */
    @GetMapping("/follow-statistics/{resourceId}")
    public Result<com.zhentao.entity.FollowUpStatistics> getFollowStatistics(@PathVariable Integer resourceId) {
        try {
            System.out.println("=== 获取跟进统计数据 ===");
            System.out.println("资源ID: " + resourceId);
            
            // 获取资源信息
            MyResource resource = myResourceService.getById(resourceId);
            if (resource == null) {
                return Result.error("资源不存在");
            }
            
            Integer matchmakerId = resource.getMatchmakerId();
            if (matchmakerId == null) {
                return Result.error("无法获取红娘ID");
            }
            
            // 获取或创建统计数据
            com.zhentao.entity.FollowUpStatistics statistics = 
                followUpStatisticsService.getOrCreateStatistics(resourceId, matchmakerId);
            
            if (statistics == null) {
                return Result.error("统计数据不存在");
            }
            
            System.out.println("=== 返回统计数据 ===");
            System.out.println("statistics_id: " + statistics.getStatisticsId());
            System.out.println("resource_id: " + statistics.getResourceId());
            System.out.println("matchmaker_id: " + statistics.getMatchmakerId());
            System.out.println("follow_count: " + statistics.getFollowCount());
            System.out.println("match_count: " + statistics.getMatchCount());
            System.out.println("phone_count: " + statistics.getPhoneCount());
            System.out.println("interview_count: " + statistics.getInterviewCount());
            System.out.println("完整对象: " + statistics);
            
            return Result.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最新的跟进记录
     * 
     * @param resourceId 资源ID
     * @return 最新的跟进记录
     */
    @GetMapping("/latest-follow/{resourceId}")
    public Result<com.zhentao.entity.UserFollowUp> getLatestFollow(@PathVariable Integer resourceId) {
        try {
            System.out.println("=== 获取最新跟进记录 ===");
            System.out.println("资源ID: " + resourceId);
            
            // 获取资源信息
            MyResource resource = myResourceService.getById(resourceId);
            if (resource == null) {
                return Result.error("资源不存在");
            }
            
            Integer matchmakerId = resource.getMatchmakerId();
            if (matchmakerId == null) {
                return Result.error("无法获取红娘ID");
            }
            
            // 获取最新的跟进记录
            com.zhentao.entity.UserFollowUp followUp = 
                userFollowUpService.getLatestByResourceIdAndMatchmakerId(resourceId, matchmakerId);
            
            if (followUp == null) {
                return Result.success("暂无跟进记录", null);
            }
            
            System.out.println("最新跟进记录: " + followUp);
            return Result.success(followUp);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取最新跟进记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据标签名称分页查询资源列表（包含用户头像）
     * 用于优质资源列表等场景
     * 
     * @param tagName 标签名称（如"优质资源"）
     * @param keyword 搜索关键词（可选）
     * @param pageNum 页码（默认1）
     * @param pageSize 每页大小（默认10）
     * @return 分页数据（包含头像）
     */
    @GetMapping("/list-by-tag")
    public Result<Page<MyResourceVO>> getResourceListByTagName(
            @RequestParam("tagName") String tagName,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "currentUserId", required = false) Integer currentUserId,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            // 如果提供了currentUserId，查询对应的matchmaker_id
            Integer matchmakerId = null;
            if (currentUserId != null) {
                QueryWrapper<Matchmaker> matchmakerQueryWrapper = new QueryWrapper<>();
                matchmakerQueryWrapper.eq("user_id", currentUserId);
                Matchmaker matchmaker = matchmakerService.getOne(matchmakerQueryWrapper);
                
                if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
                    matchmakerId = matchmaker.getMatchmakerId();
                    System.out.println("根据user_id=" + currentUserId + "查询到matchmaker_id=" + matchmakerId);
                }
            }
            
            Page<MyResourceVO> page = myResourceService.getResourceListByTagName(tagName, keyword, matchmakerId, pageNum, pageSize);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询资源列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据资源ID获取标签ID列表
     * 
     * @param resourceId 资源ID
     * @return 标签ID列表
     */
    @GetMapping("/tag-ids/{resourceId}")
    public Result<java.util.List<Integer>> getTagIdsByResourceId(@PathVariable Integer resourceId) {
        try {
            java.util.List<Integer> tagIds = myResourceService.getTagIdsByResourceId(resourceId);
            return Result.success(tagIds);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询标签ID列表失败：" + e.getMessage());
        }
    }

    /**
     * 检查手机号是否已存在（检查整个my_resource表）
     *
     * @param phone 主手机号
     * @param backupPhone 备用手机号（可选）
     * @return 检查结果，如果存在则返回资源信息
     */
    @GetMapping("/check-phone")
    public Result<java.util.Map<String, Object>> checkPhone(
            @RequestParam String phone,
            @RequestParam(required = false) String backupPhone) {
        try {
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("phoneExists", false);
            result.put("backupPhoneExists", false);
            result.put("phoneAsBackupExists", false);
            result.put("backupPhoneAsMainExists", false);
            result.put("existingResource", null);

            String phoneTrimmed = phone != null ? phone.trim() : "";
            String backupPhoneTrimmed = backupPhone != null ? backupPhone.trim() : null;

            System.out.println("=== check-phone 接口调用 ===");
            System.out.println("主手机号: " + phoneTrimmed);
            System.out.println("备用手机号: " + backupPhoneTrimmed);

            // 检查主手机号是否已存在（使用count更可靠）
            QueryWrapper<MyResource> phoneQueryWrapper = new QueryWrapper<>();
            phoneQueryWrapper.eq("phone", phoneTrimmed);
            long phoneCount = myResourceService.count(phoneQueryWrapper);
            System.out.println("主手机号查询结果数量: " + phoneCount);
            if (phoneCount > 0) {
                MyResource existingResourceByPhone = myResourceService.getOne(phoneQueryWrapper);
                result.put("phoneExists", true);
                result.put("existingResource", existingResourceByPhone);
                System.out.println("找到重复的主手机号，资源名称: " + (existingResourceByPhone != null ? existingResourceByPhone.getName() : "未知"));
                return Result.success(result);
            }

            // 检查主手机号是否作为备用手机号存在
            QueryWrapper<MyResource> phoneAsBackupQueryWrapper = new QueryWrapper<>();
            phoneAsBackupQueryWrapper.eq("backup_phone", phoneTrimmed);
            long phoneAsBackupCount = myResourceService.count(phoneAsBackupQueryWrapper);
            System.out.println("主手机号作为备用手机号查询结果数量: " + phoneAsBackupCount);
            if (phoneAsBackupCount > 0) {
                MyResource existingResourceByPhoneAsBackup = myResourceService.getOne(phoneAsBackupQueryWrapper);
                result.put("phoneAsBackupExists", true);
                result.put("existingResource", existingResourceByPhoneAsBackup);
                System.out.println("找到重复的主手机号（作为备用手机号），资源名称: " + (existingResourceByPhoneAsBackup != null ? existingResourceByPhoneAsBackup.getName() : "未知"));
                return Result.success(result);
            }

            // 如果提供了备用手机号，检查备用手机号
            if (backupPhoneTrimmed != null && !backupPhoneTrimmed.isEmpty()) {
                // 检查备用手机号是否作为主手机号存在
                QueryWrapper<MyResource> backupPhoneAsMainQueryWrapper = new QueryWrapper<>();
                backupPhoneAsMainQueryWrapper.eq("phone", backupPhoneTrimmed);
                long backupPhoneAsMainCount = myResourceService.count(backupPhoneAsMainQueryWrapper);
                System.out.println("备用手机号作为主手机号查询结果数量: " + backupPhoneAsMainCount);
                if (backupPhoneAsMainCount > 0) {
                    MyResource existingResourceByBackupAsMain = myResourceService.getOne(backupPhoneAsMainQueryWrapper);
                    result.put("backupPhoneAsMainExists", true);
                    result.put("existingResource", existingResourceByBackupAsMain);
                    System.out.println("找到重复的备用手机号（作为主手机号），资源名称: " + (existingResourceByBackupAsMain != null ? existingResourceByBackupAsMain.getName() : "未知"));
                    return Result.success(result);
                }

                // 检查备用手机号是否作为备用手机号存在
                QueryWrapper<MyResource> backupPhoneQueryWrapper = new QueryWrapper<>();
                backupPhoneQueryWrapper.eq("backup_phone", backupPhoneTrimmed);
                long backupPhoneCount = myResourceService.count(backupPhoneQueryWrapper);
                System.out.println("备用手机号查询结果数量: " + backupPhoneCount);
                if (backupPhoneCount > 0) {
                    MyResource existingResourceByBackup = myResourceService.getOne(backupPhoneQueryWrapper);
                    result.put("backupPhoneExists", true);
                    result.put("existingResource", existingResourceByBackup);
                    System.out.println("找到重复的备用手机号，资源名称: " + (existingResourceByBackup != null ? existingResourceByBackup.getName() : "未知"));
                    return Result.success(result);
                }
            }

            System.out.println("=== check-phone 检查通过，没有重复 ===");
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查手机号失败：" + e.getMessage());
        }
    }

    /**
     * 批量检查并更新线索用户的注册状态
     * 定时刷新线索列表中的所有线索用户，根据线索用户的手机号在users表中检索
     * 如果users表中存在该用户，则更新该线索用户的is_user字段为1和user_id字段
     *
     * @param matchmakerId 红娘ID（可选，如果提供则只检查该红娘的线索）
     * @return 更新结果，包含更新的资源数量
     */
    @PostMapping("/batch-check-clue-registration")
    public Result<java.util.Map<String, Object>> batchCheckAndUpdateClueRegistrationStatus(
            @RequestParam(required = false) Integer matchmakerId) {
        try {
            System.out.println("=== 收到批量检查线索用户注册状态请求 ===");
            if (matchmakerId != null) {
                System.out.println("红娘ID: " + matchmakerId);
            }

            int updateCount = myResourceService.batchCheckAndUpdateClueRegistrationStatus(matchmakerId);

            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("updateCount", updateCount);
            result.put("message", "批量检查完成，共更新 " + updateCount + " 条线索用户记录");

            return Result.success("批量检查完成", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量检查线索用户注册状态失败：" + e.getMessage());
        }
    }

    /**
     * 搜索资源（按姓名或手机号）
     * 用于撮合成功审核页面的下拉搜索
     *
     * @param matchmakerId 红娘ID
     * @param keyword 搜索关键词（姓名或手机号）
     * @param gender 性别筛选（1-男，2-女，可选）
     * @return 匹配的资源列表
     */
    @GetMapping("/search")
    public Result<java.util.List<MyResourceVO>> searchResources(
            @RequestParam Integer matchmakerId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer gender) {
        try {
            System.out.println("=== 搜索资源 ===");
            System.out.println("matchmakerId: " + matchmakerId);
            System.out.println("keyword: " + keyword);
            System.out.println("gender: " + gender);

            java.util.List<MyResourceVO> resources = myResourceService.searchResources(matchmakerId, keyword, gender);

            System.out.println("搜索结果数量: " + resources.size());
            return Result.success(resources);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索资源失败：" + e.getMessage());
        }
    }

    /**
     * 获取资源下拉列表（用于撮合成功审核页面）
     * 返回简化的资源信息：resourceId, name, avatarUrl, gender, phone
     *
     * @param matchmakerId 红娘ID
     * @param gender 性别筛选（1-男，2-女）
     * @return 资源下拉列表
     */
    @GetMapping("/dropdown")
    public Result<java.util.List<java.util.Map<String, Object>>> getResourceDropdown(
            @RequestParam Integer matchmakerId,
            @RequestParam(required = false) Integer gender) {
        try {
            System.out.println("=== 获取资源下拉列表 ===");
            System.out.println("matchmakerId: " + matchmakerId);
            System.out.println("gender: " + gender);

            java.util.List<MyResourceVO> resources = myResourceService.searchResources(matchmakerId, null, gender);

            // 转换为简化的下拉列表格式
            java.util.List<java.util.Map<String, Object>> dropdown = new java.util.ArrayList<>();
            for (MyResourceVO resource : resources) {
                java.util.Map<String, Object> item = new java.util.HashMap<>();
                item.put("resourceId", resource.getResourceId());
                item.put("name", resource.getName());
                item.put("avatarUrl", resource.getAvatarUrl());
                item.put("gender", resource.getGender());
                item.put("phone", resource.getPhone());
                item.put("age", resource.getAge());
                dropdown.add(item);
            }

            System.out.println("下拉列表数量: " + dropdown.size());
            return Result.success(dropdown);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取资源下拉列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取已注册用户的资源下拉列表（用于撮合成功审核页面）
     * 只返回user_id不为空的资源（即已注册为平台用户的资源）
     *
     * @param matchmakerId 红娘ID
     * @param gender 性别筛选（1-男，2-女）
     * @return 已注册用户的资源下拉列表
     */
    @GetMapping("/registered-dropdown")
    public Result<java.util.List<java.util.Map<String, Object>>> getRegisteredResourceDropdown(
            @RequestParam Integer matchmakerId,
            @RequestParam(required = false) Integer gender) {
        try {
            System.out.println("=== 获取已注册用户资源下拉列表 ===");
            System.out.println("matchmakerId: " + matchmakerId);
            System.out.println("gender: " + gender);

            // 查询资源列表
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MyResource> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("matchmaker_id", matchmakerId);
            // 只查询user_id不为空的资源（已注册用户）
            queryWrapper.isNotNull("user_id");

            // 性别筛选
            if (gender != null) {
                queryWrapper.eq("gender", gender);
            }

            // 按创建时间降序
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT 100");

            java.util.List<MyResource> resources = myResourceService.list(queryWrapper);
            System.out.println("查询到已注册资源数量: " + resources.size());

            // 转换为简化的下拉列表格式，并查询用户头像
            java.util.List<java.util.Map<String, Object>> dropdown = new java.util.ArrayList<>();
            for (MyResource resource : resources) {
                java.util.Map<String, Object> item = new java.util.HashMap<>();
                item.put("resourceId", resource.getResourceId());
                item.put("userId", resource.getUserId());
                item.put("name", resource.getName());
                item.put("gender", resource.getGender());
                item.put("phone", resource.getPhone());
                item.put("age", resource.getAge());

                // 查询用户头像
                String avatarUrl = "/static/default-avatar.svg";
                if (resource.getUserId() != null) {
                    com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User> userQuery =
                        new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                    userQuery.eq("user_id", resource.getUserId());
                    User user = userMapper.selectOne(userQuery);
                    if (user != null && user.getAvatarUrl() != null) {
                        avatarUrl = user.getAvatarUrl();
                    }
                }
                item.put("avatarUrl", avatarUrl);

                dropdown.add(item);
            }

            System.out.println("已注册用户下拉列表数量: " + dropdown.size());
            return Result.success(dropdown);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取已注册用户资源下拉列表失败：" + e.getMessage());
        }
    }

    /**
     * 搜索已注册用户的资源（按姓名或手机号）
     * 只返回user_id不为空的资源
     *
     * @param matchmakerId 红娘ID
     * @param keyword 搜索关键词（姓名或手机号）
     * @param gender 性别筛选（1-男，2-女，可选）
     * @return 匹配的已注册用户资源列表
     */
    @GetMapping("/registered-search")
    public Result<java.util.List<java.util.Map<String, Object>>> searchRegisteredResources(
            @RequestParam Integer matchmakerId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer gender) {
        try {
            System.out.println("=== 搜索已注册用户资源 ===");
            System.out.println("matchmakerId: " + matchmakerId);
            System.out.println("keyword: " + keyword);
            System.out.println("gender: " + gender);

            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MyResource> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("matchmaker_id", matchmakerId);
            // 只查询user_id不为空的资源（已注册用户）
            queryWrapper.isNotNull("user_id");

            // 性别筛选
            if (gender != null) {
                queryWrapper.eq("gender", gender);
            }

            // 关键词搜索（姓名或手机号）
            if (keyword != null && !keyword.trim().isEmpty()) {
                String kw = keyword.trim();
                queryWrapper.and(wrapper ->
                    wrapper.like("name", kw)
                           .or()
                           .like("phone", kw)
                );
            }

            // 按创建时间降序
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("LIMIT 100");

            java.util.List<MyResource> resources = myResourceService.list(queryWrapper);
            System.out.println("搜索到已注册资源数量: " + resources.size());

            // 转换为简化的列表格式，并查询用户头像
            java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
            for (MyResource resource : resources) {
                java.util.Map<String, Object> item = new java.util.HashMap<>();
                item.put("resourceId", resource.getResourceId());
                item.put("userId", resource.getUserId());
                item.put("name", resource.getName());
                item.put("gender", resource.getGender());
                item.put("phone", resource.getPhone());
                item.put("age", resource.getAge());

                // 查询用户头像
                String avatarUrl = "/static/default-avatar.svg";
                if (resource.getUserId() != null) {
                    com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User> userQuery =
                        new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
                    userQuery.eq("user_id", resource.getUserId());
                    User user = userMapper.selectOne(userQuery);
                    if (user != null && user.getAvatarUrl() != null) {
                        avatarUrl = user.getAvatarUrl();
                    }
                }
                item.put("avatarUrl", avatarUrl);

                result.add(item);
            }

            System.out.println("搜索结果数量: " + result.size());
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索已注册用户资源失败：" + e.getMessage());
        }
    }
}

