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.FollowUpStatistics;
import com.zhentao.entity.UserFollowUp;
import com.zhentao.mapper.FollowUpStatisticsMapper;
import com.zhentao.mapper.UserFollowUpMapper;
import com.zhentao.service.FollowUpStatisticsService;
import com.zhentao.service.MyResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 跟进统计服务实现类
 */
@Service
public class FollowUpStatisticsServiceImpl extends ServiceImpl<FollowUpStatisticsMapper, FollowUpStatistics> 
        implements FollowUpStatisticsService {
    
    @Autowired
    private UserFollowUpMapper userFollowUpMapper;
    
    @Autowired
    private MyResourceService myResourceService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FollowUpStatistics getOrCreateStatistics(Integer resourceId, Integer matchmakerId) {
        // 查询是否已存在统计数据
        QueryWrapper<FollowUpStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_id", resourceId);
        queryWrapper.eq("matchmaker_id", matchmakerId);
        FollowUpStatistics statistics = this.getOne(queryWrapper);
        
        if (statistics == null) {
            // 创建新的统计数据
            statistics = new FollowUpStatistics();
            statistics.setResourceId(resourceId);
            statistics.setMatchmakerId(matchmakerId);
            
            // 查询资源信息获取user_id
            com.zhentao.entity.MyResource resource = myResourceService.getById(resourceId);
            if (resource != null && resource.getUserId() != null) {
                statistics.setUserId(resource.getUserId());
            }
            
            Date now = new Date();
            statistics.setCreateTime(now);
            statistics.setUpdateTime(now);
            
            // 初始化统计数据
            statistics.setFollowCount(0);
            statistics.setMatchCount(0);
            statistics.setPhoneCount(0);
            statistics.setInterviewCount(0);
            
            this.save(statistics);
        }
        
        // 更新统计数据
        updateStatistics(resourceId, matchmakerId);
        
        // 重新查询返回最新数据
        return this.getOne(queryWrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatistics(Integer resourceId, Integer matchmakerId) {
        // 查询该资源的所有跟进记录
        QueryWrapper<UserFollowUp> followUpQuery = new QueryWrapper<>();
        followUpQuery.eq("resource_id", resourceId);
        followUpQuery.eq("matchmaker_id", matchmakerId);
        List<UserFollowUp> followUpList = userFollowUpMapper.selectList(followUpQuery);
        
        // 统计各项数据
        int followCount = followUpList.size();
        int matchCount = 0;
        int phoneCount = 0;
        int interviewCount = 0;
        
        for (UserFollowUp followUp : followUpList) {
            // 统计匹配对象数（is_match=1）
            if (followUp.getIsMatch() != null && followUp.getIsMatch() == 1) {
                matchCount++;
            }
            
            // 统计电话沟通次数（follow_type=1）
            if (followUp.getFollowType() != null && followUp.getFollowType() == 1) {
                phoneCount++;
            }
            
            // 统计面谈次数（follow_type=2）
            if (followUp.getFollowType() != null && followUp.getFollowType() == 2) {
                interviewCount++;
            }
        }
        
        // 查询或创建统计数据
        QueryWrapper<FollowUpStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_id", resourceId);
        queryWrapper.eq("matchmaker_id", matchmakerId);
        FollowUpStatistics statistics = this.getOne(queryWrapper);
        
        if (statistics == null) {
            // 创建新的统计数据
            statistics = new FollowUpStatistics();
            statistics.setResourceId(resourceId);
            statistics.setMatchmakerId(matchmakerId);
            
            // 查询资源信息获取user_id
            com.zhentao.entity.MyResource resource = myResourceService.getById(resourceId);
            if (resource != null && resource.getUserId() != null) {
                statistics.setUserId(resource.getUserId());
            }
            
            Date now = new Date();
            statistics.setCreateTime(now);
            statistics.setUpdateTime(now);
        }
        
        // 更新统计数据
        statistics.setFollowCount(followCount);
        statistics.setMatchCount(matchCount);
        statistics.setPhoneCount(phoneCount);
        statistics.setInterviewCount(interviewCount);
        statistics.setUpdateTime(new Date());
        
        return this.saveOrUpdate(statistics);
    }
    
    @Override
    public FollowUpStatistics getStatistics(Integer resourceId, Integer matchmakerId) {
        QueryWrapper<FollowUpStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_id", resourceId);
        queryWrapper.eq("matchmaker_id", matchmakerId);
        return this.getOne(queryWrapper);
    }
}

