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

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

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

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

    private final BdSalarySettlementService bdSalarySettlementService;

    /**
     * 每月1号和16号 1点执行半月结算.
     */
    @Scheduled(cron = "0 30 0 1,16 * ?", zone = "Asia/Riyadh")
    @TaskCacheLock(key = "BD_SALARY_SETTLEMENT", expireSecond = 86400)
    public void processBdSalarySettlement() {
        long startTime = System.currentTimeMillis();
        log.warn("========== BD工资结算定时任务开始 ==========");

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

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

          log.warn("当前账期：{}，结算账期：{} - {}", currentBillBelong, billBelong, billTitle);

            // 执行 BD 工资结算
            bdSalarySettlementService.processAllBdSettlement(billBelong, billTitle);

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

    /**
     * 计算需要结算的账期
     * 规则：
     * - 如果当前账期是本月1号（如20250101），则结算上个月16号的账期（如20241216）
     * - 如果当前账期是本月16号（如20250116），则结算本月1号的账期（如20250101）
     */
    private Integer calculateSettlementBillBelong(Integer currentBillBelong) {
      String billStr = String.valueOf(currentBillBelong);
      int year = Integer.parseInt(billStr.substring(0, 4));
      int month = Integer.parseInt(billStr.substring(4, 6));
      int day = Integer.parseInt(billStr.substring(6, 8));

      LocalDate settlementDate;

      if (day == 1) {
        // 当前是本月1号，结算上个月16号
        settlementDate = LocalDate.of(year, month, 1).minusMonths(1).withDayOfMonth(16);
      } else {
        // 当前是本月16号，结算本月1号
        settlementDate = LocalDate.of(year, month, 1);
      }

      return Integer.parseInt(settlementDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
    }

    /**
     * 测试方法（手动触发）.
     */
    public void processBdSalarySettlementTest(Integer billBelong) {
        String billTitle = TeamBillCycleUtils.parseBillBelongToDateRangeStr(billBelong);
        bdSalarySettlementService.processAllBdSettlement(billBelong, billTitle);
    }
}
