package vip.xiaonuo.coldchain.modular.files;

import cn.hutool.core.io.IoUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.pojo.CommonResult;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import static cn.dev33.satoken.SaManager.log;

@Tag(name = "文件控制器")
@RestController
@Validated
@Slf4j
public class fileController {

    @Value("${file.path}")
    private String filePath;

    @Operation(summary = "下载文件")
    @RequestMapping("/download")
    public void fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
        File file = new File(filePath, fileName);
        log.info(file.getAbsolutePath() + "--------" + filePath);
        if(!file.exists()){
            throw new CommonException("下载文件不存在");
        }

        String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename*=utf8''" + encodeFileName);

        IoUtil.copy(Files.newInputStream(file.toPath()), response.getOutputStream());
    }
}
