package com.fs.task.service;

import com.fs.provider.domain.ServiceGenConfig; // 你的配置实体（自己替换）
import com.fs.provider.service.IServiceGenConfigService; // 配置service（自己替换）
import com.fs.provider.service.IServiceGenConfigRunLogService;
import com.fs.provider.service.IServiceOrderService;
import com.fs.task.domain.ServiceGenResult;
import com.fs.task.utils.RunKeyUtil;
import com.fs.task.utils.ServerIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.*;
import java.util.List;

@Slf4j
@Component("serviceGenQuartzTask")
public class ServiceGenQuartzTask {

    @Resource
    private IServiceGenConfigService serviceGenConfigService;

    @Resource
    private IServiceGenConfigRunLogService runLogService;

    @Resource
    private IServiceOrderService serviceOrderService;

    /**
     * 扫描配置 -> 抢占 -> 生成服务单
     * 注意：无参，给 sys_job 调
     */
    public void scanAndGenerateServiceOrder() {

        // 1) 时间窗口（避免刚好卡点才跑）
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = now.minusMinutes(6); // 你可以改成 5分钟任务就 minusMinutes(6)

        LocalTime startTime = start.toLocalTime();
        LocalTime endTime = now.toLocalTime();
        LocalDate today = now.toLocalDate();

        // 2) 查“命中执行时间窗口”的配置（只筛到“可能需要跑”的）
        List<ServiceGenConfig> dueConfigs = serviceGenConfigService.selectDueConfigs(startTime, endTime, today);
         log.info("[serviceGenQuartzTask] dueConfigs size={}, window={}~{}", dueConfigs.size(), startTime, endTime);

        for (ServiceGenConfig cfg : dueConfigs) {
            String runKey = RunKeyUtil.buildRunKey(cfg.getFrequencyUnit(), today);

            // 3) 抢占：同 config + 同 runKey 只允许跑一次
            boolean claimed = runLogService.claim(cfg.getId(), runKey, cfg.getFrequencyUnit(), ServerIdUtil.serverId());
            if (!claimed) {
                log.info("[serviceGenQuartzTask] skip claimed, cfgId={}, runKey={}", cfg.getId(), runKey);
                continue;
            }

            try {
                // 4) 真正执行业务：按配置找任务，按医生拆单生成
                ServiceGenResult result = serviceOrderService.generateByConfig(cfg);

                // 5) 记成功日志
                runLogService.markSuccess(cfg.getId(), runKey,
                        result.getTaskTotal(),
                        result.getTaskCreated(),
                        result.getOrderCreated(),
                        result.getRemark());

                log.info("[serviceGenQuartzTask] success cfgId={}, runKey={}, taskTotal={}, orderCreated={}",
                        cfg.getId(), runKey, result.getTaskTotal(), result.getOrderCreated());

            } catch (Exception e) {
                log.error("[serviceGenQuartzTask] failed cfgId={}, runKey={}", cfg.getId(), runKey, e);
                runLogService.markFailed(cfg.getId(), runKey, truncate(e.getMessage(), 450));
            }
        }
    }

    private String truncate(String s, int max) {
        if (s == null) return null;
        return s.length() <= max ? s : s.substring(0, max);
    }
}
