package cn.iocoder.yudao.module.infra.controller.admin.file;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.FileUploadAnonymousReqVO;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.FileUploadAnonymousRespVO;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.*;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.infra.service.file.FileService;

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 lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.util.UUID;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.infra.framework.file.core.utils.FileTypeUtils.writeAttachment;

@Tag(name = "管理后台 - 文件存储")
@RestController
@RequestMapping("/infra/file")
@Validated
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "模式一：后端上传文件")
    public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        byte[] content = IoUtil.readBytes(file.getInputStream());
        return success(fileService.createFile(content, file.getOriginalFilename(),
                uploadReqVO.getDirectory(), file.getContentType()));
    }

    @GetMapping("/presigned-url")
    @Operation(summary = "获取文件预签名地址", description = "模式二：前端上传文件：用于前端直接上传七牛、阿里云 OSS 等文件存储器")
    @Parameters({
            @Parameter(name = "name", description = "文件名称", required = true),
            @Parameter(name = "directory", description = "文件目录")
    })
    public CommonResult<FilePresignedUrlRespVO> getFilePresignedUrl(
            @RequestParam("name") String name,
            @RequestParam(value = "directory", required = false) String directory) {
        return success(fileService.getFilePresignedUrl(name, directory));
    }

    @PostMapping("/create")
    @Operation(summary = "创建文件", description = "模式二：前端上传文件：配合 presigned-url 接口，记录上传了上传的文件")
    public CommonResult<Long> createFile(@Valid @RequestBody FileCreateReqVO createReqVO) {
        return success(fileService.createFile(createReqVO));
    }

    @PostMapping("/delete")
    @Operation(summary = "删除文件")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('infra:file:delete')")
    public CommonResult<Boolean> deleteFile(@RequestParam("id") Long id) throws Exception {
        fileService.deleteFile(id);
        return success(true);
    }

    @GetMapping("/{configId}/get/**")
    @PermitAll
    @TenantIgnore
    @Operation(summary = "下载文件")
    @Parameter(name = "configId", description = "配置编号", required = true)
    public void getFileContent(HttpServletRequest request,
                               HttpServletResponse response,
                               @PathVariable("configId") Long configId) throws Exception {
        // 获取请求的路径
        String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false);
        if (StrUtil.isEmpty(path)) {
            throw new IllegalArgumentException("结尾的 path 路径必须传递");
        }
        // 解码，解决中文路径的问题 https://gitee.com/zhijiantianya/ruoyi-vue-pro/pulls/807/
        path = URLUtil.decode(path);

        // 读取内容
        byte[] content = fileService.getFileContent(configId, path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        writeAttachment(response, path, content);
    }

    @GetMapping("/page")
    @Operation(summary = "获得文件分页")
    @PreAuthorize("@ss.hasPermission('infra:file:query')")
    public CommonResult<PageResult<FileRespVO>> getFilePage(@Valid FilePageReqVO pageVO) {
        PageResult<FileDO> pageResult = fileService.getFilePage(pageVO);
        return success(BeanUtils.toBean(pageResult, FileRespVO.class));
    }


    @PostMapping("/upload-anonymous")
    @Operation(summary = "匿名上传文件")
    @PermitAll  // 允许匿名访问
    @TenantIgnore  // 忽略租户
    public CommonResult<FileUploadAnonymousRespVO> uploadFileAnonymous(FileUploadAnonymousReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();

        // 1. 校验文件大小（限制为10MB）
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过10MB");
        }

        // 2. 校验文件类型（只允许特定类型）
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!isAllowedFileType(originalFilename, contentType)) {
            throw new IllegalArgumentException("只支持图片、PDF、Word、Excel、压缩文件");
        }

        // 3. 读取文件内容
        byte[] content = IoUtil.readBytes(file.getInputStream());

        // 4. 固定目录，避免用户指定任意目录
        String directory = "anonymous/" + java.time.LocalDate.now().format(
                java.time.format.DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        // 5. 生成安全的文件名，避免文件名冲突和注入
        //String safeFilename = generateSafeFilename(originalFilename);

        // 6. 上传文件
        String path = fileService.createFile(content, originalFilename, directory, contentType);

        // 7. 返回结果（不包含完整URL，只返回路径）
        FileUploadAnonymousRespVO respVO = new FileUploadAnonymousRespVO();
        respVO.setPath(path);
        respVO.setOriginalFilename(originalFilename);
        respVO.setSize(file.getSize());
        respVO.setContentType(contentType);

        log.info("[uploadFileAnonymous][匿名用户上传文件][文件名: {}][大小: {}][路径: {}]",
                originalFilename, file.getSize(), path);

        return success(respVO);
    }

    /**
     * 校验允许的文件类型
     */
    private boolean isAllowedFileType(String filename, String contentType) {
        if (StrUtil.isBlank(filename) || StrUtil.isBlank(contentType)) {
            return false;
        }

        String lowerFilename = filename.toLowerCase();

        // 只允许上传以下类型
        String[] allowedExtensions = {
                ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp",  // 图片
                ".pdf",                                           // PDF
                ".doc", ".docx", ".wps",                          // Word
                ".xls", ".xlsx",                                  // Excel
                ".txt",                                           // 文本
                ".zip", ".rar", ".7z"                                  // 压缩文件
        };

        for (String ext : allowedExtensions) {
            if (lowerFilename.endsWith(ext)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 生成安全的文件名
     */
    private String generateSafeFilename(String originalFilename) {
        // 获取文件扩展名
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = originalFilename.substring(dotIndex);
        }

        // 生成UUID作为文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 返回新文件名
        return uuid + extension;
    }
}
