package com.bcxin.ferry.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * description: 文件工具类
 * author: linchunpeng
 * date:  2023-04-18 15:15
 */
@Slf4j
public class FileUtils {


    /**
     * description: 根据url下载文件
     * author: linchunpeng
     * date:  2023-04-18 15:15
     */
    public static boolean downloadByUrl(String urlStr, String fileSavePath) {
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置部分请求头信息，根据自己的实际需要来书写，不需要的也可以删掉
            conn.setRequestProperty("api_token", "Bearer_");
            conn.setRequestProperty("Cookie", "XXL_JOB_LOGIN_IDENTITY=");
            //得到输入流
            inputStream = conn.getInputStream();

            fos = new FileOutputStream(fileSavePath);
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            fos.close();
            inputStream.close();

            log.info("文件: {}，下载成功", urlStr);
            return true;
        } catch (Exception e) {
            log.error("文件：{}，下载异常", urlStr, e);
            return false;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (fos != null) fos.close();
            } catch (Exception e) {
                log.error("文件：{}，关闭流异常", urlStr, e);
            }
        }
    }


    /**
     * description: 判断文件是否能访问
     * author: linchunpeng
     * date:  2023-04-23 16:48
     */
    public static boolean checkFileHutool(String fileUrl) {
        HttpResponse executeAsync = null;
        try {
            if (fileUrl.startsWith("https:/")) {
                if (!fileUrl.substring(0, 8).equals("https://")) {
                    fileUrl = fileUrl.replace("https:/", "https://");
                }
            }
            HttpRequest get = HttpUtil.createGet(fileUrl, true);
            get.header("accessToken", "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTY2Njg2MDAwMSwidXNlcm5hbWUiOiI3TkVMR1RYaSJ9.Fvx16149p8Grp-a_QwFRGro_sWD1xqL2QV5beL9bRcc");
            executeAsync = get.executeAsync();
            int status = executeAsync.getStatus();
            if (status != 200) {
                log.info("文件访问失败，访问结果：{}，文件地址：{}", status, fileUrl);
            }
            return status == 200;
        } catch (Exception e) {
            log.error("文件：{}，判断是否能访问异常：{}", fileUrl, e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (executeAsync != null) executeAsync.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * description: 判断文件是否能访问
     * author: linchunpeng
     * date:  2023-04-23 16:48
     */
    public static boolean checkFile(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            urlcon.setRequestMethod("GET");
            urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            int responseCode = urlcon.getResponseCode();
            if (responseCode != 200) {
                log.info("第二次文件访问失败，访问结果：{}，文件地址：{}", responseCode, fileUrl);
            }
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            log.error("文件：{}，第二次访问异常：{}", fileUrl, e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    /**
     * description: 获取url的连接状态
     * author: linchunpeng
     * date:  2023-04-28 10:17
     */
    public static int getUrlStatus(String fileUrl) {
        HttpResponse executeAsync = null;
        try {
            HttpRequest get = HttpUtil.createGet(fileUrl, true);
            executeAsync = get.executeAsync();
            return executeAsync.getStatus();
        } catch (Exception e) {
            e.printStackTrace();
            return 404;
        } finally {
            try {
                if (executeAsync != null) executeAsync.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void responseWithFile(String realPath, HttpServletResponse response) throws IOException {
        File selectedFile = new File(realPath);
        response.setContentType("application/x-download; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + java.net.URLEncoder.encode(selectedFile.getName(), "UTF-8") + "\"");

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            try (BufferedInputStream reader = new BufferedInputStream(new FileInputStream(selectedFile))) {
                byte[] buffer = new byte[4096];
                int i = -1;
                while ((i = reader.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, i);
                }
            }
            outputStream.flush();
        }
    }

//    public static void main(String[] args) {
//        downloadByUrl("https://02obs-file-system-obpm-uploads.obs.cn-north-1.myhuaweicloud.com/baidu/pull/beijing/20240926061616326.zip", "/Users/linchunpeng/Downloads/20240926061616326.zip");
//    }

}
