package org.xyzh.file.controller;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.xyzh.api.file.dto.TbSysFileDTO;
import org.xyzh.api.file.service.FileService;
import org.xyzh.common.core.domain.ResultDomain;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @description    文件管理控制器
 * @filename    FileController.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Tag(name = "文件管理")
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    // ========================= 文件上传 =========================

    @Operation(summary = "上传文件")
    @PostMapping("/upload")
    public ResultDomain<TbSysFileDTO> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false) String module,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "fileName", required = false) String fileName) {
        try {
            // 如果前端传递了 fileName，使用它；否则使用 MultipartFile 的原始文件名
            String actualFileName = (fileName != null && !fileName.isEmpty()) ? fileName : file.getOriginalFilename();
            return fileService.uploadFileBytes(file.getBytes(), actualFileName, file.getContentType(), module, businessId);
        } catch (Exception e) {
            return ResultDomain.failure("文件上传失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量上传文件")
    @PostMapping("/upload/batch")
    public ResultDomain<TbSysFileDTO> batchUploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "module", required = false) String module,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "uploader", required = false) String uploader) {
        return fileService.batchUploadFiles(files, module, businessId, uploader);
    }

    @Operation(summary = "上传临时文件")
    @PostMapping("/upload/temp")
    public ResultDomain<TbSysFileDTO> saveTempFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false) String module,
            @RequestParam(value = "businessId", required = false) String businessId) {
        return fileService.saveTempFile(file, module, businessId);
    }

    @Operation(summary = "上传新版本文件")
    @PostMapping("/upload/version")
    public ResultDomain<TbSysFileDTO> uploadFileVersion(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false) String module,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam("fileRootId") String fileRootId) {
        return fileService.uploadFileVersion(file, module, businessId, fileRootId);
    }

    // ========================= 文件查询 =========================

    @Operation(summary = "获取文件信息")
    @GetMapping("/{fileId}")
    public ResultDomain<TbSysFileDTO> getFileById(@PathVariable("fileId") String fileId) {
        return fileService.getFileById(fileId);
    }

    // ========================= 文件下载 =========================

    @Operation(summary = "下载文件")
    @GetMapping("/download/{fileId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable("fileId") String fileId) {
        ResultDomain<byte[]> result = fileService.downloadFile(fileId);
        if (!result.getSuccess() || result.getData() == null) {
            return ResponseEntity.notFound().build();
        }
        
        ResultDomain<TbSysFileDTO> fileInfo = fileService.getFileById(fileId);
        String filename = fileInfo.getData() != null ? fileInfo.getData().getName() : "download";
        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20");
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(result.getData());
    }

    // ========================= 文件删除 =========================

    @Operation(summary = "删除文件")
    @DeleteMapping("/{fileId}")
    public ResultDomain<Boolean> deleteFile(@PathVariable("fileId") String fileId) {
        return fileService.deleteFile(fileId);
    }

    @Operation(summary = "批量删除文件")
    @DeleteMapping("/batch")
    public ResultDomain<TbSysFileDTO> batchDeleteFiles(@RequestParam("fileIds") String[] fileIds) {
        return fileService.batchDeleteFiles(fileIds);
    }

}
