package com.ruoyi.business.util;


import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

public class JsoupUtils {

    private static final Logger log = LoggerFactory.getLogger(JsoupUtils.class);

    public static String getJsoupDocGet(String url) {

        final int MAX_RETRIES = 10;
        int retries = 0;
        Document doc = null;
        try {
            URL parsedUrl = new URL(url);
            String host = parsedUrl.getHost(); // 获取主机名

            while (retries < MAX_RETRIES) {
                try {
                    doc = Jsoup.connect(url)
                            .ignoreContentType(true)
                            .ignoreHttpErrors(true)
                            .timeout(1000 * 30)
                            .header("Host", host) // 使用正确的主机名
                            .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                            .header("Accept-Encoding", "gzip, deflate")
                            .header("Accept-Language", "zh-CN,zh;q=0.9")
                            .header("Cache-Control", "max-age=0")
                            .header("Connection", "keep-alive")
                            .header("Upgrade-Insecure-Requests", "1")
                            .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36")
                            .get();

                    String text = doc.text();
                    if (text.contains("illegal")) {
                        return "";
                    } else {
                        return text;
                    }
                } catch (Exception e) {
                    log.info("Failed to retrieve document from URL: " + url + ". Retrying... (" + (retries + 1) + "/" + MAX_RETRIES + ")", e);
                    retries++;
                    if (retries >= MAX_RETRIES) {
                        throw new RuntimeException("Failed to retrieve document after " + MAX_RETRIES + " retries.", e);
                    }
                }
            }
        } catch (MalformedURLException e) {
            log.error("Invalid URL: " + url, e);
            return "";
        }

        return ""; // 理论上不应该到达这里，但保持代码的完整性
    }

    //将文件传入 post请求中
    public static String doPostFileRequest(String url, Map<String, String> param, InputStream fis, String fileName) throws Exception {
        try {
            Connection conn = Jsoup.connect(url);
            if (param != null) {
                conn.data(param);
            }
            conn.data("imagefile", fileName, fis);
            Connection.Response response = conn.timeout(50000)
                    .ignoreContentType(true)
                    .maxBodySize(0)
                    .followRedirects(true)
                    .method(Connection.Method.POST).execute();
            return response.body();
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * post 请求通用入口
     *
     * @param url
     * @param map
     * @return
     */
    public static String jsoupPost(String url, Map<String, Object> map, String json) {
        String res = "";
        try {
            Connection con = Jsoup.connect(url);
            con.requestBody(json);
            con.header("Content-Type", "application/json");
            con.ignoreContentType(true);
            Document doc = con.timeout(50000).post();
            res = doc.text();
        } catch (Exception e) {
            log.info(StringKit.getTrace(e));
        }
        return res;
    }

    public static String jsoupPost(String url, Map<String, Object> map) {
        String res = "";
        try {
            Connection con = Jsoup.connect(url);
            if (map != null && map.size() > 0) {
                Set<String> sets = map.keySet();
                for (String s : sets) {
                    con.data(s, StringKit.toString(map.get(s)));
                }
            }
            con.ignoreContentType(true);
            Document doc =
                    con.timeout(50000)
                            .post();
            res = doc.text();
        } catch (Exception e) {
            log.info(StringKit.getTrace(e));
        }
        return res;
    }


}
