package com.testor.common.util;

import lombok.SneakyThrows;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private static MimetypesFileTypeMap mimetypesFileTypeMap;

    public static void main(String[] args) {
        //String url = "http://10.10.80.105:18083/ureport/excel?_u=file:revisionAccident.ureport.xml&accidentStartTime=2022-01-01+00:00:00&accidentEndTime=2022-06-13+23:59:59";
        // 测试示例
        String url = "http://192.168.1.5:9000/zlmy/1736241571750.png";
        String fileName = getFileNameWithoutExtension(url);
        System.out.println("File Name: " + fileName);  // 输出: 1736241571750.png
    }

    /**
     * 从给定的 URL 中提取文件名
     *
     * @param url 目标文件的 URL
     * @return 提取到的文件名
     */
    public static String getFileNameFromUrl(String url) {
        try {
            // 从 URL 中提取文件名
            URI uri = new URI(url);
            String path = uri.getPath(); // 获取 URL 路径部分
            return Paths.get(path).getFileName().toString(); // 获取文件名
        } catch (Exception e) {
            // 处理异常，可能是 URL 格式错误等
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从给定的 URL 中提取不带后缀的文件名
     *
     * @param url 目标文件的 URL
     * @return 提取到的文件名（不包含后缀）
     */
    public static String getFileNameWithoutExtension(String url) {
        try {
            // 从 URL 中提取文件名
            URI uri = new URI(url);
            String path = uri.getPath(); // 获取 URL 路径部分
            String fileName = Paths.get(path).getFileName().toString(); // 获取文件名

            // 移除文件扩展名
            int dotIndex = fileName.lastIndexOf('.');
            if (dotIndex > 0) {
                return fileName.substring(0, dotIndex); // 返回去除后缀的文件名
            } else {
                return fileName; // 如果没有扩展名，直接返回文件名
            }
        } catch (Exception e) {
            // 处理异常，可能是 URL 格式错误等
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载http文件流
     *
     * @param urlStr
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadHttpFile(String urlStr, HttpServletRequest request, HttpServletResponse response, String fileName) {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
//            String encode = URLEncoder.encode(urlStr, "UTF-8");
            String encode = encode(urlStr);
            URL url = new URL(encode);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization", request.getHeader("Authorization"));
            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = FileUtil.inputStreamToByte(inputStream);
            // 下载
            out = response.getOutputStream();
            long contentLength = getData.length;
            FileUtil.setResponse(fileName, contentLength, request, response);
            out.write(getData);
            out.flush();
        } catch (Exception e) {
            String message = e.getMessage();
            if (StringUtils.isBlank(message)) {
                message = "下载失败!";
            }
            throw new RuntimeException(message);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String encode(String url) {
        try {

            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            int count = 0;
            while (matcher.find()) {
                String tmp = matcher.group();
                url = url.replaceAll(tmp, URLEncoder.encode(tmp, "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = url.replaceAll(" ", "+");
        return url;
    }

    //File、FileInputStream 转换为byte数组
    public static byte[] inputStreamToByte(InputStream inputStream) {
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("文件转换失败!");
        }
    }

    /**
     * 通过 URL 下载图片并将其转换为 PNG 格式的 Base64 编码
     *
     * @param imageUrl 图片的 URL
     * @return 返回转换后的 PNG 格式 Base64 编码
     * @throws IOException 如果读取或写入文件时出错
     */
    @SneakyThrows
    public static String convertImageFromUrlToBase64(String imageUrl){
        // 从 URL 获取输入流
        URL url = new URL(imageUrl);
        InputStream inputStream = url.openStream();
        TranscoderInput input = new TranscoderInput(inputStream);

        // 判断图片的格式
        String format = getImageFormatFromUrl(imageUrl);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        if (format.contains("svg")) {
            PNGTranscoder transcoder = new PNGTranscoder();
            TranscoderOutput output = new TranscoderOutput(outputStream);
            transcoder.transcode(input, output);
        }else {
            // 读取图片并转换为 BufferedImage 对象
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            // 将 BufferedImage 转换为 ByteArrayOutputStream
            ImageIO.write(bufferedImage, "PNG", outputStream);  // 写入 PNG 格式
        }
        // 将字节数组转换为 Base64 编码
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        // 关闭输入流
        inputStream.close();
        outputStream.close();
        inputStream.close();
        return base64Image;
    }


    /**
     * 根据图片文件的 URL 后缀判断图片格式
     *
     * @param imageUrl 图片的 URL
     * @return 图片格式（如 "jpg", "png", "gif" 等）
     */
    public static String getImageFormatFromUrl(String imageUrl) {
        // 获取文件名并判断后缀
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

        // 提取文件扩展名
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 根据扩展名判断图片格式
        switch (fileExtension) {
            case "jpg":
            case "jpeg":
                return "jpeg";
            case "png":
                return "png";
            case "gif":
                return "gif";
            case "bmp":
                return "bmp";
            case "tiff":
                return "tiff";
            case "webp":
                return "webp";
            case "svg":
                return "svg";
            default:
                return "unknown";  // 未知格式
        }
    }

    /**
     * 下载文件流
     *
     * @param file
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response, String fileName) {
        if (file != null && file.exists() && file.length() > 0L) {
            try {
                RandomAccessFile randomFile = new RandomAccessFile(file, "r");
                Throwable var5 = null;

                Object var54;
                try {
                    ServletOutputStream out = response.getOutputStream();
                    Throwable var7 = null;

                    try {
                        long contentLength = randomFile.length();
                        String range = request.getHeader("Range");
                        long start = 0L;
                        long end = 0L;
                        if (range != null && range.startsWith("bytes=")) {
                            String[] values = range.split("=")[1].split("-");
                            start = Long.parseLong(values[0]);
                            if (values.length > 1) {
                                end = Long.parseLong(values[1]);
                            }
                        }

                        int requestSize;
                        if (end != 0L && end > start) {
                            requestSize = Long.valueOf(end - start + 1L).intValue();
                        } else {
                            requestSize = 2147483647;
                        }

                        FileUtil.setResponse(fileName, contentLength, request, response);

                        randomFile.seek(start);

                        byte[] buffer;
                        for (int needSize = requestSize; needSize > 0; needSize -= buffer.length) {
                            buffer = new byte[1024];
                            int len = randomFile.read(buffer);
                            if (needSize < buffer.length) {
                                out.write(buffer, 0, needSize);
                            } else {
                                out.write(buffer, 0, len);
                                if (len < buffer.length) {
                                    break;
                                }
                            }
                        }

                        out.flush();
                        var54 = null;
                    } catch (Throwable var47) {
                        var7 = var47;
                        throw var47;
                    } finally {
                        if (out != null) {
                            if (var7 != null) {
                                try {
                                    out.close();
                                } catch (Throwable var46) {
                                    var7.addSuppressed(var46);
                                }
                            } else {
                                out.close();
                            }
                        }

                    }
                } catch (Throwable var49) {
                    var5 = var49;
                    throw var49;
                } finally {
                    if (randomFile != null) {
                        if (var5 != null) {
                            try {
                                randomFile.close();
                            } catch (Throwable var45) {
                                var5.addSuppressed(var45);
                            }
                        } else {
                            randomFile.close();
                        }
                    }

                }
            } catch (IOException var51) {
                logger.debug(var51.getMessage(), var51);
                throw new RuntimeException(var51.getMessage());
            }
        } else {
            throw new RuntimeException("文件为空或不存在！");
        }
    }

    /**
     * @param fileName
     * @param contentLength
     * @param request
     * @param response
     * @return
     */
    public static void setResponse(String fileName, long contentLength, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(FileUtil.getContentType("0.jpg"));
            boolean isPreview = "preview".equalsIgnoreCase(request.getParameter("source"));
            response.addHeader("Content-Disposition", (!isPreview ? "attachment; " : "") + "filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Accept-Ranges", "bytes");

            String range = request.getHeader("Range");
            if (range == null) {
                response.setHeader("Content-Length", String.valueOf(contentLength));
            } else {
                response.setStatus(206);
                long requestStart = 0L;
                long requestEnd = 0L;
                String[] ranges = range.split("=");
                if (ranges.length > 1) {
                    String[] rangeDatas = ranges[1].split("-");
                    requestStart = Long.parseLong(rangeDatas[0]);
                    if (rangeDatas.length > 1) {
                        requestEnd = Long.parseLong(rangeDatas[1]);
                    }
                }

                long length = 0L;
                if (requestEnd > 0L) {
                    length = requestEnd - requestStart + 1L;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
                } else {
                    length = contentLength - requestStart;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + (contentLength - 1L) + "/" + contentLength);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("response响应失败!");
        }
    }

    public static String getContentType(String fileName) {
        if (mimetypesFileTypeMap == null) {
            mimetypesFileTypeMap = new MimetypesFileTypeMap();
        }

        return mimetypesFileTypeMap.getContentType(fileName);
    }

    /**
     * 将磁盘的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipDirFileToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置response参数并且获取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);

            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                File file = new File(map.get("path"));
                InputStream inputStream = new FileInputStream(file);
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void ExcelUrlToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response, String name) {
        try {
            ArrayList<InputStream> list = new ArrayList<>();
            ArrayList<String> fileNames = new ArrayList<>();
            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                InputStream inputStream = getInputStreamFromUrl(map.get("path"));
                list.add(inputStream);
                fileNames.add(fileName);
            }
            ExcelUtils.mergeExcel(list, name, response,fileNames);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 将网络url资源文件的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param request
     * @param response
     */
    public static void zipUrlToFile(List<Map<String, String>> pathList, HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        ZipArchiveOutputStream zous = null;
        try {
            // 设置response参数并且获取ServletOutputStream
            zous = getServletOutputStream(response);

            for (Map<String, String> map : pathList) {
                String fileName = map.get("name");
                inputStream = getInputStreamFromUrl(map.get("path"));
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try{
                inputStream.close();
                zous.close();
            }catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }
    }

    private static ZipArchiveOutputStream getServletOutputStream(HttpServletResponse response) throws Exception {

        String outputFileName = "文件" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletResponse res = new ServletResponseWrapper(response);
        ServletOutputStream out = res.getOutputStream();
//        BufferedOutputStream bout = new BufferedOutputStream(out);
        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        return zous;
    }

    private static void setByteArrayOutputStream(String fileName, InputStream inputStream, ZipArchiveOutputStream zous) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] bytes = baos.toByteArray();

        //设置文件名
        ArchiveEntry entry = new ZipArchiveEntry(fileName);
        zous.putArchiveEntry(entry);
        zous.write(bytes);
        zous.closeArchiveEntry();
        baos.close();
    }

    /**
     * 通过网络地址获取文件InputStream
     *
     * @param path 地址
     * @return
     */
    private static InputStream getInputStreamFromUrl(String path) {
        URL url = null;
        InputStream is = null;
        try {
            String encode = encode(path);
            url = new URL(encode);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }
        return is;
    }

    /**
     * 复制InputStream
     *
     * InputStream inputStream = new ByteArrayInputStream(ByteArrayOutputStream.toByteArray());
     * @param input
     * @return
     */
    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
            return null;
        }
    }
}
