package com.fs.provider.service.impl;

import com.fs.provider.domain.ServiceGenConfigRunLog;
import com.fs.provider.mapper.ServiceGenConfigRunLogMapper;
import com.fs.provider.service.IServiceGenConfigRunLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 任务生成配置-执行日志（去重/抢占）Service业务层处理
 *
 * @author fs
 * @date 2026-01-28
 */
@Service
public class ServiceGenConfigRunLogServiceImpl implements IServiceGenConfigRunLogService {

    @Resource
    private ServiceGenConfigRunLogMapper runLogMapper;

    @Override
    public boolean claim(Long configId, String runKey, Integer frequencyUnit, String serverId) {
        ServiceGenConfigRunLog log = new ServiceGenConfigRunLog();
        log.setConfigId(configId);
        log.setRunKey(runKey);
        log.setFrequencyUnit(frequencyUnit);
        log.setStatus(0); // RUNNING
        log.setStartedAt(LocalDateTime.now());
        log.setServerId(serverId);

        // 插入成功=抢占成功；插入失败(唯一键冲突)=已经有人执行过/正在执行
        return runLogMapper.insertIgnoreForClaim(log) > 0;
    }

    @Override
    public void markSuccess(Long configId, String runKey,
                            int taskTotal, int taskCreated, int orderCreated,
                            String remark) {
        ServiceGenConfigRunLog log = new ServiceGenConfigRunLog();
        log.setConfigId(configId);
        log.setRunKey(runKey);
        log.setTaskTotal(taskTotal);
        log.setTaskCreated(taskCreated);
        log.setOrderCreated(orderCreated);
        log.setRemark(trim500(remark));

        runLogMapper.markSuccess(log);
    }

    @Override
    public void markFailed(Long configId, String runKey, String remark) {
        ServiceGenConfigRunLog log = new ServiceGenConfigRunLog();
        log.setConfigId(configId);
        log.setRunKey(runKey);
        log.setRemark(trim500(remark));

        runLogMapper.markFailed(log);
    }

    private String trim500(String s) {
        if (s == null) return null;
        if (s.length() <= 500) return s;
        return s.substring(0, 500);
    }

}
