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

import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.other.app.service.AdminSalarySettlementService;
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;

/**
 * 管理员工资结算定时任务.
 * 每月1号2点执行整月结算（在BD和BD Leader结算之后）.
 *
 * @author AI Assistant
 * @since 2025-12-13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminSalarySettlementTask {

    private static final boolean SALARY_SETTLEMENT_PAUSED = true;

    private final AdminSalarySettlementService adminSalarySettlementService;

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

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

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

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

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

            // 执行管理员工资结算
            adminSalarySettlementService.processAllAdminSettlement(billBelong, billTitle);

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

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

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

        String billTitle = TeamBillCycleUtils.parseBillBelongToDateRangeStr(billBelong);
        adminSalarySettlementService.processAllAdminSettlement(billBelong, billTitle);
    }
}
