package com.lion.lionwebsite.Util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpHeaders;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;


public class FileDownload {
    public static void export(HttpServletRequest request, HttpServletResponse response, String path) {
        File file = new File(path);

        String fileName = file.getName();

        String range = request.getHeader(HttpHeaders.RANGE);

        String rangeSeparator = "-";
        // 开始下载位置
        long startByte = 0;
        // 结束下载位置
        long endByte = file.length() - 1;

        // 如果是断点续传
        if (range != null && range.contains("bytes=") && range.contains(rangeSeparator)) {
            // 设置响应状态码为 206
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String[] ranges = range.split(rangeSeparator);
            try {
                // 判断 range 的类型
                if (ranges.length == 1) {
                    // 类型一：bytes=-2343
                    if (range.startsWith(rangeSeparator)) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                    // 类型二：bytes=2343-
                    else if (range.endsWith(rangeSeparator)) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                // 类型三：bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }
            } catch (NumberFormatException e) {
                // 传参不规范，则直接返回所有内容
                startByte = 0;
                endByte = file.length() - 1;
            }
        } else {
            // 没有 ranges 即全部一次性传输，需要用 200 状态码，这一行应该可以省掉，因为默认返回是 200 状态码
            response.setStatus(HttpServletResponse.SC_OK);
        }

        //要下载的长度（endByte 为总长度 -1，这时候要加回去）
        long contentLength = endByte - startByte + 1;
        //文件类型
        String contentType = request.getServletContext().getMimeType(fileName);

        if (StrUtil.isEmpty(contentType)) {
            contentType = "attachment";
        }

        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        response.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
        // 这里文件名换你想要的，inline 表示浏览器可以直接使用
        // 参考资料：https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,  contentType + ";filename=\"" + URLUtil.encode(fileName) + "\"");
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + startByte + rangeSeparator + endByte + "/" + file.length());

        BufferedOutputStream outputStream;
        RandomAccessFile randomAccessFile = null;
        //已传送数据大小
        long transmitted = 0;
        try {
            randomAccessFile = new RandomAccessFile(file, "r");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int len = 0;
            randomAccessFile.seek(startByte);
            while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                transmitted += len;
                // 本地测试, 防止下载速度过快
//                 Thread.sleep(1);
            }
            // 处理不足 buff.length 部分
            if (transmitted < contentLength) {
                len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
                outputStream.write(buff, 0, len);
            }

            outputStream.flush();
            response.flushBuffer();
            randomAccessFile.close();
            // log.trace("下载完毕: {}-{}, 已传输 {}", startByte, endByte, transmitted);
        } catch (ClientAbortException e) {
            // ignore 用户停止下载
            // log.trace("用户停止下载: {}-{}, 已传输 {}", startByte, endByte, transmitted);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
