package com.jeelowcode.service.infra.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.jeelowcode.service.infra.controller.vo.file.*;
import com.jeelowcode.service.infra.entity.FileDO;
import com.jeelowcode.service.infra.service.IFileService;
import com.jeelowcode.tool.framework.common.pojo.CommonResult;
import com.jeelowcode.tool.framework.common.pojo.PageResult;
import com.jeelowcode.tool.framework.common.util.io.FileUtils;
import com.jeelowcode.tool.framework.common.util.object.BeanUtils;
import com.jeelowcode.tool.framework.common.util.servlet.ServletUtils;
import com.jeelowcode.tool.framework.operatelog.core.annotations.OperateLog;
import com.jeelowcode.tool.framework.security.core.LoginUser;
import com.jeelowcode.tool.framework.security.core.util.SecurityFrameworkUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import static com.jeelowcode.tool.framework.common.pojo.CommonResult.success;

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

    @Resource
    private IFileService fileService;

    @PostMapping("/upload")
    @Operation(tags = "文件管理", summary = "上传文件", description = "模式一：后端上传文件")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String fileName = file.getOriginalFilename();
        //微信图片_20230905094700.png
        //查询当天是否存在该名称


        // String fileName = uploadReqVO.getPath();
        //jeeLowCode修改
        //判断当天是否有该名称了

        //根据天来分类
        String today = DateUtil.today();
        String publicPath = "upload/" + today + "/";
        String path = publicPath + fileName;

        fileName = fileService.getUniqueFileName(fileName, path);
        path = publicPath + IdUtil.simpleUUID() + (StrUtil.isEmpty(FileUtil.extName(fileName)) ? "" : ("." + FileUtil.extName(fileName)));

        return success(fileService.createFile(fileName, path, IoUtil.readBytes(file.getInputStream())));
    }

    @PostMapping("/jeelowcode/upload")
    @Operation(tags = "文件管理", summary = "上传文件", description = "模式一：后端上传文件")
    @OperateLog(logArgs = false) // 上传文件，没有记录操作日志的必要
    public CommonResult<Map<String, String>> jeeLowCodeUploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String fileName = file.getOriginalFilename();
        //微信图片_20230905094700.png
        Long tenantId = -1L;
        Long userId = -1L;
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser != null) {
            tenantId = loginUser.getTenantId();
            userId = loginUser.getId();
        }
        //每个文件放一个文件夹，防止乱码后找不到正确文件
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmssSSS");
        String timeString = now.format(formatter);
        String publicPath = "upload/" + tenantId + "/" + userId + "/" + timeString + "/";
        String path = publicPath + fileName;

        fileName = fileService.getUniqueFileName(fileName, path);
        // 解决信创环境下文件名中文乱码导致附件错乱的问题
        //path = publicPath + IdUtil.simpleUUID() + (StrUtil.isEmpty(FileUtil.extName(fileName)) ? "" : ("." + FileUtil.extName(fileName)));

        String fileUrl = fileService.createFile(fileName, path, IoUtil.readBytes(file.getInputStream()));

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("fileUrl", fileUrl);
        return success(resultMap);
    }


    @GetMapping("/presigned-url")
    @Operation(tags = "文件管理", summary = "获取文件预签名地址", description = "模式二：前端上传文件：用于前端直接上传七牛、阿里云 OSS 等文件存储器")
    public CommonResult<FilePresignedUrlRespVO> getFilePresignedUrl(@RequestParam("path") String path) throws Exception {
        return success(fileService.getFilePresignedUrl(path));
    }

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

    @DeleteMapping("/delete")
    @Operation(tags = "文件管理", 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
    @Operation(tags = "文件管理", 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;
        }
        ServletUtils.writeAttachment(response, path, content);
    }

    @GetMapping("/page")
    @Operation(tags = "文件管理", 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));
    }

}
