package com.example.demo.repository.impl;

import com.example.demo.model.TaskScheme;
import com.example.demo.model.enums.SchemeStatus;
import com.example.demo.repository.SchemeRepository;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 任务方案仓储内存实现。
 * <p>
 * 使用 ConcurrentHashMap 模拟数据库存储，应用启动时初始化示例方案数据。
 * 后续可替换为 MyBatis/JPA 等数据库实现。
 * </p>
 *
 * @requirement(name="集中式/分布式方案列表展示", id="SRS-TMS-01")
 * 以表格或卡片形式展示所有可用任务方案，支持分页加载。
 */
@Repository
public class InMemorySchemeRepository implements SchemeRepository {

    private final ConcurrentHashMap<String, TaskScheme> store = new ConcurrentHashMap<>();
    private final AtomicLong idCounter = new AtomicLong(0);

    public InMemorySchemeRepository() {
        initSampleData();
    }

    private void initSampleData() {
        LocalDateTime now = LocalDateTime.now();

        TaskScheme s1 = new TaskScheme("SCH-001", "联合打击方案-A", "集中式",
                SchemeStatus.EXECUTING, 8, 120, 0.15, 0.92);
        s1.setEventId("EVT-001");
        s1.setDraftId("DRF-001");
        s1.setDeploymentDetail("{\"air\":\"歼-20 4架\",\"ground\":\"火箭炮 2个连\",\"naval\":\"驱逐舰 1艘\"}");
        s1.setRouteDetail("[{\"phase\":\"集结\",\"coord\":\"A(30.5,120.3)\"},{\"phase\":\"突击\",\"coord\":\"B(31.2,121.5)\"}]");
        s1.setTimelineDetail("{\"T+0\":\"集结\",\"T+30min\":\"突击\",\"T+60min\":\"评估\"}");
        s1.setAlgorithmTrace("路径规划采用A*算法优化，约束满足率98.5%，冲突消解2次");
        s1.setExecutionProgress(45);
        s1.setSubTaskStatus("[{\"name\":\"空中侦察\",\"progress\":80,\"status\":\"进行中\"},{\"name\":\"地面打击\",\"progress\":20,\"status\":\"进行中\"}]");
        s1.setCreateTime(now.minusHours(2));
        s1.setUpdateTime(now.minusMinutes(30));
        store.put(s1.getSchemeId(), s1);

        TaskScheme s2 = new TaskScheme("SCH-002", "分布式机动方案-B", "分布式",
                SchemeStatus.PENDING_DISPATCH, 6, 90, 0.22, 0.85);
        s2.setEventId("EVT-002");
        s2.setDeploymentDetail("{\"air\":\"无人机 6架\",\"ground\":\"特种作战分队 1个\"}");
        s2.setRouteDetail("[{\"phase\":\"渗透\",\"coord\":\"C(121.0,30.8)\"},{\"phase\":\"打击\",\"coord\":\"D(121.5,31.2)\"}]");
        s2.setTimelineDetail("{\"T+0\":\"渗透\",\"T+45min\":\"打击\",\"T+80min\":\"撤离\"}");
        s2.setAlgorithmTrace("分布式优化采用遗传算法，种群规模500，迭代100次");
        s2.setExecutionProgress(0);
        s2.setCreateTime(now.minusHours(1));
        s2.setUpdateTime(now.minusMinutes(10));
        store.put(s2.getSchemeId(), s2);

        TaskScheme s3 = new TaskScheme("SCH-003", "区域防御方案-C", "集中式",
                SchemeStatus.COMPLETED, 5, 180, 0.08, 0.96);
        s3.setEventId("EVT-003");
        s3.setDeploymentDetail("{\"air\":\"防空导弹 4个营\",\"ground\":\"雷达站 3座\"}");
        s3.setRouteDetail("[]");
        s3.setTimelineDetail("{\"T+0\":\"部署\",\"T+60min\":\"警戒\",\"T+180min\":\"撤防\"}");
        s3.setAlgorithmTrace("区域防御覆盖优化，最大覆盖半径300km，重叠率<5%");
        s3.setExecutionProgress(100);
        s3.setSubTaskStatus("[{\"name\":\"防空部署\",\"progress\":100,\"status\":\"已完成\"}]");
        s3.setCreateTime(now.minusDays(1));
        s3.setUpdateTime(now.minusHours(5));
        store.put(s3.getSchemeId(), s3);

        TaskScheme s4 = new TaskScheme("SCH-004", "电子战压制方案-D", "分布式",
                SchemeStatus.ABORTED, 7, 60, 0.18, 0.78);
        s4.setEventId("EVT-004");
        s4.setDeploymentDetail("{\"electronic\":\"电子战飞机 2架\",\"ground\":\"干扰站 2个\"}");
        s4.setRouteDetail("[{\"phase\":\"抵近\",\"coord\":\"E(119.5,29.3)\"}]");
        s4.setTimelineDetail("{\"T+0\":\"抵近\",\"T+30min\":\"压制\"}");
        s4.setAlgorithmTrace("电子频谱分配算法，冲突率0%，但目标移动导致方案中止");
        s4.setExecutionProgress(30);
        s4.setSubTaskStatus("[{\"name\":\"电子侦察\",\"progress\":100,\"status\":\"已完成\"},{\"name\":\"干扰压制\",\"progress\":0,\"status\":\"已中止\"}]");
        s4.setCreateTime(now.minusHours(6));
        s4.setUpdateTime(now.minusHours(3));
        store.put(s4.getSchemeId(), s4);
    }

    @Override
    public TaskScheme save(TaskScheme scheme) {
        if (scheme.getSchemeId() == null || scheme.getSchemeId().isEmpty()) {
            String id = "SCH-" + String.format("%03d", idCounter.incrementAndGet());
            scheme.setSchemeId(id);
        }
        scheme.setUpdateTime(LocalDateTime.now());
        if (scheme.getCreateTime() == null) {
            scheme.setCreateTime(LocalDateTime.now());
        }
        store.put(scheme.getSchemeId(), scheme);
        return scheme;
    }

    @Override
    public Optional<TaskScheme> findById(String schemeId) {
        return Optional.ofNullable(store.get(schemeId));
    }

    @Override
    public List<TaskScheme> findAll() {
        return new ArrayList<>(store.values());
    }

    @Override
    public List<TaskScheme> findByStatus(SchemeStatus status) {
        return store.values().stream()
                .filter(s -> s.getStatus() == status)
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskScheme> findByEventId(String eventId) {
        return store.values().stream()
                .filter(s -> eventId.equals(s.getEventId()))
                .collect(Collectors.toList());
    }

    @Override
    public Optional<TaskScheme> updateStatus(String schemeId, SchemeStatus status) {
        return Optional.ofNullable(store.computeIfPresent(schemeId, (id, scheme) -> {
            scheme.setStatus(status);
            scheme.setUpdateTime(LocalDateTime.now());
            return scheme;
        }));
    }

    @Override
    public Optional<TaskScheme> updateProgress(String schemeId, int progress) {
        return Optional.ofNullable(store.computeIfPresent(schemeId, (id, scheme) -> {
            scheme.setExecutionProgress(progress);
            scheme.setUpdateTime(LocalDateTime.now());
            return scheme;
        }));
    }

    @Override
    public void deleteById(String schemeId) {
        store.remove(schemeId);
    }
}
