package com.example.controller;



import com.example.dto.AttachmentDto;

import com.example.dto.AttachmentResponseDTO;

import com.example.dto.NoteDto;

import com.example.dto.SaveNoteRequest;

import com.example.dto.SearchResultDTO;

import com.example.entity.Note;

import com.example.entity.User;

import com.example.service.AttachmentService;

import com.example.service.NoteService;

import com.example.service.SearchService;

import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;



import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;



/**

 * 笔记控制器

 * 注意:由于 server.servlet.context-path=/api,实际路径为 /api/notes/xxx

 * 

 * 变更说明:返回 NoteDto 而不是 Note 实体,避免序列化 Hibernate 懒加载代理对象

 */

@RestController

@RequestMapping("/notes")

@RequiredArgsConstructor

@Slf4j

public class NoteController {

    

    private final NoteService noteService;

    private final AttachmentService attachmentService;

    private final SearchService searchService;

    

    /**

     * 上传附件

     * POST /api/notes/{noteId}/attachments

     * 变更说明:AttachmentResponseDTO 中的 attachment 字段现在返回 AttachmentDto

     */

    @PostMapping("/{noteId}/attachments")

    public ResponseEntity<AttachmentResponseDTO> uploadAttachment(

            @PathVariable Long noteId,

            @RequestParam("file") MultipartFile file) {

        

        try {

            if (noteId == null) {

                log.warn("笔记ID为空");

                return ResponseEntity.badRequest()

                        .body(new AttachmentResponseDTO(false, "笔记ID不能为空", null));

            }

            

            if (file == null || file.isEmpty()) {

                log.warn("上传文件为空");

                return ResponseEntity.badRequest()

                        .body(new AttachmentResponseDTO(false, "文件不能为空", null));

            }

            

            log.info("========== 开始上传附件 ==========");

            log.info("笔记ID: {}, 文件名: {}, 文件大小: {} bytes", 

                noteId, file.getOriginalFilename(), file.getSize());

            

            // 使用同步 OCR 方法,确保上传时能立即获得 OCR 结果

            com.example.entity.Attachment attachment = attachmentService.uploadAttachmentWithOcr(noteId, file);

            AttachmentDto attachmentDto = AttachmentDto.fromEntity(attachment);

            

            AttachmentResponseDTO response = new AttachmentResponseDTO(

                    true,

                    "文件上传成功" + (attachment.getOcrContent() != null && !attachment.getOcrContent().isEmpty() 

                        ? ",OCR识别完成" : "(OCR未执行或结果为空)"),

                    attachmentDto

            );

            

            log.info("========== 附件上传成功 ==========");

            log.info("附件ID: {}, OCR内容长度: {}", 

                attachment.getId(),

                attachment.getOcrContent() != null ? attachment.getOcrContent().length() : 0);

            return ResponseEntity.status(HttpStatus.CREATED).body(response);

            

        } catch (IllegalArgumentException e) {

            log.error("附件上传失败(参数错误): {}", e.getMessage());

            return ResponseEntity.badRequest()

                    .body(new AttachmentResponseDTO(false, "参数错误: " + e.getMessage(), null));

        } catch (RuntimeException e) {

            // RuntimeException 通常是业务逻辑错误(如文件保存失败),但不应该导致 500

            log.error("❌ 附件上传失败(业务异常),笔记ID: {}", noteId, e);

            log.error("异常类型: {}", e.getClass().getName());

            log.error("异常消息: {}", e.getMessage());

            

            String errorMessage = "文件上传失败";

            if (e.getMessage() != null && !e.getMessage().isEmpty()) {

                errorMessage = e.getMessage();

            }

            

            // 返回 400 而不是 500,表示客户端请求有问题

            return ResponseEntity.status(HttpStatus.BAD_REQUEST)

                    .body(new AttachmentResponseDTO(false, errorMessage, null));

        } catch (Exception e) {

            // 未知异常,记录详细日志但返回友好错误信息

            log.error("❌ 附件上传失败(未知异常),笔记ID: {}", noteId, e);

            log.error("异常类型: {}", e.getClass().getName());

            log.error("异常消息: {}", e.getMessage());

            if (e.getCause() != null) {

                log.error("根因: {}", e.getCause().getMessage());

                log.error("根因类型: {}", e.getCause().getClass().getName());

            }

            

            // 提取更详细的错误信息

            String errorMessage = "文件上传失败,请稍后重试";

            if (e.getMessage() != null && !e.getMessage().isEmpty()) {

                // 过滤掉技术细节,只返回用户友好的信息

                String msg = e.getMessage();

                if (msg.contains("IOException") || msg.contains("File")) {

                    errorMessage = "文件读取或保存失败,请检查文件是否完整";

                } else if (msg.contains("数据库") || msg.contains("database")) {

                    errorMessage = "数据保存失败,请稍后重试";

                } else {

                    errorMessage = "文件上传失败: " + msg;

                }

            }

            

            // 返回 500 但带友好错误信息

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)

                    .body(new AttachmentResponseDTO(false, errorMessage, null));

        }

    }

    

    /**

     * 获取某笔记本下的所有笔记

     * GET /api/notes?notebookId=xx

     * 变更说明:返回 NoteDto 列表而不是 Note 列表

     */

    @GetMapping

    public ResponseEntity<List<NoteDto>> getNotes(@RequestParam(required = false) Long notebookId) {

        try {

            if (notebookId == null) {

                log.warn("笔记本ID参数为空");

                return ResponseEntity.badRequest().build();

            }

            

            List<Note> notes = noteService.getNotesByNotebookId(notebookId);

            

            // 转换为 DTO 列表(注意:notes 列表中的 attachments 可能未初始化,但不影响基本字段)

            List<NoteDto> noteDtos = notes.stream()

                    .map(NoteDto::fromEntity)

                    .collect(Collectors.toList());

            

            log.info("获取笔记本 {} 下的笔记列表,共 {} 条", notebookId, noteDtos.size());

            return ResponseEntity.ok(noteDtos);

            

        } catch (Exception e) {

            log.error("获取笔记列表失败,笔记本ID: {}", notebookId, e);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

        }

    }

    

    /**

     * 获取笔记详情

     * GET /api/notes/{id}

     * 变更说明:返回 NoteDto 而不是 Note 实体

     * 注意:attachments 字段已包含 AttachmentDto 列表

     */

    @GetMapping("/{id}")

    public ResponseEntity<NoteDto> getNoteById(@PathVariable Long id) {

        try {

            if (id == null) {

                log.warn("笔记ID为空");

                return ResponseEntity.badRequest().build();

            }

            

            Note note = noteService.getNoteById(id);

            NoteDto noteDto = NoteDto.fromEntity(note);

            

            log.info("获取笔记详情,ID: {}", id);

            return ResponseEntity.ok(noteDto);

            

        } catch (IllegalArgumentException e) {

            log.error("获取笔记详情失败: {}", e.getMessage());

            return ResponseEntity.badRequest().build();

        } catch (Exception e) {

            log.error("获取笔记详情失败,ID: {}", id, e);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

        }

    }

    

    /**

     * 保存或更新笔记

     * POST /api/notes/save

     * 变更说明:返回 NoteDto 而不是 Note 实体

     * 注意:新建时返回 201 CREATED,更新时返回 200 OK

     */

    @PostMapping("/save")

    public ResponseEntity<NoteDto> saveNote(@RequestBody SaveNoteRequest request) {

        try {

            if (request == null) {

                log.warn("请求体为空");

                return ResponseEntity.badRequest().build();

            }

            

            // 将 DTO 转换为实体

            Note note = new Note();

            note.setId(request.getId()); // 如果为 null 则是新建

            note.setTitle(request.getTitle());

            note.setContent(request.getContent());

            note.setNotebookId(request.getNotebookId());

            

            Note savedNote = noteService.saveNote(note);

            NoteDto noteDto = NoteDto.fromEntity(savedNote);

            

            if (note.getId() == null) {

                log.info("创建笔记成功,ID: {}", savedNote.getId());

                return ResponseEntity.status(HttpStatus.CREATED).body(noteDto);

            } else {

                log.info("更新笔记成功,ID: {}", savedNote.getId());

                return ResponseEntity.ok(noteDto);

            }

            

        } catch (IllegalArgumentException e) {

            log.error("保存笔记失败: {}", e.getMessage());

            return ResponseEntity.badRequest().build();

        } catch (Exception e) {

            log.error("保存笔记失败", e);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

        }

    }

    

    /**

     * 删除笔记

     * DELETE /api/notes/{id}

     * 从 Spring Security Context 中获取当前登录用户,确保只能删除自己的笔记

     */

    @DeleteMapping("/{id}")

    public ResponseEntity<?> deleteNote(@PathVariable Long id) {

        log.info("========== 删除笔记请求到达 ==========");

        log.info("笔记ID: {}", id);

        

        try {

            // 1. 从 SecurityContext 获取当前登录用户

            Long userId = getCurrentUserId();

            if (userId == null) {

                log.warn("无法获取当前登录用户ID");

                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)

                        .body(createErrorResponse("未登录或登录已过期,请重新登录"));

            }

            

            // 2. 参数验证

            if (id == null) {

                log.warn("笔记ID为空");

                return ResponseEntity.badRequest()

                        .body(createErrorResponse("笔记ID不能为空"));

            }

            

            // 3. 删除笔记(包含权限验证)

            noteService.deleteNote(id, userId);

            

            log.info("删除笔记成功,ID: {}, 用户ID: {}", id, userId);

            log.info("========== 删除笔记成功 ==========");

            

            // 4. 返回成功响应

            Map<String, Object> response = new HashMap<>();

            response.put("success", true);

            response.put("message", "笔记删除成功");

            

            return ResponseEntity.ok(response);

            

        } catch (IllegalArgumentException e) {

            log.error("删除笔记失败(参数错误): {}", e.getMessage());

            return ResponseEntity.status(HttpStatus.BAD_REQUEST)

                    .body(createErrorResponse(e.getMessage()));

        } catch (Exception e) {

            log.error("删除笔记失败,ID: {}", id, e);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)

                    .body(createErrorResponse("删除笔记失败: " + e.getMessage()));

        }

    }

    

    /**

     * 从 Spring Security Context 获取当前登录用户的ID

     * @return 用户ID,如果未登录则返回 null

     */

    private Long getCurrentUserId() {

        try {

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication == null || !authentication.isAuthenticated()) {

                log.warn("SecurityContext 中没有认证信息");

                return null;

            }

            

            Object principal = authentication.getPrincipal();

            if (principal instanceof User) {

                User user = (User) principal;

                return user.getId();

            }

            

            log.warn("Principal 不是 User 类型: {}", principal != null ? principal.getClass().getName() : "null");

            return null;

            

        } catch (Exception e) {

            log.error("获取当前用户ID失败", e);

            return null;

        }

    }

    

    /**

     * 创建错误响应

     */

    private Map<String, Object> createErrorResponse(String message) {

        Map<String, Object> response = new HashMap<>();

        response.put("success", false);

        response.put("message", message);

        return response;

    }

    

    /**

     * 全局搜索

     * GET /api/notes/search?q=xxx

     * 搜索笔记标题、内容和关联附件的OCR内容

     * 返回格式:无变化(SearchResultDTO)

     */

    @GetMapping("/search")

    public ResponseEntity<List<SearchResultDTO>> search(@RequestParam("q") String keyword) {

        try {

            if (keyword == null || keyword.trim().isEmpty()) {

                log.warn("搜索关键词为空");

                return ResponseEntity.badRequest().build();

            }

            

            log.info("执行全局搜索,关键词: {}", keyword);

            

            List<SearchResultDTO> results = searchService.globalSearch(keyword);

            

            log.info("搜索完成,找到 {} 条结果", results.size());

            return ResponseEntity.ok(results);

            

        } catch (Exception e) {

            log.error("搜索失败,关键词: {}", keyword, e);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

        }

    }

}