package cn.cslg.report.controller;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.model.vo.TaskFromPASVO;
import cn.cslg.report.common.utils.DateUtils;
import cn.cslg.report.common.utils.FileUtils;

import cn.cslg.report.entity.Task;
import cn.cslg.report.service.OutInterfaceService;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
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;
import java.util.List;

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

    @GetMapping("downloadFile")
    @Operation(summary = "下载文件")
    public ResponseEntity<FileSystemResource> downloadSystemFile2(String url, Integer taskId) throws IOException {
        File file = new File(fileUtils.getSystemPath() + url);
        if (!file.exists()) {
            String json2 = outInterfaceService.getDownLoadFile(url);
            JSONObject jsonObject2 = JSONObject.parseObject(json2);
            String path = jsonObject2.get("data").toString();
            file = new File(path);
        }
        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);
    }

}
