package com.lingyue.parse.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.document.entity.Document;
import com.lingyue.document.repository.DocumentRepository;
import com.lingyue.document.service.DocumentElementService;
import com.lingyue.parse.service.ParseTaskCenterService;
import com.lingyue.parse.service.ParseTaskExecutor;
import com.lingyue.parse.service.WordStructuredExtractionService;
import com.lingyue.parse.vo.ParseTaskCenterVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 解析控制器
 */
@Slf4j
@RestController
@RequestMapping("/parse")
@RequiredArgsConstructor
@Tag(name = "解析任务", description = "解析任务启动与状态查询接口")
public class ParseController {

    private final ParseTaskExecutor parseTaskExecutor;
    private final ParseTaskCenterService taskCenterService;
    private final WordStructuredExtractionService wordStructuredExtractionService;
    private final DocumentRepository documentRepository;
    private final DocumentElementService documentElementService;

    /**
     * 启动解析
     *
     * @param documentId 文档ID
     * @param filePath 原始文件路径
     */
    @PostMapping("/start")
    @Operation(summary = "启动解析任务")
    public AjaxResult<?> startParse(
            @Parameter(description = "文档ID", required = true)
            @RequestParam("documentId") String documentId,
            @Parameter(description = "原始文件路径", required = true)
            @RequestParam("filePath") String filePath) {

        parseTaskExecutor.submitParseTask(documentId, filePath);
        return AjaxResult.success("解析任务已提交");
    }

    /**
     * 查询解析状态（按文档ID）
     */
    @GetMapping("/status/{documentId}")
    @Operation(summary = "查询解析任务状态")
    public AjaxResult<?> getParseStatus(@PathVariable String documentId) {
        ParseTaskCenterVO detail = taskCenterService.getTaskDetailByDocumentId(documentId);
        if (detail == null) {
            return AjaxResult.error("解析任务不存在");
        }
        return AjaxResult.success(detail);
    }
    
    /**
     * 获取 Word 文档结构化内容
     * 包含段落、图片、表格的顺序和位置信息
     * 自动从数据库获取文件路径，并保存到 document_elements 表
     */
    @GetMapping("/structured/{documentId}")
    @Operation(summary = "获取Word文档结构化内容", description = "提取Word文档的段落、图片、表格，保持原始排版结构")
    public AjaxResult<?> getStructuredContent(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId) {
        
        // 从数据库获取文档信息
        Document document = documentRepository.selectById(documentId);
        if (document == null) {
            return AjaxResult.error("文档不存在: " + documentId);
        }
        
        String filePath = document.getFileUrl();
        if (filePath == null || filePath.isEmpty()) {
            return AjaxResult.error("文档文件路径为空");
        }
        
        // 检查是否是 Word 文档
        if (!"word".equalsIgnoreCase(document.getType())) {
            return AjaxResult.error("仅支持 Word 文档的结构化解析，当前文档类型: " + document.getType());
        }
        
        // 提取结构化内容
        WordStructuredExtractionService.WordStructuredResult result = 
                wordStructuredExtractionService.extractStructured(filePath, documentId);
        
        // 保存到数据库
        try {
            log.info("保存结构化元素到数据库: documentId={}, elementCount={}", documentId, result.getElements().size());
            documentElementService.saveElements(documentId, result.getElements());
            log.info("结构化元素保存成功: documentId={}", documentId);
        } catch (Exception e) {
            // 保存失败不影响返回结果，只记录日志
            log.error("保存结构化元素失败: documentId={}, error={}", documentId, e.getMessage(), e);
        }
        
        return AjaxResult.success(result);
    }
    
    /**
     * 获取已保存的文档结构化元素
     */
    @GetMapping("/elements/{documentId}")
    @Operation(summary = "获取文档结构化元素", description = "从数据库获取已解析的文档元素")
    public AjaxResult<?> getDocumentElements(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId) {
        return AjaxResult.success(documentElementService.getElements(documentId));
    }
    
    /**
     * 获取文档中的图片元素
     */
    @GetMapping("/elements/{documentId}/images")
    @Operation(summary = "获取文档图片", description = "获取文档中的所有图片元素")
    public AjaxResult<?> getDocumentImages(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId) {
        return AjaxResult.success(documentElementService.getImageElements(documentId));
    }
    
    /**
     * 获取文档中的表格元素
     */
    @GetMapping("/elements/{documentId}/tables")
    @Operation(summary = "获取文档表格", description = "获取文档中的所有表格元素")
    public AjaxResult<?> getDocumentTables(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId) {
        return AjaxResult.success(documentElementService.getTableElements(documentId));
    }
}

