package org.xyzh.file.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xyzh.api.file.FileService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.dto.system.TbSysFile;

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

/**
 * @description 文件控制器
 * @filename FileController.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-16
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * @description 上传文件
     * @param file 文件对象
     * @param module 所属模块
     * @param businessId 业务ID
     * @param uploader 上传者用户ID（可选）
     * @return ResultDomain<TbSysFile> 上传结果
     * @author yslg
     * @since 2025-10-16
     */
    @PostMapping("/upload")
    public ResultDomain<TbSysFile> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false, defaultValue = "common") String module,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "uploader", required = false) String uploader) {
        
        log.info("上传文件请求: module={}, businessId={}, uploader={}, fileName={}", 
                module, businessId, uploader, file.getOriginalFilename());
        
        return fileService.uploadFile(file, module, businessId, uploader);
    }

    /**
     * @description 下载文件
     * @param fileId 文件ID
     * @return ResponseEntity<byte[]> 文件字节数组
     * @author yslg
     * @since 2025-10-16
     */
    @GetMapping("/download/{fileId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileId) {
        log.info("下载文件请求: fileId={}", fileId);
        
        ResultDomain<TbSysFile> fileResult = fileService.getFileById(fileId);
        if (!fileResult.isSuccess() || fileResult.getData() == null) {
            return ResponseEntity.notFound().build();
        }

        ResultDomain<byte[]> dataResult = fileService.downloadFile(fileId);
        if (!dataResult.isSuccess() || dataResult.getData() == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

        TbSysFile sysFile = (TbSysFile) fileResult.getData();
        byte[] fileData = (byte[]) dataResult.getData();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(
                sysFile.getMimeType() != null ? sysFile.getMimeType() : MediaType.APPLICATION_OCTET_STREAM_VALUE));
        headers.setContentDispositionFormData("attachment", 
                URLEncoder.encode(sysFile.getOriginalName(), StandardCharsets.UTF_8));
        headers.setContentLength(fileData.length);

        return new ResponseEntity<>(fileData, headers, HttpStatus.OK);
    }

    /**
     * @description 删除文件（逻辑删除）
     * @param fileId 文件ID
     * @return ResultDomain<TbSysFile> 删除结果
     * @author yslg
     * @since 2025-10-16
     */
    @DeleteMapping("/{fileId}")
    public ResultDomain<TbSysFile> deleteFile(@PathVariable String fileId) {
        log.info("删除文件请求: fileId={}", fileId);
        return fileService.deleteFile(fileId);
    }

    /**
     * @description 物理删除文件
     * @param fileId 文件ID
     * @return ResultDomain<TbSysFile> 删除结果
     * @author yslg
     * @since 2025-10-16
     */
    @DeleteMapping("/physical/{fileId}")
    public ResultDomain<TbSysFile> deleteFilePhysically(@PathVariable String fileId) {
        log.info("物理删除文件请求: fileId={}", fileId);
        return fileService.deleteFilePhysically(fileId);
    }

    /**
     * @description 根据文件ID查询文件信息
     * @param fileId 文件ID
     * @return ResultDomain<TbSysFile> 文件信息
     * @author yslg
     * @since 2025-10-16
     */
    @GetMapping("/{fileId}")
    public ResultDomain<TbSysFile> getFileById(@PathVariable String fileId) {
        return fileService.getFileById(fileId);
    }

    /**
     * @description 根据业务ID查询文件列表
     * @param module 所属模块
     * @param businessId 业务ID
     * @return ResultDomain<TbSysFile> 文件列表
     * @author yslg
     * @since 2025-10-16
     */
    @GetMapping("/business/{module}/{businessId}")
    public ResultDomain<TbSysFile> getFilesByBusinessId(
            @PathVariable String module,
            @PathVariable String businessId) {
        return fileService.getFilesByBusinessId(module, businessId);
    }

    /**
     * @description 根据上传者查询文件列表
     * @param uploader 上传者用户ID
     * @return ResultDomain<TbSysFile> 文件列表
     * @author yslg
     * @since 2025-10-16
     */
    @GetMapping("/uploader/{uploader}")
    public ResultDomain<TbSysFile> getFilesByUploader(@PathVariable String uploader) {
        return fileService.getFilesByUploader(uploader);
    }

    /**
     * @description 获取文件访问URL
     * @param fileId 文件ID
     * @return ResultDomain<String> 文件访问URL
     * @author yslg
     * @since 2025-10-16
     */
    @GetMapping("/url/{fileId}")
    public ResultDomain<String> getFileUrl(@PathVariable String fileId) {
        return fileService.getFileUrl(fileId);
    }

    /**
     * @description 批量上传文件
     * @param files 文件对象数组
     * @param module 所属模块
     * @param businessId 业务ID
     * @param uploader 上传者用户ID（可选）
     * @return ResultDomain<TbSysFile> 上传结果
     * @author yslg
     * @since 2025-10-16
     */
    @PostMapping("/batch-upload")
    public ResultDomain<TbSysFile> batchUploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "module", required = false, defaultValue = "common") String module,
            @RequestParam(value = "businessId", required = false) String businessId,
            @RequestParam(value = "uploader", required = false) String uploader) {
        
        log.info("批量上传文件请求: count={}, module={}, businessId={}, uploader={}", 
                files != null ? files.length : 0, module, businessId, uploader);
        
        return fileService.batchUploadFiles(files, module, businessId, uploader);
    }

    /**
     * @description 批量删除文件
     * @param fileIds 文件ID数组
     * @return ResultDomain<TbSysFile> 删除结果
     * @author yslg
     * @since 2025-10-16
     */
    @DeleteMapping("/batch")
    public ResultDomain<TbSysFile> batchDeleteFiles(@RequestBody String[] fileIds) {
        log.info("批量删除文件请求: count={}", fileIds != null ? fileIds.length : 0);
        return fileService.batchDeleteFiles(fileIds);
    }
}

