package com.aegis.web.controller.knowledge;

import com.aegis.common.annotation.Log;
import com.aegis.common.core.controller.BaseController;
import com.aegis.common.core.domain.AjaxResult;
import com.aegis.common.core.page.TableDataInfo;
import com.aegis.common.enums.BusinessType;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.StringUtils;
import com.aegis.file.domain.FileInfo;
import com.aegis.file.service.IFileService;
import com.aegis.knowledge.domain.KnowledgeDocument;
import com.aegis.knowledge.service.IKnowledgeDocumentService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 知识库文档管理 Controller
 */
@RestController
@RequestMapping("/api/knowledge/documents")
public class KnowledgeDocumentController extends BaseController {

    @Autowired
    private IKnowledgeDocumentService documentService;

    @Autowired
    private IFileService fileService;

    /**
     * 查询文档列表
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:list')")
    @GetMapping
    public TableDataInfo list(@RequestParam(required = false) String keyword,
                              @RequestParam(required = false) Long categoryId,
                              @RequestParam(required = false) String tags,
                              @RequestParam(required = false) Date beginTime,
                              @RequestParam(required = false) Date endTime) {
        startPage();
        List<KnowledgeDocument> list = documentService.listByCondition(keyword, categoryId, tags, beginTime, endTime);
        return getDataTable(list);
    }

    /**
     * 获取文档详情
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        KnowledgeDocument document = documentService.getById(id);
        if (document == null || "2".equals(document.getDelFlag())) {
            return error("文档不存在或已删除");
        }
        // 增加查看次数
        documentService.incrementViewCount(id);
        return success(document);
    }

    /**
     * 新增文档
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:add')")
    @Log(title = "知识库文档管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KnowledgeDocument document) {
        if (document == null) {
            return error("文档信息不能为空");
        }
        if (StringUtils.isBlank(document.getTitle())) {
            return error("文档标题不能为空");
        }
        if (document.getFileId() == null) {
            return error("文件ID不能为空");
        }
        
        // 验证文件是否存在
        FileInfo fileInfo = fileService.selectFileById(document.getFileId());
        if (fileInfo == null) {
            return error("文件不存在");
        }
        
        // 设置文件信息
        if (StringUtils.isBlank(document.getFileName())) {
            document.setFileName(fileInfo.getOriginalName());
        }
        if (document.getFileSize() == null) {
            document.setFileSize(fileInfo.getFileSize());
        }
        if (StringUtils.isBlank(document.getFileType())) {
            document.setFileType(fileInfo.getFileType());
        }
        
        boolean saved = documentService.save(document);
        if (saved) {
            return success(document);
        }
        return error("保存失败");
    }

    /**
     * 修改文档
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:edit')")
    @Log(title = "知识库文档管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}")
    public AjaxResult edit(@PathVariable Long id, @RequestBody KnowledgeDocument document) {
        document.setId(id);
        return toAjax(documentService.updateById(document));
    }

    /**
     * 删除文档
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:remove')")
    @Log(title = "知识库文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        KnowledgeDocument document = documentService.getById(id);
        if (document == null || "2".equals(document.getDelFlag())) {
            return error("文档不存在或已删除");
        }
        // 逻辑删除
        document.setDelFlag("2");
        return toAjax(documentService.updateById(document));
    }

    /**
     * 下载文档
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:download')")
    @GetMapping("/{id}/download")
    public void download(@PathVariable Long id, HttpServletResponse response) {
        KnowledgeDocument document = documentService.getById(id);
        if (document == null || "2".equals(document.getDelFlag())) {
            throw new ServiceException("文档不存在或已删除");
        }
        if (document.getFileId() == null) {
            throw new ServiceException("文件ID不能为空");
        }
        
        // 增加下载次数
        documentService.incrementDownloadCount(id);
        
        // 通过文件模块下载
        fileService.downloadFile(document.getFileId(), response);
    }

    /**
     * 根据事件类型和关键词推荐文档
     */
    @PreAuthorize("@ss.hasPermi('knowledge:document:recommend')")
    @GetMapping("/recommend")
    public AjaxResult recommend(@RequestParam(required = false) String eventType,
                                 @RequestParam(required = false) String keywords) {
        List<KnowledgeDocument> list = documentService.recommendDocuments(eventType, keywords);
        return success(list);
    }
}

