package org.dromara.zhishu.util;

import cn.hutool.json.JSONUtil;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 导出json文件工具类
 */
public class JsonExporterUtils {

    /**
     * 导出json文件方法
     *
     * @param data     导出数据对象
     * @param filename 导出文件名称
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> ResponseEntity<InputStreamResource> exportJsonAsFile(List<T> data, String filename) throws IOException {
        if (data == null || data.isEmpty()) {
            throw new IllegalArgumentException("Data cannot be null or empty.");
        }

        // 将列表转换为JSON字符串
        String jsonStr = JSONUtil.toJsonStr(data);

        // 将JSON字符串写入ByteArrayOutputStream
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(jsonStr.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

        // 设置响应头，让浏览器知道这是一个文件下载
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new ResponseEntity<>(new InputStreamResource(in), headers, HttpStatus.OK);
    }
}
