package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.MyResource;
import com.zhentao.entity.MyResourceTag;
import com.zhentao.entity.Tag;
import com.zhentao.service.MyResourceService;
import com.zhentao.service.TagService;
import com.zhentao.mapper.MyResourceMapper;
import com.zhentao.mapper.MyResourceTagMapper;
import com.zhentao.vo.MyResourceVO;
import com.zhentao.vo.ClientDetailVO;
import com.zhentao.mapper.UserMapper;
import com.zhentao.entity.User;
import com.zhentao.pojo.PartnerRequirement;
import com.zhentao.service.PartnerRequirementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.ArrayList;

/**
* @author Administrator
* @description 针对表【my_resource(红娘资源表
)】的数据库操作Service实现
* @createDate 2025-12-08 15:38:21
*/
@Service
public class MyResourceServiceImpl extends ServiceImpl<MyResourceMapper, MyResource>
    implements MyResourceService{
    
    @Autowired
    private MyResourceMapper myResourceMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MyResourceTagMapper myResourceTagMapper;
    
    @Autowired
    private TagService tagService;
    
    @Autowired(required = false)
    private PartnerRequirementService partnerRequirementService;
    
    @Autowired(required = false)
    private com.zhentao.service.UserFollowUpService userFollowUpService;
    
    @Autowired(required = false)
    private com.zhentao.service.PointsManageService pointsManageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addResource(MyResource myResource, List<Integer> tagIds) {
        // 设置创建时间和更新时间
        Date now = new Date();
        myResource.setCreateTime(now);
        myResource.setUpdateTime(now);
        
        // 打印保存前的数据，用于调试
        System.out.println("=== 保存资源数据前 ===");
        System.out.println("婚姻状况(marrStatus): " + myResource.getMarrStatus() + " (0-未婚, 1-离异, 2-丧偶)");
        System.out.println("备用手机号(backupPhone): " + myResource.getBackupPhone());
        System.out.println("择偶标准(mateSelectionCriteria): " + myResource.getMateSelectionCriteria());
        
        // 处理备用手机号：如果为空字符串，设置为null；如果有值，去除首尾空格
        if (myResource.getBackupPhone() != null) {
            String trimmed = myResource.getBackupPhone().trim();
            if (trimmed.isEmpty()) {
                myResource.setBackupPhone(null);
            } else {
                myResource.setBackupPhone(trimmed);
            }
        }
        
        // 处理择偶标准：如果为空字符串，设置为null；如果有值，去除首尾空格
        if (myResource.getMateSelectionCriteria() != null) {
            String trimmed = myResource.getMateSelectionCriteria().trim();
            if (trimmed.isEmpty()) {
                myResource.setMateSelectionCriteria(null);
            } else {
                myResource.setMateSelectionCriteria(trimmed);
            }
        }
        
        // 使用自定义insert方法确保所有字段都被插入（包括null值）
        // 打印插入前的完整对象信息
        System.out.println("=== 准备插入数据库的对象 ===");
        System.out.println("resourceId: " + myResource.getResourceId() + " (应该为null，使用数据库自增)");
        System.out.println("marrStatus: " + myResource.getMarrStatus());
        System.out.println("backupPhone: " + myResource.getBackupPhone());
        System.out.println("mateSelectionCriteria: " + myResource.getMateSelectionCriteria());
        
        // 使用自定义的insertWithNulls方法，它已经正确配置了useGeneratedKeys="true" keyProperty="resourceId"
        // 这样可以确保自增主键被正确处理，同时null值字段也会被插入
        int insertResult = myResourceMapper.insertWithNulls(myResource);
        boolean result = insertResult > 0;
        
        // 打印插入结果
        System.out.println("插入结果: " + insertResult + " (影响行数)");
        
        // 打印保存后的数据
        System.out.println("=== 保存资源数据后 ===");
        System.out.println("保存结果: " + result);
        System.out.println("资源ID: " + myResource.getResourceId());
        System.out.println("婚姻状况(marrStatus): " + myResource.getMarrStatus() + " (0-未婚, 1-离异, 2-丧偶)");
        System.out.println("备用手机号(backupPhone): " + myResource.getBackupPhone());
        System.out.println("择偶标准(mateSelectionCriteria): " + myResource.getMateSelectionCriteria());
        
        // 保存标签关联
        if (result && myResource.getResourceId() != null && tagIds != null && !tagIds.isEmpty()) {
            System.out.println("=== 开始保存标签关联 ===");
            System.out.println("资源ID: " + myResource.getResourceId());
            System.out.println("标签ID列表: " + tagIds);
            
            // 使用上面定义的now变量
            for (Integer tagId : tagIds) {
                if (tagId != null) {
                    MyResourceTag resourceTag = new MyResourceTag();
                    resourceTag.setResourceId(myResource.getResourceId());
                    resourceTag.setTagId(tagId);
                    resourceTag.setCreateTime(now);
                    int tagInsertResult = myResourceTagMapper.insert(resourceTag);
                    System.out.println("保存标签关联 - tagId: " + tagId + ", 结果: " + tagInsertResult);
                }
            }
            System.out.println("=== 标签关联保存完成 ===");
        }
        
        // 资源录入成功后，为红娘添加积分奖励（阶梯奖励）
        // 只有上传线索（未注册用户，isUser=0）才给积分，上传资源（已注册用户，isUser=1）不给积分
        boolean isClue = myResource.getIsUser() == null || myResource.getIsUser() == 0;
        if (result && isClue && myResource.getMatchmakerId() != null && pointsManageService != null) {
            try {
                String resourceName = myResource.getName() != null ? myResource.getName() : "未知";
                
                // 查询红娘当日已上传的线索数量（只统计未注册用户，包括刚录入的这条）
                int todayCount = getTodayClueCount(myResource.getMatchmakerId());
                
                // 计算阶梯积分：基础10分，超3人+2分，超10人+5分
                int basePoints = 10;
                int bonusPoints = 0;
                if (todayCount > 10) {
                    bonusPoints = 5;  // 超过10人，每个额外+5分
                } else if (todayCount > 3) {
                    bonusPoints = 2;  // 超过3人，每个额外+2分
                }
                int totalPoints = basePoints + bonusPoints;
                
                String reason = "上传线索: " + resourceName + " (今日第" + todayCount + "个";
                if (bonusPoints > 0) {
                    reason += "，额外奖励+" + bonusPoints;
                }
                reason += ")";
                
                // 直接添加计算后的积分
                boolean pointsAdded = pointsManageService.addPoints(
                    myResource.getMatchmakerId(), 
                    totalPoints,
                    reason
                );
                if (pointsAdded) {
                    System.out.println("✅ 线索录入积分奖励添加成功，红娘ID: " + myResource.getMatchmakerId() + 
                                      "，今日第" + todayCount + "个线索，获得" + totalPoints + "积分");
                } else {
                    System.out.println("⚠️ 线索录入积分奖励添加失败，红娘ID: " + myResource.getMatchmakerId());
                }
            } catch (Exception e) {
                // 积分添加失败不影响资源录入
                System.err.println("⚠️ 添加积分奖励时发生异常: " + e.getMessage());
                e.printStackTrace();
            }
        } else if (result && !isClue) {
            System.out.println("📝 录入的是已注册用户（资源），不给积分奖励");
        }
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResource(MyResource myResource, List<Integer> tagIds) {
        // 处理备用手机号：如果为空字符串，设置为null；如果有值，去除首尾空格
        if (myResource.getBackupPhone() != null) {
            String trimmed = myResource.getBackupPhone().trim();
            if (trimmed.isEmpty()) {
                myResource.setBackupPhone(null);
            } else {
                myResource.setBackupPhone(trimmed);
            }
        }
        
        // 处理择偶标准：如果为空字符串，设置为null；如果有值，去除首尾空格
        if (myResource.getMateSelectionCriteria() != null) {
            String trimmed = myResource.getMateSelectionCriteria().trim();
            if (trimmed.isEmpty()) {
                myResource.setMateSelectionCriteria(null);
            } else {
                myResource.setMateSelectionCriteria(trimmed);
            }
        }
        
        // 更新资源基本信息
        boolean result = this.updateById(myResource);
        
        System.out.println("=== 更新资源基本信息 ===");
        System.out.println("资源ID: " + myResource.getResourceId());
        System.out.println("更新结果: " + result);
        
        // 更新标签关联
        if (result && myResource.getResourceId() != null) {
            System.out.println("=== 开始更新标签关联 ===");
            System.out.println("资源ID: " + myResource.getResourceId());
            System.out.println("新标签ID列表: " + tagIds);
            
            // 删除旧的标签关联
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MyResourceTag> deleteWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            deleteWrapper.eq("resource_id", myResource.getResourceId());
            int deleteCount = myResourceTagMapper.delete(deleteWrapper);
            System.out.println("删除旧标签关联数量: " + deleteCount);
            
            // 插入新的标签关联
            if (tagIds != null && !tagIds.isEmpty()) {
                Date now = new Date();
                for (Integer tagId : tagIds) {
                    if (tagId != null) {
                        MyResourceTag resourceTag = new MyResourceTag();
                        resourceTag.setResourceId(myResource.getResourceId());
                        resourceTag.setTagId(tagId);
                        resourceTag.setCreateTime(now);
                        int tagInsertResult = myResourceTagMapper.insert(resourceTag);
                        System.out.println("插入标签关联 - tagId: " + tagId + ", 结果: " + tagInsertResult);
                    }
                }
            }
            System.out.println("=== 标签关联更新完成 ===");
        }
        
        return result;
    }
    
    /**
     * 获取红娘当日已上传的线索数量（只统计未注册用户，isUser=0或null）
     * @param matchmakerId 红娘ID
     * @return 当日上传线索数量
     */
    private int getTodayClueCount(Integer matchmakerId) {
        if (matchmakerId == null) {
            return 0;
        }
        
        // 获取今天的开始时间和结束时间
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(java.util.Calendar.HOUR_OF_DAY, 0);
        calendar.set(java.util.Calendar.MINUTE, 0);
        calendar.set(java.util.Calendar.SECOND, 0);
        calendar.set(java.util.Calendar.MILLISECOND, 0);
        Date todayStart = calendar.getTime();
        
        calendar.add(java.util.Calendar.DAY_OF_MONTH, 1);
        Date todayEnd = calendar.getTime();
        
        // 查询当日该红娘上传的线索数量（只统计未注册用户，isUser=0或null）
        QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("matchmaker_id", matchmakerId)
                   .ge("create_time", todayStart)
                   .lt("create_time", todayEnd)
                   .and(wrapper -> wrapper.eq("is_user", 0).or().isNull("is_user"));
        
        long count = this.count(queryWrapper);
        return (int) count;
    }

    @Override
    public Page<MyResource> getResourceList(Integer matchmakerId, String keyword, Integer pageNum, Integer pageSize) {
        Page<MyResource> page = new Page<>(pageNum, pageSize);
        QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
        
        // 如果提供了红娘ID，则按红娘ID查询
        if (matchmakerId != null) {
            queryWrapper.eq("matchmaker_id", matchmakerId);
        }
        
        // 如果提供了搜索关键词，则按名称或手机号模糊查询
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like("name", keyword)
                .or()
                .like("phone", keyword)
            );
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        return this.page(page, queryWrapper);
    }

    @Override
    public List<MyResource> getResourceByPhone(String phone) {
        QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return this.list(queryWrapper);
    }

    @Override
    public Page<MyResourceVO> getResourceListWithAvatar(Integer matchmakerId, String keyword, Integer isUser, Integer pageNum, Integer pageSize) {
        Page<MyResourceVO> page = new Page<>(pageNum, pageSize);
        Page<MyResourceVO> result = myResourceMapper.selectResourceListWithAvatar(page, matchmakerId, keyword, isUser);
        
        // 为每个资源查询标签
        if (result != null && result.getRecords() != null) {
            System.out.println("=== 查询到的资源列表（包含头像） ===");
            System.out.println("isUser筛选条件: " + isUser);
            for (MyResourceVO vo : result.getRecords()) {
                System.out.println("资源ID: " + vo.getResourceId() + 
                                 " (类型: " + (vo.getResourceId() != null ? vo.getResourceId().getClass().getName() : "null") + ")" +
                                 ", 姓名: " + vo.getName() + 
                                 ", 手机号: " + vo.getPhone() + 
                                 ", 头像URL: " + vo.getAvatarUrl() +
                                 ", isUser: " + vo.getIsUser() +
                                 ", userId: " + vo.getUserId());
                
                // 查询该资源的标签
                if (vo.getResourceId() != null) {
                    List<Integer> tagIds = myResourceTagMapper.selectTagIdsByResourceId(vo.getResourceId());
                    if (tagIds != null && !tagIds.isEmpty()) {
                        // 根据标签ID查询标签名称
                        List<String> tagNames = new java.util.ArrayList<>();
                        for (Integer tagId : tagIds) {
                            com.zhentao.entity.Tag tag = tagService.getById(tagId);
                            if (tag != null && tag.getName() != null) {
                                tagNames.add(tag.getName());
                            }
                        }
                        vo.setTags(tagNames);
                        System.out.println("  标签: " + tagNames);
                    }
                }
            }
        }
        
        return result;
    }
    
    @Override
    public Page<MyResourceVO> getResourceListByTagName(String tagName, String keyword, Integer excludeMatchmakerId, Integer pageNum, Integer pageSize) {
        Page<MyResourceVO> page = new Page<>(pageNum, pageSize);
        Page<MyResourceVO> result = myResourceMapper.selectResourceListByTagName(page, tagName, keyword, excludeMatchmakerId);
        
        // 为每个资源查询标签
        if (result != null && result.getRecords() != null) {
            System.out.println("=== 根据标签名称查询到的资源列表（包含头像） ===");
            System.out.println("标签名称: " + tagName);
            System.out.println("查询到的资源数量: " + result.getRecords().size());
            for (MyResourceVO vo : result.getRecords()) {
                System.out.println("资源ID: " + vo.getResourceId() + 
                                 ", 姓名: " + vo.getName() + 
                                 ", 手机号: " + vo.getPhone() + 
                                 ", 头像URL: " + vo.getAvatarUrl() +
                                 ", isUser: " + vo.getIsUser() + 
                                 ", userId: " + vo.getUserId());
                
                // 确保 isUser 字段正确设置（由于SQL已经过滤了 is_user = 1，这里应该都是1）
                if (vo.getIsUser() == null) {
                    System.out.println("⚠️ 警告：资源 isUser 为 null，强制设置为 1");
                    vo.setIsUser(1);
                }
                
                // 查询该资源的标签
                if (vo.getResourceId() != null) {
                    List<Integer> tagIds = myResourceTagMapper.selectTagIdsByResourceId(vo.getResourceId());
                    if (tagIds != null && !tagIds.isEmpty()) {
                        // 根据标签ID查询标签名称
                        List<String> tagNames = new java.util.ArrayList<>();
                        for (Integer tagId : tagIds) {
                            com.zhentao.entity.Tag tag = tagService.getById(tagId);
                            if (tag != null && tag.getName() != null) {
                                tagNames.add(tag.getName());
                            }
                        }
                        vo.setTags(tagNames);
                        System.out.println("  标签: " + tagNames);
                    }
                }
            }
        }
        
        return result;
    }
    
    @Override
    public List<Integer> getTagIdsByResourceId(Integer resourceId) {
        if (resourceId == null) {
            return new java.util.ArrayList<>();
        }
        List<Integer> tagIds = myResourceTagMapper.selectTagIdsByResourceId(resourceId);
        return tagIds != null ? tagIds : new java.util.ArrayList<>();
    }
    
    @Override
    public ClientDetailVO getClientDetail(Integer resourceId) {
        System.out.println("=== MyResourceService.getClientDetail ===");
        System.out.println("查询resourceId: " + resourceId);
        
        // 根据resourceId查询my_resource表
        MyResource myResource = this.getById(resourceId);
        if (myResource == null) {
            System.out.println("未找到资源，resourceId: " + resourceId);
            return null;
        }
        
        System.out.println("找到资源:");
        System.out.println("  resourceId: " + myResource.getResourceId());
        System.out.println("  name: " + myResource.getName());
        System.out.println("  userId: " + myResource.getUserId());
        System.out.println("  backupPhone: " + myResource.getBackupPhone());
        System.out.println("  mateSelectionCriteria: " + myResource.getMateSelectionCriteria());
        
        // 创建ClientDetailVO并填充基本信息
        ClientDetailVO clientDetail = new ClientDetailVO();
        clientDetail.setResourceId(myResource.getResourceId());
        clientDetail.setName(myResource.getName());
        clientDetail.setAge(myResource.getAge());
        clientDetail.setGender(myResource.getGender());
        clientDetail.setConstellation(myResource.getConstellation());
        clientDetail.setHeight(myResource.getHeight());
        clientDetail.setWeight(myResource.getWeight());
        clientDetail.setMarrStatus(myResource.getMarrStatus());
        clientDetail.setDiploma(myResource.getDiploma());
        clientDetail.setIncome(myResource.getIncome());
        clientDetail.setAddress(myResource.getAddress());
        clientDetail.setDomicile(myResource.getDomicile());
        clientDetail.setOccupation(myResource.getOccupation());
        clientDetail.setHouse(myResource.getHouse());
        clientDetail.setPhone(myResource.getPhone());
        clientDetail.setBackupPhone(myResource.getBackupPhone());
        clientDetail.setCar(myResource.getCar());
        // 择偶要求从my_resource表的mate_selection_criteria字段获取
        clientDetail.setMateSelectionCriteria(myResource.getMateSelectionCriteria());
        
        // 从跟进表获取匹配和邀约状态
        if (userFollowUpService != null) {
            com.zhentao.entity.UserFollowUp followUp = userFollowUpService.getLatestByResourceIdAndMatchmakerId(
                    myResource.getResourceId(), myResource.getMatchmakerId());
            if (followUp != null) {
                clientDetail.setIsMatch(followUp.getIsMatch());
                clientDetail.setIsInvitation(followUp.getIsInvitation());
                clientDetail.setInvitationTime(followUp.getInvitationTime());
            } else {
                // 如果没有跟进记录，设置默认值
                clientDetail.setIsMatch(0);
                clientDetail.setIsInvitation(0);
                clientDetail.setInvitationTime(null);
            }
        } else {
            // 如果服务不可用，设置默认值
            clientDetail.setIsMatch(0);
            clientDetail.setIsInvitation(0);
            clientDetail.setInvitationTime(null);
        }
        
        // 查询该资源的标签
        if (myResource.getResourceId() != null) {
            List<Integer> tagIds = myResourceTagMapper.selectTagIdsByResourceId(myResource.getResourceId());
            if (tagIds != null && !tagIds.isEmpty()) {
                List<String> tagNames = new ArrayList<>();
                for (Integer tagId : tagIds) {
                    Tag tag = tagService.getById(tagId);
                    if (tag != null && tag.getName() != null) {
                        tagNames.add(tag.getName());
                    }
                }
                clientDetail.setTags(tagNames);
                System.out.println("  客户标签: " + tagNames);
            }
        }
        
        // 如果user_id不为空，查询用户头像和择偶要求详情
        if (myResource.getUserId() != null) {
            // 查询用户头像
            User user = userMapper.selectById(myResource.getUserId());
            if (user != null && user.getAvatarUrl() != null) {
                clientDetail.setAvatarUrl(user.getAvatarUrl());
                System.out.println("  查询到用户头像: " + user.getAvatarUrl());
            } else {
                System.out.println("  未找到用户或用户头像为空");
            }
            
            // 根据user_id查询partner_requirement表获取择偶要求
            if (partnerRequirementService == null) {
                System.err.println("  ⚠️ PartnerRequirementService未注入，跳过择偶要求查询");
                // 即使服务未注入，也不影响返回其他数据
            } else {
                try {
                    System.out.println("  开始查询择偶要求，userId: " + myResource.getUserId());
                    // 设置查询超时，避免长时间等待
                    PartnerRequirement requirement = partnerRequirementService.getByUserId(myResource.getUserId().longValue());
                    if (requirement != null) {
                        System.out.println("  ✅ 查询到择偶要求:");
                        System.out.println("    minAge: " + requirement.getMinAge());
                        System.out.println("    maxAge: " + requirement.getMaxAge());
                        System.out.println("    minHeight: " + requirement.getMinHeight());
                        System.out.println("    maxHeight: " + requirement.getMaxHeight());
                        System.out.println("    educationLevel: " + requirement.getEducationLevel());
                        System.out.println("    salaryRange: " + requirement.getSalaryRange());
                        System.out.println("    house: " + requirement.getHouse());
                        System.out.println("    car: " + requirement.getCar());
                        System.out.println("    maritalStatus: " + requirement.getMaritalStatus());
                        System.out.println("    preferredCity: " + requirement.getPreferredCity());
                        System.out.println("    otherRequirements: " + requirement.getOtherRequirements());
                        
                        clientDetail.setMinAge(requirement.getMinAge());
                        clientDetail.setMaxAge(requirement.getMaxAge());
                        clientDetail.setMinHeight(requirement.getMinHeight());
                        clientDetail.setMaxHeight(requirement.getMaxHeight());
                        clientDetail.setEducationLevel(requirement.getEducationLevel());
                        clientDetail.setSalaryRange(requirement.getSalaryRange());
                        clientDetail.setHouseRequirement(requirement.getHouse());
                        clientDetail.setCarRequirement(requirement.getCar());
                        clientDetail.setMaritalStatusRequirement(requirement.getMaritalStatus());
                        clientDetail.setPreferredCity(requirement.getPreferredCity());
                        clientDetail.setOtherRequirements(requirement.getOtherRequirements());
                    } else {
                        System.out.println("  ⚠️ 未找到择偶要求记录，userId: " + myResource.getUserId());
                    }
                } catch (Exception e) {
                    System.err.println("  ❌ 查询择偶要求时发生异常: " + e.getMessage());
                    e.printStackTrace();
                    // 即使查询择偶要求失败，也不影响返回其他数据
                }
            }
        } else {
            System.out.println("  userId为空，无法查询用户头像和择偶要求");
        }
        
        return clientDetail;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResourceStatusByPhone(String phone, Integer userId) {
        if (phone == null || phone.trim().isEmpty() || userId == null) {
            System.out.println("⚠️ 更新资源状态失败：手机号或用户ID为空");
            return false;
        }
        
        try {
            // 根据手机号查询资源列表
            QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone.trim());
            List<MyResource> resources = this.list(queryWrapper);
            
            if (resources == null || resources.isEmpty()) {
                System.out.println("未找到匹配的资源记录，手机号: " + phone);
                return false;
            }
            
            // 更新所有匹配的资源记录
            boolean hasUpdate = false;
            for (MyResource resource : resources) {
                // 只更新未注册的资源（is_user = 0）
                if (resource.getIsUser() == null || resource.getIsUser() == 0) {
                    resource.setIsUser(1);
                    resource.setUserId(userId);
                    resource.setUpdateTime(new Date());
                    boolean updated = this.updateById(resource);
                    if (updated) {
                        hasUpdate = true;
                        System.out.println("✅ 更新资源注册状态成功 - 资源ID: " + resource.getResourceId() + 
                                         ", 手机号: " + phone + ", 用户ID: " + userId);
                    } else {
                        System.out.println("⚠️ 更新资源注册状态失败 - 资源ID: " + resource.getResourceId());
                    }
                } else {
                    System.out.println("资源已注册，跳过更新 - 资源ID: " + resource.getResourceId());
                }
            }
            
            return hasUpdate;
        } catch (Exception e) {
            System.err.println("❌ 更新资源注册状态时发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public java.util.List<com.zhentao.vo.MatchResultVO> preciseMatch(Integer resourceId) {
        System.out.println("=== 开始精准匹配 ===");
        System.out.println("资源ID: " + resourceId);
        
        // 1. 获取资源用户信息
        MyResource resource = this.getById(resourceId);
        if (resource == null) {
            System.out.println("资源不存在，resourceId: " + resourceId);
            return new java.util.ArrayList<>();
        }
        
        // 检查用户是否已注册
        if (resource.getIsUser() == null || resource.getIsUser() != 1 || resource.getUserId() == null) {
            System.out.println("资源用户未注册，无法进行匹配");
            throw new RuntimeException("该用户还未注册用户端，注册之后才能进行匹配");
        }
        
        Integer resourceUserId = resource.getUserId();
        Integer resourceGender = resource.getGender(); // 1-男, 2-女
        
        System.out.println("资源用户ID: " + resourceUserId + ", 性别: " + resourceGender);
        
        // 2. 获取择偶要求
        PartnerRequirement requirement = null;
        if (partnerRequirementService != null) {
            requirement = partnerRequirementService.getByUserId(resourceUserId.longValue());
        }
        
        if (requirement == null) {
            System.out.println("未找到择偶要求，使用默认匹配逻辑");
        } else {
            System.out.println("择偶要求: 年龄" + requirement.getMinAge() + "-" + requirement.getMaxAge() + 
                             ", 身高" + requirement.getMinHeight() + "-" + requirement.getMaxHeight() + 
                             ", 学历" + requirement.getEducationLevel());
        }
        
        // 3. 确定目标性别（异性）
        Integer targetGender = (resourceGender == 1) ? 2 : 1; // 1-男找女, 2-女找男
        
        // 4. 查询所有异性用户（确保查询phone字段）
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("gender", targetGender);
        userQuery.eq("status", 1); // 只查询正常状态的用户
        // 不限制查询字段，查询所有字段（包括phone）
        List<User> allUsers = userMapper.selectList(userQuery);
        
        System.out.println("查询到的用户数量: " + allUsers.size());
        if (!allUsers.isEmpty()) {
            System.out.println("第一个用户的phone: " + (allUsers.get(0).getPhone() != null ? allUsers.get(0).getPhone() : "null"));
        }
        
        System.out.println("找到 " + allUsers.size() + " 个异性用户");
        
        if (allUsers.isEmpty()) {
            return new java.util.ArrayList<>();
        }
        
        // 5. 计算每个用户的匹配度
        List<com.zhentao.vo.MatchResultVO> matchResults = new java.util.ArrayList<>();
        
        for (User user : allUsers) {
            // 跳过自己
            if (user.getUserId().equals(resourceUserId)) {
                continue;
            }
            
            com.zhentao.vo.MatchResultVO matchResult = new com.zhentao.vo.MatchResultVO();
            matchResult.setUserId(user.getUserId());
            matchResult.setNickname(user.getNickname());
            matchResult.setGender(user.getGender());
            matchResult.setAvatarUrl(user.getAvatarUrl());
            
            // 查询用户资料（通过SQL）
            // 由于homePage服务可能没有UserProfileMapper，我们通过MyResourceMapper执行SQL查询
            java.util.Map<String, Object> profileMap = myResourceMapper.selectUserProfileByUserId(user.getUserId());
            
            if (profileMap != null) {
                matchResult.setHeight((Integer) profileMap.get("height"));
                Object birthDateObj = profileMap.get("birth_date");
                if (birthDateObj != null) {
                    java.util.Date birthDate = null;
                    if (birthDateObj instanceof java.util.Date) {
                        birthDate = (java.util.Date) birthDateObj;
                    } else if (birthDateObj instanceof java.sql.Date) {
                        birthDate = new java.util.Date(((java.sql.Date) birthDateObj).getTime());
                    } else if (birthDateObj instanceof java.time.LocalDate) {
                        java.time.LocalDate localDate = (java.time.LocalDate) birthDateObj;
                        birthDate = java.sql.Date.valueOf(localDate);
                    }
                    matchResult.setAge(calculateAge(birthDate));
                }
                matchResult.setMaritalStatus((Integer) profileMap.get("marital_status"));
                matchResult.setHouse((Integer) profileMap.get("house"));
                matchResult.setCar((Integer) profileMap.get("car"));
                
                // 学历转换
                Integer educationLevel = (Integer) profileMap.get("education_level");
                matchResult.setDiploma(convertEducationLevel(educationLevel));
                
                // 收入转换
                Integer salaryRange = (Integer) profileMap.get("salary_range");
                matchResult.setIncome(convertSalaryRange(salaryRange));
                
                // 职业
                matchResult.setOccupation((String) profileMap.get("job_title"));
                
                // 住址（从company获取，这里简化处理）
                matchResult.setAddress((String) profileMap.get("company"));
            }
            
            // 查询用户手机号（从users表通过userId查询，脱敏）
            // 如果user对象中的phone为空，通过userId重新查询users表获取完整信息
            String phone = user.getPhone();
            if (phone == null || phone.trim().isEmpty()) {
                // 如果user对象中没有phone，通过userId重新查询users表
                User fullUser = userMapper.selectById(user.getUserId());
                if (fullUser != null && fullUser.getPhone() != null && !fullUser.getPhone().trim().isEmpty()) {
                    phone = fullUser.getPhone();
                    System.out.println("通过userId重新查询获取到手机号: " + (phone != null ? maskPhone(phone) : "null"));
                } else {
                    System.out.println("警告: 用户ID " + user.getUserId() + " 在users表中没有手机号");
                }
            }
            // 设置脱敏手机号（用于显示）
            String maskedPhone = phone != null && !phone.trim().isEmpty() ? maskPhone(phone) : "";
            matchResult.setPhone(maskedPhone);
            
            // 设置完整手机号（用于复制，红娘端有权限查看）
            String originalPhone = phone != null && !phone.trim().isEmpty() ? phone : "";
            matchResult.setOriginalPhone(originalPhone);
            
            System.out.println("用户 " + user.getUserId() + " 手机号设置:");
            System.out.println("  - 脱敏手机号(phone): " + maskedPhone);
            System.out.println("  - 完整手机号(originalPhone): " + (originalPhone != null && !originalPhone.isEmpty() ? originalPhone : "空"));
            System.out.println("  - 完整手机号长度: " + (originalPhone != null ? originalPhone.length() : 0));
            System.out.println("  - MatchResultVO对象originalPhone值: " + matchResult.getOriginalPhone());
            
            // 查询标签
            List<String> tags = new java.util.ArrayList<>();
            // 这里可以查询用户的标签，暂时使用空列表
            matchResult.setTags(tags);
            
            // 计算匹配度
            double matchScore = calculateMatchScore(resource, requirement, matchResult);
            matchResult.setMatchScore(matchScore);
            
            // 查询匹配到的用户的择偶要求（而不是资源用户的择偶要求）
            PartnerRequirement candidateRequirement = null;
            if (partnerRequirementService != null) {
                candidateRequirement = partnerRequirementService.getByUserId(user.getUserId().longValue());
            }
            
            // 择偶要求文本（显示匹配到的用户的要求）
            matchResult.setRequirement(formatRequirement(candidateRequirement));
            
            matchResults.add(matchResult);
        }
        
        // 6. 按匹配度降序排序，取前3个
        matchResults.sort((a, b) -> Double.compare(b.getMatchScore(), a.getMatchScore()));
        
        int limit = Math.min(3, matchResults.size());
        List<com.zhentao.vo.MatchResultVO> topMatches = matchResults.subList(0, limit);
        
        System.out.println("匹配完成，返回 " + topMatches.size() + " 个结果");
        for (com.zhentao.vo.MatchResultVO result : topMatches) {
            System.out.println("用户: " + result.getNickname() + ", 匹配度: " + result.getMatchScore());
        }
        
        return topMatches;
    }
    
    /**
     * 计算匹配度分数
     */
    private double calculateMatchScore(MyResource resource, PartnerRequirement requirement, com.zhentao.vo.MatchResultVO candidate) {
        double totalScore = 0.0;
        int factorCount = 0;
        
        if (requirement == null) {
            // 如果没有择偶要求，返回基础分数
            return 60.0;
        }
        
        // 1. 年龄匹配 (权重: 20%)
        if (requirement.getMinAge() != null && requirement.getMaxAge() != null && candidate.getAge() != null) {
            int age = candidate.getAge();
            if (age >= requirement.getMinAge() && age <= requirement.getMaxAge()) {
                totalScore += 20.0;
            } else {
                // 年龄差距越大，分数越低
                int gap = Math.min(Math.abs(age - requirement.getMinAge()), Math.abs(age - requirement.getMaxAge()));
                totalScore += Math.max(0, 20.0 - gap * 2);
            }
            factorCount++;
        }
        
        // 2. 身高匹配 (权重: 20%)
        if (requirement.getMinHeight() != null && requirement.getMaxHeight() != null && candidate.getHeight() != null) {
            int height = candidate.getHeight();
            if (height >= requirement.getMinHeight() && height <= requirement.getMaxHeight()) {
                totalScore += 20.0;
            } else {
                int gap = Math.min(Math.abs(height - requirement.getMinHeight()), Math.abs(height - requirement.getMaxHeight()));
                totalScore += Math.max(0, 20.0 - gap * 0.5);
            }
            factorCount++;
        }
        
        // 3. 学历匹配 (权重: 15%)
        if (requirement.getEducationLevel() != null && candidate.getDiploma() != null) {
            int requiredLevel = requirement.getEducationLevel();
            int candidateLevel = parseEducationLevel(candidate.getDiploma());
            if (candidateLevel >= requiredLevel) {
                totalScore += 15.0;
            } else {
                totalScore += Math.max(0, 15.0 - (requiredLevel - candidateLevel) * 3);
            }
            factorCount++;
        }
        
        // 4. 收入匹配 (权重: 15%)
        if (requirement.getSalaryRange() != null && candidate.getIncome() != null) {
            int requiredRange = requirement.getSalaryRange();
            int candidateRange = parseSalaryRange(candidate.getIncome());
            if (candidateRange >= requiredRange) {
                totalScore += 15.0;
            } else {
                totalScore += Math.max(0, 15.0 - (requiredRange - candidateRange) * 3);
            }
            factorCount++;
        }
        
        // 5. 房产匹配 (权重: 10%)
        if (requirement.getHouse() != null && requirement.getHouse() != 0 && candidate.getHouse() != null) {
            if (candidate.getHouse() == 1) {
                totalScore += 10.0;
            }
            factorCount++;
        }
        
        // 6. 车辆匹配 (权重: 10%)
        if (requirement.getCar() != null && requirement.getCar() != 0 && candidate.getCar() != null) {
            if (candidate.getCar() == 1) {
                totalScore += 10.0;
            }
            factorCount++;
        }
        
        // 7. 婚姻状况匹配 (权重: 10%)
        if (requirement.getMaritalStatus() != null && requirement.getMaritalStatus() != 0 && candidate.getMaritalStatus() != null) {
            if (candidate.getMaritalStatus().equals(requirement.getMaritalStatus())) {
                totalScore += 10.0;
            }
            factorCount++;
        }
        
        // 如果没有任何匹配因子，返回基础分数
        if (factorCount == 0) {
            return 60.0;
        }
        
        // 归一化到0-100
        double maxScore = 100.0;
        return Math.min(100.0, totalScore);
    }
    
    /**
     * 计算年龄（从出生日期）
     */
    private Integer calculateAge(java.util.Date birthDate) {
        if (birthDate == null) {
            return null;
        }
        java.util.Calendar birth = java.util.Calendar.getInstance();
        birth.setTime(birthDate);
        java.util.Calendar now = java.util.Calendar.getInstance();
        int age = now.get(java.util.Calendar.YEAR) - birth.get(java.util.Calendar.YEAR);
        if (now.get(java.util.Calendar.DAY_OF_YEAR) < birth.get(java.util.Calendar.DAY_OF_YEAR)) {
            age--;
        }
        return age;
    }
    
    /**
     * 转换学历等级为文本
     */
    private String convertEducationLevel(Integer level) {
        if (level == null) return null;
        switch (level) {
            case 1: return "高中";
            case 2: return "专科";
            case 3: return "本科";
            case 4: return "硕士";
            case 5: return "博士";
            default: return "未知";
        }
    }
    
    /**
     * 解析学历文本为等级
     */
    private int parseEducationLevel(String diploma) {
        if (diploma == null) return 0;
        if (diploma.contains("博士")) return 5;
        if (diploma.contains("硕士")) return 4;
        if (diploma.contains("本科")) return 3;
        if (diploma.contains("专科")) return 2;
        if (diploma.contains("高中")) return 1;
        return 0;
    }
    
    /**
     * 转换收入范围为文本
     */
    private String convertSalaryRange(Integer range) {
        if (range == null) return null;
        switch (range) {
            case 1: return "5k以下";
            case 2: return "5-10k";
            case 3: return "10-20k";
            case 4: return "20-50k";
            case 5: return "50k+";
            default: return "未知";
        }
    }
    
    /**
     * 解析收入文本为范围
     */
    private int parseSalaryRange(String income) {
        if (income == null) return 0;
        if (income.contains("50k+") || income.contains("50k以上")) return 5;
        if (income.contains("20-50k") || income.contains("20k")) return 4;
        if (income.contains("10-20k") || income.contains("10k")) return 3;
        if (income.contains("5-10k") || income.contains("5k")) return 2;
        return 1;
    }
    
    /**
     * 手机号脱敏
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.length() < 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    /**
     * 格式化择偶要求文本
     */
    private String formatRequirement(PartnerRequirement requirement) {
        if (requirement == null) {
            return "暂无要求";
        }
        StringBuilder sb = new StringBuilder();
        if (requirement.getMinAge() != null && requirement.getMaxAge() != null) {
            sb.append("年龄").append(requirement.getMinAge()).append("-").append(requirement.getMaxAge()).append("岁 ");
        }
        if (requirement.getMinHeight() != null && requirement.getMaxHeight() != null) {
            sb.append("身高").append(requirement.getMinHeight()).append("-").append(requirement.getMaxHeight()).append("cm ");
        }
        if (requirement.getEducationLevel() != null && requirement.getEducationLevel() != 0) {
            sb.append(convertEducationLevel(requirement.getEducationLevel())).append(" ");
        }
        return sb.length() > 0 ? sb.toString().trim() : "暂无要求";
    }

    @Override
    public List<MyResourceVO> searchResources(Integer matchmakerId, String keyword, Integer gender) {
        System.out.println("=== searchResources 开始 ===");
        System.out.println("matchmakerId: " + matchmakerId + ", keyword: " + keyword + ", gender: " + gender);
        
        // 构建查询条件
        QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("matchmaker_id", matchmakerId);
        
        // 性别筛选
        if (gender != null) {
            queryWrapper.eq("gender", gender);
        }
        
        // 关键词搜索（姓名或手机号）
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> 
                wrapper.like("name", keyword)
                       .or()
                       .like("phone", keyword)
            );
        }
        
        // 按创建时间降序
        queryWrapper.orderByDesc("create_time");
        
        // 限制返回数量，避免数据过多
        queryWrapper.last("LIMIT 100");
        
        List<MyResource> resources = myResourceMapper.selectList(queryWrapper);
        System.out.println("查询到资源数量: " + resources.size());
        
        // 转换为VO并填充头像
        List<MyResourceVO> voList = new ArrayList<>();
        for (MyResource resource : resources) {
            MyResourceVO vo = new MyResourceVO();
            vo.setResourceId(resource.getResourceId());
            vo.setMatchmakerId(resource.getMatchmakerId());
            vo.setName(resource.getName());
            vo.setAge(resource.getAge());
            vo.setGender(resource.getGender());
            vo.setConstellation(resource.getConstellation());
            vo.setHeight(resource.getHeight());
            vo.setWeight(resource.getWeight());
            vo.setMarrStatus(resource.getMarrStatus());
            vo.setDiploma(resource.getDiploma());
            vo.setIncome(resource.getIncome());
            vo.setAddress(resource.getAddress());
            vo.setDomicile(resource.getDomicile());
            vo.setOccupation(resource.getOccupation());
            vo.setHouse(resource.getHouse());
            vo.setPhone(resource.getPhone());
            vo.setBackupPhone(resource.getBackupPhone());
            vo.setCar(resource.getCar());
            vo.setMateSelectionCriteria(resource.getMateSelectionCriteria());
            vo.setCreateTime(resource.getCreateTime());
            vo.setUpdateTime(resource.getUpdateTime());
            vo.setIsUser(resource.getIsUser());
            
            // 查询用户头像
            if (resource.getIsUser() != null && resource.getIsUser() == 1) {
                // 根据手机号查询用户头像
                QueryWrapper<User> userQuery = new QueryWrapper<>();
                userQuery.eq("phone", resource.getPhone());
                User user = userMapper.selectOne(userQuery);
                if (user != null && user.getAvatarUrl() != null) {
                    vo.setAvatarUrl(user.getAvatarUrl());
                } else {
                    vo.setAvatarUrl("/static/default-avatar.svg");
                }
            } else {
                vo.setAvatarUrl("/static/default-avatar.svg");
            }
            
            voList.add(vo);
        }
        
        System.out.println("返回VO数量: " + voList.size());
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchCheckAndUpdateClueRegistrationStatus(Integer matchmakerId) {
        int updateCount = 0;
        try {
            System.out.println("=== 开始批量检查并更新线索用户注册状态 ===");
            if (matchmakerId != null) {
                System.out.println("红娘ID: " + matchmakerId);
            }

            // 查询所有线索用户（is_user=0或null，且user_id为null）
            QueryWrapper<MyResource> queryWrapper = new QueryWrapper<>();
            queryWrapper.and(wrapper -> wrapper
                .eq("is_user", 0)
                .or()
                .isNull("is_user")
            );
            queryWrapper.and(wrapper -> wrapper
                .isNull("user_id")
                .or()
                .eq("user_id", 0)
            );

            // 如果提供了红娘ID，则只检查该红娘的线索
            if (matchmakerId != null) {
                queryWrapper.eq("matchmaker_id", matchmakerId);
            }

            List<MyResource> clueResources = this.list(queryWrapper);

            if (clueResources == null || clueResources.isEmpty()) {
                System.out.println("未找到需要检查的线索用户");
                return 0;
            }

            System.out.println("找到 " + clueResources.size() + " 个线索用户需要检查");

            // 遍历每个线索用户，检查其手机号是否在users表中已注册
            for (MyResource clueResource : clueResources) {
                String phone = clueResource.getPhone();
                String backupPhone = clueResource.getBackupPhone();

                // 检查主手机号
                if (phone != null && !phone.trim().isEmpty()) {
                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                    userQueryWrapper.eq("phone", phone.trim());
                    User user = userMapper.selectOne(userQueryWrapper);

                    if (user != null && user.getUserId() != null) {
                        // 找到匹配的用户，更新线索资源
                        clueResource.setIsUser(1);
                        clueResource.setUserId(user.getUserId());
                        clueResource.setUpdateTime(new Date());
                        boolean updated = this.updateById(clueResource);
                        if (updated) {
                            updateCount++;
                            System.out.println("✅ 更新线索用户注册状态成功 - 资源ID: " + clueResource.getResourceId() +
                                             ", 手机号: " + phone + ", 用户ID: " + user.getUserId());
                        } else {
                            System.out.println("⚠️ 更新线索用户注册状态失败 - 资源ID: " + clueResource.getResourceId());
                        }
                        continue; // 已更新，跳过备用手机号检查
                    }
                }

                // 如果主手机号未找到匹配，检查备用手机号
                if (backupPhone != null && !backupPhone.trim().isEmpty()) {
                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                    userQueryWrapper.eq("phone", backupPhone.trim());
                    User user = userMapper.selectOne(userQueryWrapper);

                    if (user != null && user.getUserId() != null) {
                        // 找到匹配的用户，更新线索资源
                        clueResource.setIsUser(1);
                        clueResource.setUserId(user.getUserId());
                        clueResource.setUpdateTime(new Date());
                        boolean updated = this.updateById(clueResource);
                        if (updated) {
                            updateCount++;
                            System.out.println("✅ 更新线索用户注册状态成功（通过备用手机号） - 资源ID: " + clueResource.getResourceId() +
                                             ", 备用手机号: " + backupPhone + ", 用户ID: " + user.getUserId());
                        } else {
                            System.out.println("⚠️ 更新线索用户注册状态失败 - 资源ID: " + clueResource.getResourceId());
                        }
                    }
                }
            }

            System.out.println("=== 批量检查并更新线索用户注册状态完成，共更新 " + updateCount + " 条记录 ===");
            return updateCount;
        } catch (Exception e) {
            System.err.println("❌ 批量检查并更新线索用户注册状态时发生异常: " + e.getMessage());
            e.printStackTrace();
            return updateCount;
        }
    }
}




