package com.test.bijihoudaun.controller;

import cn.hutool.core.util.ObjectUtil;
import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.entity.MarkdownFile;
import com.test.bijihoudaun.entity.MarkdownFileChunk;
import com.test.bijihoudaun.entity.MarkdownFileVO;
import com.test.bijihoudaun.service.MarkdownFileService;
import com.test.bijihoudaun.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Tag(name = "markdown接口")
@RestController
@RequestMapping("/api/markdown")
public class MarkdownController {

    @Autowired
    private MarkdownFileService markdownFileService;

    @Operation(summary = "测试")
    @GetMapping("/test")
    @Profile("!prod")
    public R<List<MarkdownFile>> test() {
        List<MarkdownFile> test = markdownFileService.test();
        return R.success(test);
    }

    @Operation(summary = "预览markdown文件")
    @Parameters({
        @Parameter(name = "id", description = "文件ID", required = true)
    })
    @GetMapping("/{id}")
    public R<String> getMarkdownContent(@PathVariable Long id) {
        // 获取当前认证状态
        boolean isAuthenticated = SecurityUtil.isUserAuthenticated();
        
        MarkdownFile file = markdownFileService.getMarkdownById(id, isAuthenticated);
        if (ObjectUtil.isNotNull(file)) {
            // 如果是私密笔记且用户未认证，只返回标题
            if (file.getIsPrivate() != null && file.getIsPrivate() == 1 && !isAuthenticated) {
                return R.success(""); // 返回空内容，只显示标题
            }
            return R.success(file.getContent());
        }
        return R.fail();
    }


    @Operation(summary = "更新Markdown文件")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/updateMarkdown")
    public R<MarkdownFile> updateMarkdown(@RequestBody MarkdownFile markdownFile) {
        MarkdownFile file = markdownFileService.updateMarkdownContent(markdownFile);
        return R.success(file);
    }

    @Operation(summary = "获取所有Markdown文件")
    @GetMapping
    public R<List<MarkdownFile>> getAllMarkdownFiles() {
        List<MarkdownFile> files = markdownFileService.getAllMarkdownFiles();
        return R.success(files);
    }
    
    @Operation(summary = "删除Markdown文件")
    @PreAuthorize("hasRole('ADMIN')")
    @Parameters({
            @Parameter(name = "id", description = "Markdown文件ID", required = true),
    })
    @DeleteMapping("/{id}")
    public R<Void> deleteMarkdown(@PathVariable Long id) {
        if (markdownFileService.deleteMarkdownFile(id)) {
            return R.success();
        }
        return R.fail();
    }
    
    @Operation(summary = "根据分组ID获取Markdown文件")
    @GetMapping("/grouping/{groupingId}")
    public R<List<MarkdownFileVO>> getFilesByGroupingId(@PathVariable Long groupingId) {
        List<MarkdownFileVO> files = markdownFileService.getFilesByGroupingId(groupingId);
        return R.success(files);
    }

    @Operation(summary = "根据标题模糊搜索")
    @GetMapping("/search")
    public R<List<MarkdownFile>> searchByTitle(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        if (page < 1) page = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 20;
        List<MarkdownFile> files = markdownFileService.searchByTitle(keyword, page, pageSize);
        return R.success(files);
    }

    @Operation(summary = "更新Markdown文件标题")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{id}/title")
    public R<MarkdownFile> updateMarkdownTitle(
            @PathVariable Long id,
            @RequestParam String title) {
        MarkdownFile updatedFile = markdownFileService.updateMarkdownTitle(id, title);
        if (ObjectUtil.isNotNull(updatedFile)) {
            return R.success(updatedFile);
        }
        return R.fail("文件未找到或更新失败");
    }

    @Operation(summary = "获取最近更新的笔记")
    @GetMapping("/recent")
    public R<List<MarkdownFileVO>> getRecentFiles(@RequestParam(defaultValue = "16") int limit) {
        List<MarkdownFileVO> files = markdownFileService.getRecentFiles(limit);
        return R.success(files);
    }

    @Operation(summary = "分块加载Markdown文件内容", description = "用于大文件（> 500KB）的分页加载")
    @Parameters({
        @Parameter(name = "id", description = "文件ID", required = true),
        @Parameter(name = "chunkIndex", description = "块索引（从0开始）", required = false),
        @Parameter(name = "chunkSize", description = "块大小（字符数），默认10000", required = false)
    })
    @GetMapping("/{id}/chunk")
    public R<MarkdownFileChunk> getMarkdownChunk(
            @PathVariable Long id,
            @RequestParam(defaultValue = "0") int chunkIndex,
            @RequestParam(defaultValue = "10000") int chunkSize) {
        
        // 获取当前认证状态
        boolean isAuthenticated = SecurityUtil.isUserAuthenticated();
        
        MarkdownFileChunk chunk = markdownFileService.getMarkdownChunk(id, chunkIndex, chunkSize, isAuthenticated);
        if (ObjectUtil.isNotNull(chunk)) {
            return R.success(chunk);
        }
        return R.fail("文件未找到");
    }

}
