package com.rj.controller;

import com.rj.entity.KnowledgeBase;
import com.rj.service.IKnowledgeBaseService;
import com.rj.service.MinIOService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 知识库管理表 前端控制器
 * </p>
 *
 * @author 李中华 ,spllzh
 * @since 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/api/knowledgeBase")
@Tag(name = "知识库管理", description = "知识库管理相关接口")
public class KnowledgeBaseController {

    @Autowired
    private IKnowledgeBaseService knowledgeBaseService;

    @Autowired
    private MinIOService minIOService;

    /**
     * 新增知识
     */
    @PostMapping("/add")
    @Operation(summary = "新增知识", description = "添加新的知识信息")
    public ResponseEntity<Map<String, Object>> addKnowledge(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @Parameter(description = "知识信息", required = true)
            @ModelAttribute KnowledgeBase knowledgeBase) {
        // 如果提供了文件，上传到MinIO并保存路径
        if (file != null && !file.isEmpty()) {
            try {
                log.info("开始上传文件到MinIO，文件名：{}", file.getOriginalFilename());
                String fileUrl = minIOService.uploadFile(file);
                log.info("文件上传到MinIO成功，URL: {}", fileUrl);
                // 将上传的文件URL保存到知识库对象的附件URL字段
                knowledgeBase.setAttachmentUrl(fileUrl);
            } catch (Exception e) {
                log.error("文件上传到MinIO失败: {}", e.getMessage(), e);
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("success", false);
                errorResult.put("message", "文件上传失败：" + e.getMessage());
                return ResponseEntity.internalServerError().body(errorResult);
            }
        }
        
        Map<String, Object> result = knowledgeBaseService.addKnowledge(knowledgeBase);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据ID查询知识
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询知识", description = "根据知识ID获取知识详细信息")
    public ResponseEntity<Map<String, Object>> getKnowledgeById(
            @Parameter(description = "知识ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = knowledgeBaseService.getKnowledgeById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 分页查询知识列表
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询知识列表", description = "分页查询知识信息列表")
    public ResponseEntity<Map<String, Object>> getKnowledgeList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "知识标题（模糊查询）")
            @RequestParam(required = false) String title,
            @Parameter(description = "知识分类")
            @RequestParam(required = false) String category,
            @Parameter(description = "应用行业")
            @RequestParam(required = false) String industry,
            @Parameter(description = "创建人")
            @RequestParam(required = false) String creator,
            @Parameter(description = "状态")
            @RequestParam(required = false) String status) {
        Map<String, Object> result = knowledgeBaseService.getKnowledgeList(current, size, title, category, industry, creator, status);
        return ResponseEntity.ok(result);
    }

    /**
     * 更新知识信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新知识信息", description = "更新知识详细信息")
    public ResponseEntity<Map<String, Object>> updateKnowledge(
            @Parameter(description = "知识信息", required = true)
            @RequestBody KnowledgeBase knowledgeBase) {
        Map<String, Object> result = knowledgeBaseService.updateKnowledge(knowledgeBase);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据ID删除知识
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除知识", description = "根据知识ID删除知识信息")
    public ResponseEntity<Map<String, Object>> deleteKnowledge(
            @Parameter(description = "知识ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = knowledgeBaseService.deleteKnowledge(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 批量删除知识
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除知识", description = "根据知识ID列表批量删除知识信息")
    public ResponseEntity<Map<String, Object>> batchDeleteKnowledge(
            @Parameter(description = "知识ID列表", required = true)
            @RequestBody List<String> ids) {
        Map<String, Object> result = knowledgeBaseService.batchDeleteKnowledge(ids);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 点赞知识
     */
    @PostMapping("/like/{id}")
    @Operation(summary = "点赞知识", description = "为指定知识点赞")
    public ResponseEntity<Map<String, Object>> likeKnowledge(
            @Parameter(description = "知识ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = knowledgeBaseService.likeKnowledge(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 置顶/取消置顶知识
     */
    @PostMapping("/toggleTop/{id}")
    @Operation(summary = "置顶/取消置顶知识", description = "切换知识的置顶状态")
    public ResponseEntity<Map<String, Object>> toggleTopKnowledge(
            @Parameter(description = "知识ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = knowledgeBaseService.toggleTopKnowledge(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取知识统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取知识统计信息", description = "获取知识总数等统计信息")
    public ResponseEntity<Map<String, Object>> getKnowledgeStatistics() {
        Map<String, Object> result = knowledgeBaseService.getKnowledgeStatistics();
        return ResponseEntity.ok(result);
    }

    /**
     * 获取分类列表
     */
    @GetMapping("/categories")
    @Operation(summary = "获取分类列表", description = "获取所有知识分类")
    public ResponseEntity<Map<String, Object>> getCategories() {
        Map<String, Object> result = knowledgeBaseService.getCategories();
        return ResponseEntity.ok(result);
    }

    /**
     * 获取行业列表
     */
    @GetMapping("/industries")
    @Operation(summary = "获取行业列表", description = "获取所有应用行业")
    public ResponseEntity<Map<String, Object>> getIndustries() {
        Map<String, Object> result = knowledgeBaseService.getIndustries();
        return ResponseEntity.ok(result);
    }
}
