package cn.teammodel.test;

import cn.teammodel.callAble.LessonRecordQueryTask;
import cn.teammodel.model.entity.school.LessonRecord;
import cn.teammodel.repository.LessonRecordRepository;
import com.azure.spring.data.cosmos.core.query.CosmosPageRequest;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class LessonRecordQueryService {
    //private static final int SLICE_SIZE = 1000; // 分页大小
    private static final int THREAD_POOL_SIZE = 4; // 线程池大小

    private final LessonRecordRepository repository;
    private final ExecutorService executor;

    public LessonRecordQueryService(LessonRecordRepository repository) {
        this.repository = repository;
        this.executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    public List<LessonRecord> queryLessonsInParallel(String lessonRecordKey,
                                                     Long startTime,
                                                     Long endTime,
                                                     String subjectId,
                                                     String tmdId,
                                                     String grade,
                                                     String periodId) throws InterruptedException, ExecutionException {
        List<Future<List<LessonRecord>>> futures = new ArrayList<>();

        // 按时间范围拆分任务
        long timeRange = endTime - startTime;
        int numTasks = THREAD_POOL_SIZE; // 拆分为与线程池大小相同的任务数

        for (int i = 0; i < numTasks; i++) {
            long chunkStart = startTime + (i * timeRange / numTasks);
            long chunkEnd = (i == numTasks - 1) ? endTime : startTime + ((i + 1) * timeRange / numTasks);

            //CosmosPageRequest pageRequest = new CosmosPageRequest(0, SLICE_SIZE, null);
            LessonRecordQueryTask task = new LessonRecordQueryTask(
                    repository, lessonRecordKey, chunkStart, chunkEnd,
                    subjectId, tmdId, grade, periodId
            );
            futures.add(executor.submit(task));
        }

        // 合并结果
        List<LessonRecord> allRecords = new ArrayList<>();
        for (Future<List<LessonRecord>> future : futures) {
            allRecords.addAll(future.get());
        }

        return allRecords;
    }

    public void shutdown() {
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow(); // 强制关闭未完成的任务
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}
