package cn.iocoder.yudao.framework.common.util.io;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class JsonFileUtils {

    /**
     * 读取json文件并转化为类
     * @param multipartFile 文件
     * @return 文件内容
     */
    public static <T> T readJsonAndConvertToObject(MultipartFile multipartFile, Class<T> clazz) {
        try {
            String contentStr = readFile(multipartFile);
            JSONObject object = new JSONObject(multipartFile);
            return object.toBean(clazz);
        } catch (IOException e) {
            log.error("读取json文件失败：", e);
            return null;
        }
    }

    public static <T> List<T> readJsonAndConvertToList(MultipartFile multipartFile, Class<T> clazz) {
        try {
            String contentStr = readFile(multipartFile);
            JSONArray list = new JSONArray(contentStr);
            return list.toList(clazz);
        } catch (IOException e) {
            log.error("读取json文件失败：", e);
            throw ServiceExceptionUtil.exception(GlobalErrorCodeConstants.READ_FILE_FAIL);
        } catch (JSONException e) {
            log.error("读取json文件失败：", e);
            throw ServiceExceptionUtil.exception(GlobalErrorCodeConstants.DATA_CONVERT_FAIL);
        }
    }

    private static String readFile(MultipartFile multipartFile) throws IOException {
        Reader reader = new InputStreamReader(multipartFile.getInputStream(), StandardCharsets.UTF_8);
        int ch;
        StringBuilder sb = new StringBuilder();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        reader.close();
        return sb.toString();
    }

    public static <T> void writeJsonFile(HttpServletResponse response, List<T> list, String fileName) {
        try (OutputStream outputStream = response.getOutputStream()) {
            JSONArray array = new JSONArray(list);
            String jsonStr = array.toString();
            byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
            // 全文件类型（传什么文件返回什么文件流）
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".json" + "\"");
            response.setHeader("Accept-Ranges", "bytes");
            outputStream.write(bytes);
            // 将缓存区数据进行输出
            outputStream.flush();
        } catch (IOException e) {
            log.error("下载json文件失败：", e);
            throw ServiceExceptionUtil.exception(GlobalErrorCodeConstants.WRITE_FILE_FAIL);
        } catch (JSONException e) {
            log.error("读取json文件失败：", e);
            throw ServiceExceptionUtil.exception(GlobalErrorCodeConstants.DATA_CONVERT_FAIL);
        }
    }


}



