package com.nantian.cloud.dbcapp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.dbcapp.service.FileExportService;
import com.nantian.cloud.dbcapp.vo.FileExportVO;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 离线生成文件
 *
 * @author dengjian
 * @Date 2024/11/14 14:58
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/fileExport")
@Api(value = "fileExport", tags = "离线生成文件")
public class FileExportController {

    @Autowired
    private FileExportService fileExportService;


    /**
     * 查询列表
     *
     * @param
     * @return R
     */
    @GetMapping("/getFileExportList")
    @SysLog("离线文件-查询列表")
    @ApiOperation(value = "查询列表", notes = "查询列表")
    public R getFileExportList(Page page,@RequestParam(required = false) String fileName) {
        return R.ok(fileExportService.getFileExportList(page,fileName));
    }

    @GetMapping("/deleteFileExportById")
    @SysLog("删除文件")
    @ApiOperation(value = "查询列表", notes = "查询列表")
    public R deleteFileExportById(@RequestParam("id") Integer id) {
        return R.ok(fileExportService.deleteFileExportById(id));
    }

    @GetMapping("/downloadFile")
    @SysLog("下载文件")
    @ApiOperation(value = "下载文件", notes = "下载文件")
    public void downloadFile(HttpServletResponse response,@RequestParam("id") Integer id) {
        try {
            // 获取文件信息
            FileExportVO info = fileExportService.getFileExportById(id);
            // 设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(info.getFileName().getBytes("UTF-8"), "ISO-8859-1"));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            // 读取文件
            Path filePath = Paths.get(info.getFilePath());
            Files.copy(filePath, response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
