package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.UserFollowUp;
import com.zhentao.mapper.UserFollowUpMapper;
import com.zhentao.service.UserFollowUpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 用户跟进服务实现类
 */
@Service
public class UserFollowUpServiceImpl extends ServiceImpl<UserFollowUpMapper, UserFollowUp> 
        implements UserFollowUpService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateFollowUp(UserFollowUp followUp) {
        Date now = new Date();
        
        // 每次保存跟进信息都创建新记录，以支持累加统计
        // 这样每次跟进都会留下历史记录，统计时可以累加所有记录
        
        // 处理备注字段：如果为空字符串，设置为null
        if (followUp.getRemark() != null && followUp.getRemark().trim().isEmpty()) {
            followUp.setRemark(null);
        }
        
        // 设置时间
        followUp.setCreateTime(now);
        followUp.setUpdateTime(now);
        
        // 创建新记录（不更新现有记录）
        return this.save(followUp);
    }
    
    @Override
    public UserFollowUp getLatestByResourceIdAndMatchmakerId(Integer resourceId, Integer matchmakerId) {
        QueryWrapper<UserFollowUp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_id", resourceId);
        if (matchmakerId != null) {
            queryWrapper.eq("matchmaker_id", matchmakerId);
        }
        queryWrapper.orderByDesc("update_time");
        queryWrapper.last("LIMIT 1");
        return this.getOne(queryWrapper);
    }
}

