package cn.cslg.report.controller;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.utils.DateUtils;
import cn.cslg.report.common.utils.FileUtils;
import cn.cslg.report.entity.Template;
import cn.cslg.report.service.business.TemplateService;
import cn.hutool.core.io.FileUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Tag(name = "下载")
@RestController
@RequestMapping(Constants.REPORT_API + "/download")
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class DownloadController {
    private final FileUtils fileUtils;

    @GetMapping("downloadFile")
    @Operation(summary = "下载文件")
    public ResponseEntity<FileSystemResource> downloadSystemFile2(String url) throws IOException {
        File file = new File(fileUtils.getSystemPath() + url);
        HttpHeaders headers = new HttpHeaders();
        String fileName = DateUtils.getNowTimeFormat(DateUtils.YYYYMMDDHHMMSS) + "." + FileUtil.extName(file.getName());
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        HttpStatus status = HttpStatus.OK;
        return new ResponseEntity<>(new FileSystemResource(file), headers, status);
    }

}
