package com.seer.teach.pay.app.merchant.job;

import com.seer.teach.pay.entity.PayMerchantRevenueDetailEntity;
import com.seer.teach.pay.service.IPayMerchantAccountService;
import com.seer.teach.pay.service.IPayMerchantRevenueDetailService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商家收益结算定时任务
 * <p>
 * 用于定期结算商家的收益流水，并更新其账户余额
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MerchantRevenueSettlementJob {

    private final IPayMerchantRevenueDetailService merchantRevenueDetailService;

    /**
     * 收益结算截止时间（配置项）
     * 默认为当前时间前1小时
     */
    @Value("${zs.pay.job.revenue-settlement.cutoff-time:1H}")
    private String cutoffTime;

    /**
     * 商家收益结算任务
     *
     * @param param 任务参数
     */
    @XxlJob("merchantRevenueSettlementJob")
    public void executeRevenueSettlement(String param) {
        try {
            log.info("开始执行商家收益结算任务，参数: {}", param);

            // 解析截止时间配置
            LocalDateTime cutoffDateTime = parseCutoffTime(cutoffTime);
            log.info("本次结算截止时间: {}", cutoffDateTime);

            boolean result = merchantRevenueDetailService.settleMerchantRevenue(cutoffDateTime);
            if (result) {
                log.info("商家收益结算任务执行完成");
            } else {
                log.error("商家收益结算任务执行失败");
            }
        } catch (Exception e) {
            log.error("商家收益结算任务执行失败", e);
        }
    }

    /**
     * 解析截止时间配置
     *
     * @param cutoffTimeConfig 配置的时间参数 (如: 1H表示1小时前, 1D表示1天前)
     * @return 截止时间
     */
    private LocalDateTime parseCutoffTime(String cutoffTimeConfig) {
        LocalDateTime now = LocalDateTime.now();
        if (cutoffTimeConfig.endsWith("H")) {
            // 按小时计算
            int hours = Integer.parseInt(cutoffTimeConfig.substring(0, cutoffTimeConfig.length() - 1));
            return now.minusHours(hours);
        } else if (cutoffTimeConfig.endsWith("D")) {
            // 按天计算
            int days = Integer.parseInt(cutoffTimeConfig.substring(0, cutoffTimeConfig.length() - 1));
            return now.minusDays(days);
        } else {
            // 默认按小时处理
            int hours = Integer.parseInt(cutoffTimeConfig.replaceAll("[^0-9]", ""));
            return now.minusHours(hours);
        }
    }
}