package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.MatchmakerCheckin;
import com.zhentao.mapper.MatchmakerCheckinMapper;
import com.zhentao.service.MatchmakerCheckinService;
import com.zhentao.service.MatchmakerService;
import com.zhentao.service.PointsManageService;
import com.zhentao.vo.MatchmakerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 红娘签到记录Service实现类
 *
 * @author zhentao
 * @since 2025-12-10
 */
@Service
public class MatchmakerCheckinServiceImpl extends ServiceImpl<MatchmakerCheckinMapper, MatchmakerCheckin> implements MatchmakerCheckinService {

    @Autowired
    private MatchmakerCheckinMapper matchmakerCheckinMapper;

    @Autowired
    private MatchmakerService matchmakerService;

    @Autowired
    private PointsManageService pointsManageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkin(Long userId) {
        // 1. 根据 userId 查询 matchmaker 信息
        MatchmakerVO matchmaker = matchmakerService.getMatchmakerByUserId(userId);
        if (matchmaker == null) {
            System.err.println("红娘不存在: userId=" + userId);
            return false;
        }
        Integer matchmakerId = matchmaker.getMatchmakerId();
        
        // 2. 检查是否已经签到
        LocalDate today = LocalDate.now();
        MatchmakerCheckin existingCheckin = matchmakerCheckinMapper.selectByMakerIdAndDate(matchmakerId.longValue(), today);
        if (existingCheckin != null) {
            return false; // 已经签到
        }

        // 3. 计算连续签到天数
        Integer continuousDays = 1; // 默认连续1天
        Integer totalDays = 1; // 默认累计1天

        // 查询最近一次签到记录
        MatchmakerCheckin lastCheckin = matchmakerCheckinMapper.selectLastByMakerId(matchmakerId.longValue());
        if (lastCheckin != null) {
            // 计算与上次签到的间隔天数
            LocalDate lastDate = lastCheckin.getCheckinDate();
            long daysBetween = ChronoUnit.DAYS.between(lastDate, today);
            
            // 如果是连续签到（间隔1天）
            if (daysBetween == 1) {
                continuousDays = lastCheckin.getContinuousDays() + 1;
            } else if (daysBetween > 1) {
                // 中断连续签到，重置为1天
                continuousDays = 1;
            }

            // 计算累计签到天数
            Integer currentTotal = matchmakerCheckinMapper.selectTotalDaysByMakerId(matchmakerId.longValue());
            if (currentTotal != null) {
                totalDays = currentTotal + 1;
            }
        }

        // 4. 保存签到记录
        MatchmakerCheckin newCheckin = new MatchmakerCheckin();
        newCheckin.setMakerId(matchmakerId.longValue());
        newCheckin.setCheckinDate(today);
        newCheckin.setContinuousDays(continuousDays);
        newCheckin.setTotalDays(totalDays);
        boolean saveResult = save(newCheckin);

        if (saveResult) {
            // 5. 调用积分服务添加积分（使用签到规则）
            pointsManageService.addPointsByRuleName(matchmakerId, "每日签到", today.toString());
        }

        return saveResult;
    }

    @Override
    public boolean isCheckedIn(Long idParam) {
        // idParam 可能是 userId 或 matchmakerId，需要兼容处理
        LocalDate today = LocalDate.now();
        
        // 先尝试直接用 idParam 作为 matchmakerId 查询
        MatchmakerCheckin checkin = matchmakerCheckinMapper.selectByMakerIdAndDate(idParam, today);
        if (checkin != null) {
            return true;
        }
        
        // 如果没找到，尝试把 idParam 当作 userId 来查询 matchmaker
        MatchmakerVO matchmaker = matchmakerService.getMatchmakerByUserId(idParam);
        if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
            Long matchmakerId = matchmaker.getMatchmakerId().longValue();
            checkin = matchmakerCheckinMapper.selectByMakerIdAndDate(matchmakerId, today);
            return checkin != null;
        }
        
        return false;
    }

    @Override
    public Integer getTotalDays(Long idParam) {
        // idParam 可能是 userId 或 matchmakerId，需要兼容处理
        Long matchmakerId = idParam;
        
        // 先尝试直接用 idParam 作为 matchmakerId 查询
        Integer totalDays = matchmakerCheckinMapper.selectTotalDaysByMakerId(idParam);
        if (totalDays != null && totalDays > 0) {
            return totalDays;
        }
        
        // 如果没找到，尝试把 idParam 当作 userId 来查询 matchmaker
        MatchmakerVO matchmaker = matchmakerService.getMatchmakerByUserId(idParam);
        if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
            matchmakerId = matchmaker.getMatchmakerId().longValue();
            totalDays = matchmakerCheckinMapper.selectTotalDaysByMakerId(matchmakerId);
            return totalDays != null ? totalDays : 0;
        }
        
        return 0;
    }

    @Override
    public Integer getContinuousDays(Long idParam) {
        // idParam 可能是 userId 或 matchmakerId，需要兼容处理
        Long matchmakerId = idParam;
        
        // 先尝试直接用 idParam 作为 matchmakerId 查询
        MatchmakerCheckin lastCheckin = matchmakerCheckinMapper.selectLastByMakerId(idParam);
        if (lastCheckin != null) {
            LocalDate today = LocalDate.now();
            LocalDate lastDate = lastCheckin.getCheckinDate();
            long daysBetween = ChronoUnit.DAYS.between(lastDate, today);
            if (daysBetween <= 1) {
                return lastCheckin.getContinuousDays();
            }
        }
        
        // 如果没找到，尝试把 idParam 当作 userId 来查询 matchmaker
        MatchmakerVO matchmaker = matchmakerService.getMatchmakerByUserId(idParam);
        if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
            matchmakerId = matchmaker.getMatchmakerId().longValue();
            lastCheckin = matchmakerCheckinMapper.selectLastByMakerId(matchmakerId);
            if (lastCheckin != null) {
                LocalDate today = LocalDate.now();
                LocalDate lastDate = lastCheckin.getCheckinDate();
                long daysBetween = ChronoUnit.DAYS.between(lastDate, today);
                if (daysBetween <= 1) {
                    return lastCheckin.getContinuousDays();
                }
            }
        }
        
        return 0;
    }

    @Override
    public List<String> getCheckedDates(Long idParam, Integer year, Integer month) {
        // idParam 可能是 userId 或 matchmakerId，需要兼容处理
        Long matchmakerId = idParam;
        
        // 先尝试直接用 idParam 作为 matchmakerId 查询
        List<String> checkedDates = matchmakerCheckinMapper.selectCheckedDatesByMakerIdAndMonth(idParam, year, month);
        if (checkedDates != null && !checkedDates.isEmpty()) {
            return checkedDates;
        }
        
        // 如果没找到，尝试把 idParam 当作 userId 来查询 matchmaker
        MatchmakerVO matchmaker = matchmakerService.getMatchmakerByUserId(idParam);
        if (matchmaker != null && matchmaker.getMatchmakerId() != null) {
            matchmakerId = matchmaker.getMatchmakerId().longValue();
            checkedDates = matchmakerCheckinMapper.selectCheckedDatesByMakerIdAndMonth(matchmakerId, year, month);
            return checkedDates != null ? checkedDates : new ArrayList<>();
        }
        
        return new ArrayList<>();
    }
}