package org.springblade.job.processor;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.martial.service.IMartialScheduleArrangeService;
import org.springframework.stereotype.Component;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;
import tech.powerjob.worker.log.OmsLogger;

import java.util.List;

/**
 * 赛程自动编排定时任务处理器
 * <p>
 * 任务说明:
 * 1. 每10分钟执行一次自动编排
 * 2. 查询所有未锁定的赛事(schedule_status != 2)
 * 3. 对每个赛事执行自动编排算法
 * 4. 更新编排状态和最后编排时间
 * <p>
 * 配置方式:
 * 在PowerJob控制台配置定时任务:
 * - 任务名称: 赛程自动编排
 * - 执行类型: BASIC
 * - 处理器: org.springblade.job.processor.ScheduleAutoArrangeProcessor
 * - Cron表达式: 0 * /10 * * * ? (每10分钟执行一次)
 * - 最大实例数: 1 (避免并发)
 *
 * @author BladeX
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class ScheduleAutoArrangeProcessor implements BasicProcessor {

	private final IMartialScheduleArrangeService scheduleArrangeService;

	@Override
	public ProcessResult process(TaskContext context) {
		OmsLogger omsLogger = context.getOmsLogger();
		omsLogger.info("赛程自动编排任务开始执行...");

		try {
			// 1. 查询所有未锁定的赛事
			List<Long> unlockedCompetitions = scheduleArrangeService.getUnlockedCompetitions();

			if (unlockedCompetitions.isEmpty()) {
				omsLogger.info("没有需要编排的赛事");
				return new ProcessResult(true, "没有需要编排的赛事");
			}

			omsLogger.info("找到 {} 个需要编排的赛事: {}", unlockedCompetitions.size(), unlockedCompetitions);

			// 2. 对每个赛事执行自动编排
			int successCount = 0;
			int failCount = 0;
			StringBuilder errorMsg = new StringBuilder();

			for (Long competitionId : unlockedCompetitions) {
				try {
					omsLogger.info("开始编排赛事: {}", competitionId);
					scheduleArrangeService.autoArrange(competitionId);
					successCount++;
					omsLogger.info("赛事 {} 编排成功", competitionId);
				} catch (Exception e) {
					failCount++;
					String error = String.format("赛事 %d 编排失败: %s", competitionId, e.getMessage());
					omsLogger.error(error, e);
					errorMsg.append(error).append("; ");
				}
			}

			// 3. 返回执行结果
			String result = String.format("自动编排任务完成. 成功: %d, 失败: %d. %s",
				successCount, failCount, errorMsg.toString());

			omsLogger.info(result);

			// 如果有失败的,返回部分成功
			if (failCount > 0) {
				return new ProcessResult(true, result);
			}

			return new ProcessResult(true, result);

		} catch (Exception e) {
			String errorMsg = "赛程自动编排任务执行失败: " + e.getMessage();
			omsLogger.error(errorMsg, e);
			log.error(errorMsg, e);
			return new ProcessResult(false, errorMsg);
		}
	}

}
