package com.haha.admin.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.haha.common.enums.DistributorReferralStatus;
import com.haha.entity.DistributorReferral;
import com.haha.service.DistributorConfigService;
import com.haha.service.DistributorReferralService;
import com.haha.service.DistributorReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class DistributorTask {

    private final DistributorReportService reportService;
    private final DistributorReferralService referralService;
    private final DistributorConfigService configService;

    @Scheduled(cron = "0 0 2 1 * ?")
    public void generateMonthlyReport() {
        log.info("[分销定时任务] 开始生成月度报表");
        try {
            String lastMonth = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
            reportService.generateMonthlyReport(lastMonth);
            log.info("[分销定时任务] 月度报表生成完成 - month: {}", lastMonth);
        } catch (Exception e) {
            log.error("[分销定时任务] 月度报表生成失败", e);
        }
    }

    @Scheduled(cron = "0 0 3 * * ?")
    public void expirePendingReferrals() {
        log.info("[分销定时任务] 开始检查过期推荐关系");
        try {
            Integer windowDays = configService.getValidTimeWindowDays();
            if (windowDays == null || windowDays <= 0) {
                log.info("[分销定时任务] 未配置有效时间窗口，跳过过期检查");
                return;
            }
            LocalDateTime expireThreshold = LocalDateTime.now().minusDays(windowDays);
            LambdaQueryWrapper<DistributorReferral> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DistributorReferral::getStatus, DistributorReferralStatus.PENDING.getCode())
                   .le(DistributorReferral::getCreateTime, expireThreshold)
                   .isNotNull(DistributorReferral::getExpireTime)
                   .le(DistributorReferral::getExpireTime, LocalDateTime.now());
            List<DistributorReferral> expiredReferrals = referralService.list(wrapper);
            for (DistributorReferral referral : expiredReferrals) {
                referral.setStatus(DistributorReferralStatus.EXPIRED.getCode());
                referralService.updateById(referral);
            }
            log.info("[分销定时任务] 过期推荐关系处理完成 - count: {}", expiredReferrals.size());
        } catch (Exception e) {
            log.error("[分销定时任务] 过期推荐关系处理失败", e);
        }
    }
}
