package com.lingyue.parse.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyue.parse.entity.ParseTask;
import com.lingyue.parse.repository.ParseTaskRepository;
import com.lingyue.parse.vo.ParseTaskCenterVO;
import com.lingyue.parse.vo.ParseTaskStageVO;
import com.lingyue.parse.vo.ParseTaskStatisticsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析任务中心 Service
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ParseTaskCenterService {

    private final ParseTaskRepository parseTaskRepository;

    /**
     * 创建任务记录（让用户立即在任务中心看到）
     * 
     * @param documentId 文档ID
     * @param documentName 文档名称
     * @return 任务ID
     */
    public String createTask(String documentId, String documentName) {
        // 检查是否已存在
        ParseTask existing = parseTaskRepository.findByDocumentId(documentId);
        if (existing != null) {
            // 如果已存在，重置状态
            existing.setStatus("pending");
            existing.setProgress(0);
            existing.setCurrentStep(null);
            existing.setErrorMessage(null);
            existing.setStartedAt(null);
            existing.setCompletedAt(null);
            existing.setUpdateTime(new java.util.Date());
            parseTaskRepository.updateById(existing);
            return existing.getId();
        }
        
        // 创建新任务
        ParseTask task = new ParseTask();
        task.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
        task.setDocumentId(documentId);
        task.setStatus("pending");
        task.setProgress(0);
        task.setCreateTime(new java.util.Date());
        parseTaskRepository.insert(task);
        
        log.info("创建解析任务记录: taskId={}, documentId={}", task.getId(), documentId);
        return task.getId();
    }

    /**
     * 分页查询任务列表
     */
    public Page<ParseTaskCenterVO> getTaskList(String status, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        LambdaQueryWrapper<ParseTask> wrapper = new LambdaQueryWrapper<>();
        if (status != null && !status.isBlank()) {
            wrapper.eq(ParseTask::getStatus, status);
        }
        wrapper.orderByDesc(ParseTask::getCreateTime);

        Page<ParseTask> page = new Page<>(pageNum, pageSize);
        Page<ParseTask> taskPage = parseTaskRepository.selectPage(page, wrapper);

        Page<ParseTaskCenterVO> result = new Page<>();
        result.setCurrent(taskPage.getCurrent());
        result.setSize(taskPage.getSize());
        result.setTotal(taskPage.getTotal());

        List<ParseTaskCenterVO> voList = new ArrayList<>();
        for (ParseTask task : taskPage.getRecords()) {
            voList.add(toCenterVO(task));
        }
        result.setRecords(voList);
        return result;
    }

    /**
     * 查询任务详情
     */
    public ParseTaskCenterVO getTaskDetail(String taskId) {
        ParseTask task = parseTaskRepository.selectById(taskId);
        if (task == null) {
            return null;
        }
        return toCenterVO(task);
    }

    /**
     * 根据文档ID查询任务详情
     */
    public ParseTaskCenterVO getTaskDetailByDocumentId(String documentId) {
        ParseTask task = parseTaskRepository.findByDocumentId(documentId);
        if (task == null) {
            return null;
        }
        return toCenterVO(task);
    }

    /**
     * 统计信息
     */
    public ParseTaskStatisticsVO getTaskStatistics() {
        ParseTaskStatisticsVO vo = new ParseTaskStatisticsVO();
        vo.setTotal(countByStatus(null));
        vo.setPending(countByStatus("pending"));
        vo.setProcessing(countByStatus("processing"));
        vo.setCompleted(countByStatus("completed"));
        vo.setFailed(countByStatus("failed"));
        return vo;
    }

    private long countByStatus(String status) {
        LambdaQueryWrapper<ParseTask> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.eq(ParseTask::getStatus, status);
        }
        return parseTaskRepository.selectCount(wrapper);
    }

    /**
     * 删除任务（进行中的任务不允许删除）
     */
    public boolean deleteTask(String taskId) {
        ParseTask task = parseTaskRepository.selectById(taskId);
        if (task == null) {
            return false;
        }
        if ("processing".equals(task.getStatus())) {
            throw new IllegalStateException("运行中的任务不允许删除");
        }
        return parseTaskRepository.deleteById(taskId) > 0;
    }

    /**
     * Entity -> VO 映射 + 阶段列表组装
     */
    private ParseTaskCenterVO toCenterVO(ParseTask task) {
        ParseTaskCenterVO vo = new ParseTaskCenterVO();
        vo.setId(task.getId());
        vo.setDocumentId(task.getDocumentId());
        vo.setStatus(task.getStatus());
        vo.setProgress(task.getProgress());
        vo.setCurrentStep(task.getCurrentStep());
        vo.setErrorMessage(task.getErrorMessage());
        vo.setStartedAt(task.getStartedAt());
        vo.setCompletedAt(task.getCompletedAt());
        vo.setCreatedAt(task.getCreateTime());
        vo.setUpdatedAt(task.getUpdateTime());
        vo.setName("ParseTask-" + task.getDocumentId());
        vo.setStages(buildStages(task));
        return vo;
    }

    /**
     * 构建阶段列表：上传、解析、RAG、结构化、NER、图构建
     */
    private List<ParseTaskStageVO> buildStages(ParseTask task) {
        List<ParseTaskStageVO> stages = new ArrayList<>();

        // 1. 文件上传阶段（总是完成）
        ParseTaskStageVO upload = new ParseTaskStageVO();
        upload.setStageName("upload");
        upload.setDisplayName("文件上传");
        upload.setStatus("completed");
        upload.setProgress(100);
        upload.setStartedAt(task.getCreateTime());
        upload.setEndedAt(task.getCreateTime());
        stages.add(upload);

        // 2. 文本解析阶段
        ParseTaskStageVO parse = new ParseTaskStageVO();
        parse.setStageName("parse");
        parse.setDisplayName("文本解析");
        parse.setStartedAt(task.getStartedAt());
        setStageStatus(parse, task.getParseStatus(), task.getParseProgress());
        stages.add(parse);

        // 3. RAG 向量化阶段
        ParseTaskStageVO rag = new ParseTaskStageVO();
        rag.setStageName("rag");
        rag.setDisplayName("RAG向量化");
        setStageStatus(rag, task.getRagStatus(), task.getRagProgress());
        stages.add(rag);

        // 4. 结构化解析阶段
        ParseTaskStageVO structured = new ParseTaskStageVO();
        structured.setStageName("structured");
        structured.setDisplayName("结构化解析");
        setStageStatus(structured, task.getStructuredStatus(), task.getStructuredProgress());
        // 添加结果信息
        if ("completed".equals(task.getStructuredStatus())) {
            StringBuilder result = new StringBuilder();
            if (task.getStructuredElementCount() != null) {
                result.append(task.getStructuredElementCount()).append("个元素");
            }
            if (task.getStructuredImageCount() != null && task.getStructuredImageCount() > 0) {
                result.append(", ").append(task.getStructuredImageCount()).append("张图片");
            }
            if (task.getStructuredTableCount() != null && task.getStructuredTableCount() > 0) {
                result.append(", ").append(task.getStructuredTableCount()).append("个表格");
            }
            structured.setResultSummary(result.toString());
        }
        stages.add(structured);

        // 5. NER 实体提取阶段
        ParseTaskStageVO ner = new ParseTaskStageVO();
        ner.setStageName("ner");
        ner.setDisplayName("NER实体提取");
        setStageStatus(ner, task.getNerStatus(), task.getNerProgress());
        if (task.getNerTaskId() != null) {
            ner.setTaskId(task.getNerTaskId());
        }
        // 添加结果信息
        if ("completed".equals(task.getNerStatus())) {
            StringBuilder result = new StringBuilder();
            if (task.getNerEntityCount() != null) {
                result.append(task.getNerEntityCount()).append("个实体");
            }
            if (task.getNerRelationCount() != null) {
                result.append(", ").append(task.getNerRelationCount()).append("个关系");
            }
            ner.setResultSummary(result.toString());
        }
        stages.add(ner);

        // 6. 图构建阶段
        ParseTaskStageVO graph = new ParseTaskStageVO();
        graph.setStageName("graph");
        graph.setDisplayName("图数据库构建");
        setStageStatus(graph, task.getGraphStatus(), task.getGraphProgress());
        stages.add(graph);

        return stages;
    }
    
    /**
     * 设置阶段状态
     */
    private void setStageStatus(ParseTaskStageVO stage, String status, Integer progress) {
        if (status == null) {
            status = "pending";
        }
        if (progress == null) {
            progress = 0;
        }
        
        switch (status) {
            case "processing":
                stage.setStatus("in_progress");
                stage.setProgress(progress);
                break;
            case "completed":
                stage.setStatus("completed");
                stage.setProgress(100);
                break;
            case "failed":
                stage.setStatus("failed");
                stage.setProgress(progress);
                break;
            default:
                stage.setStatus("pending");
                stage.setProgress(0);
        }
    }
}


