package com.ruoyi.spider.utils;

import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class UsignUtils {
    private static Logger log = LoggerFactory.getLogger(UsignUtils.class);


    /**
     * 掌上高考签名
     * @param url
     * @return
     */
    public static String getZsgkUsign(String url) {
        try {
            // 可在本地部署
            return getPostResponse("http://121.199.24.78:3000/safesign", url);
        } catch (Exception e) {
            log.error(e.toString());
            try {
                return getPostResponse("http://121.199.24.78:3000/safesign", url);
            } catch (Exception ex) {
                try {
                    return getPostResponse("http://121.199.24.78:3000/safesign", url);
                } catch (Exception ex0) {
                    throw new RuntimeException(ex0);
                }
            }
        }
    }

    public static String getUsign(String jsParam) {
//        String[] options = new String[]{"--language=es6"};
//        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();

        try {
            NashornScriptEngine engine = getEngine();

            Object o = engine.eval("u_sign('" + jsParam + "')");
            // System.out.println("value : "+o);
            return o.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUsignTy(String path, String jsonParam) {
//        String[] options = new String[]{"--language=es6"};
//        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();

        try {
            NashornScriptEngine engine = getEngine3(null);

//            Object o = engine.eval("signAll('" + path + "'," + jsonParam + ")");
            Object o = engine.eval("sign.t()");
            System.out.println("getUsignTy value t : " + o);

            o = engine.eval("sign.sign.y('" + path + "'," + jsonParam + ")");
            System.out.println("getUsignTy value y : " + o);


            return o.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getPostResponse(String url, String queryParam) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Accept", "application/json");

        // 构造请求体
        String jsonInputString = String.format("{\"query\": \"%s\"}", queryParam);

        // 发送POST请求
        con.setDoOutput(true);
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine.trim());
                }

                // 解析响应
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                int code = jsonResponse.getIntValue("code");
                if (code == 200) {
                    return jsonResponse.getString("data");
                } else {
                    throw new Exception("Unexpected response code: " + code);
                }
            }
        } else {
            throw new Exception("请求失败: " + responseCode);
        }
    }
    public static String requestDecode(String queryParam) throws Exception {
        // 只能在windows上部署
        return getPostResponse("http://121.199.24.78:3000/decode", queryParam);
    }

    public static NashornScriptEngine getEngine() {
        /* 1.首先引入js引擎 */
        // ScriptEngineManager manager = new ScriptEngineManager();
        // 引擎名称传入JavaScript、js、javascript、nashorn、Nashorn 均可等价
        // ScriptEngine engine = manager.getEngineByName("nashorn");

        String[] options = new String[]{"--language=es6"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        NashornScriptEngine engine = (NashornScriptEngine) factory.getScriptEngine(options);

        try {
            /* 2.然后读取js文件 */
            File file = ResourceUtils.getFile("classpath:js/usign.js");
//            File file= new File("/app/voluntarydata/js/usign.js");
//            log.info("file path: {}", file.getAbsolutePath());
//            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); // 获取targe路径

//            engine.eval(new FileReader(path + "js/usign.js"));
            engine.eval(new FileReader(file.getAbsolutePath()));

            return engine;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static NashornScriptEngine getEngine3(String resourcePath) {
        /* 1.首先引入js引擎 */
        // ScriptEngineManager manager = new ScriptEngineManager();
        // 引擎名称传入JavaScript、js、javascript、nashorn、Nashorn 均可等价
        // ScriptEngine engine = manager.getEngineByName("nashorn");

        String[] options = new String[]{"--language=es6"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        NashornScriptEngine engine = (NashornScriptEngine) factory.getScriptEngine(options);

        try {
            /* 2.然后读取js文件 */

            File file = ResourceUtils.getFile(resourcePath);
            engine.eval(new FileReader(file.getAbsolutePath()));

            return engine;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String getUsignAll2(String path, String jsonParam) {
        String[] options = new String[]{"--language=es6"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();

        try {
            NashornScriptEngine engine = getEngine3("classpath:js/ie/sign.js");

            Object o = engine.eval("makeSign(" + jsonParam + ")");
//            Object o = engine.eval("makeSign()");

//            System.out.println("getEngine2 value : " + o);
            return o.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String url000= "https://api.zjzw.cn/web/api/?local_province_id=41&local_single_id=75001&local_type_id=195&page=2&school_id=1156&size=5&student_type=62&uri=apidata/api/gkv3/single/special_score&year=2023";
        url000="https://api.zjzw.cn/web/api/?local_province_id=41&local_single_id=75001&local_type_id=195&page=1&school_id=1520&size=100&student_type=62&uri=apidata/api/gkv3/single/plan&year=2021";
        System.out.println(getZsgkUsign(url000));

        String requestPath = "/youzy.dms.datalib.api.enrolldata.plan.encrypted.v2.query";
        String jsonParam = "{\"batch\":\"本一\",\"year\":2022,\"provinceCode\":36,\"collegeCode\":\"10073\",\"course\":\"文科\"}";
//        System.out.println(getUsignAll(requestPath, jsonParam));

        jsonParam = "{\"app_type\":\"senioriup\",\"good_app_type\":\"senioriup\",\"province_id\":\"5604\",\"timestrap\":1695627630,\"platform\":\"android\",\"deviceid\":\"senioriup2d3011f34b0a8dc8\",\"channel\":\"ali\",\"oaid\":\"2d3011f34b0a8dc8\",\"version\":\"v1.6.6\",\"knowledge_id\":\"19053\",\"type\":\"know_test\",\"is_next\":\"0\",\"config_id\":\"0\",\"subject_id\":\"1401\",\"cate_id\":\"1399\"}";
//        System.out.println(getUsignAll2(requestPath, jsonParam));

    }
}
