package com.red.circle.other.app.scheduler;

import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.other.app.service.BdLeaderSalarySettlementService;
import com.red.circle.other.infra.database.mongo.service.team.TeamBillCycleUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * BD Leader 工资结算定时任务.
 * 每月1号0点执行整月结算.
 *
 * @author AI Assistant
 * @since 2025-10-29
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BdLeaderSalarySettlementTask {

    private static final boolean SALARY_SETTLEMENT_PAUSED = true;

    private final BdLeaderSalarySettlementService bdLeaderSalarySettlementService;

    /**
     * 每月1号1点执行上月整月结算.
     */
    @Scheduled(cron = "0 0 1 1 * ?", zone = "Asia/Riyadh")
    @TaskCacheLock(key = "BD_LEADER_SALARY_SETTLEMENT", expireSecond = 86400)
    public void processBdLeaderSalarySettlement() {
        if (SALARY_SETTLEMENT_PAUSED) {
            log.warn("bd_leader_salary_settlement skipped: salary settlement is temporarily paused");
            return;
        }

        long startTime = System.currentTimeMillis();
        log.warn("========== BD Leader工资结算定时任务开始 ==========");

        try {
            // 获取当前日期的账期
            Integer currentBillBelong = TeamBillCycleUtils.getCalcBillBelong();

            // 计算需要结算的账期（往前推一个账期）
            Integer billBelong = calculateSettlementBillBelong(currentBillBelong);
            String billTitle = TeamBillCycleUtils.parseBillBelongToDateRangeStr(billBelong);

            log.warn("结算周期：{} - {}", billBelong, billTitle);

            // 执行 BD Leader 工资结算
            bdLeaderSalarySettlementService.processAllBdLeaderSettlement(billBelong, billTitle);

            log.warn("========== BD Leader工资结算定时任务完成，耗时：{} ms ==========",
                    System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("========== BD Leader工资结算定时任务异常 ==========", e);
        }
    }

    /**
     * 计算需要结算的上月整月账期.
     */
    private Integer calculateSettlementBillBelong(Integer currentBillBelong) {
      return TeamBillCycleUtils.getPreviousMonthlyBillBelong(currentBillBelong);
    }

    /**
     * 测试方法（手动触发）.
     */
    public void processBdLeaderSalarySettlementTest(Integer billBelong) {
        if (SALARY_SETTLEMENT_PAUSED) {
            log.warn("bd_leader_salary_settlement_test skipped: salary settlement is temporarily paused");
            return;
        }

        String billTitle = TeamBillCycleUtils.parseBillBelongToDateRangeStr(billBelong);
        bdLeaderSalarySettlementService.processAllBdLeaderSettlement(billBelong, billTitle);
    }
}
