package com.nexo.model.douyin.utils;

import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class DouYinUtils {

    public static String getABogus(String prams) {
        // 创建脚本引擎管理器
        ScriptEngineManager manager = new ScriptEngineManager();
        // 创建脚本引擎
        ScriptEngine engine = manager.getEngineByName("javascript");

        // 创建全局变量
        try {
            engine.eval("var window = window || {};");
            engine.eval("var navigator = navigator || {};");
            engine.eval("var document = document || {};");
            engine.eval("var performance = performance || { now: function() { return new Date().getTime(); } };");
            engine.eval("var location = location || {};");
            engine.eval("var history = history || {};");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        String property = System.getProperty("user.dir");
        // 执行JS文件
        try {
            engine.eval(new FileReader(property + "\\config\\geta_b.js"));
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        String result = "";
        // 转换为可调用接口
        if (engine instanceof Invocable) {
            Invocable invocable = (Invocable) engine;
            // 调用geta_b函数
            try {
                result = invocable.invokeFunction("geta_b", prams).toString();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    /**
     * 生成header
     */
    public static HashMap<String, String> getHeader() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("Accept", "application/json, text/plain, */*");
        hashMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        hashMap.put("Connection", "keep-alive");
        hashMap.put("Host", "www.douyin.com");
        hashMap.put("Referer", "https://www.douyin.com/user/MS4wLjABAAAAvUIxmVOEO2g5F32m12-cXKi836UCa5FmbpQ4GGJ3k49yiZxvv16cxXA7h56TJ2nL");
        hashMap.put("Sec-Fetch-Dest", "empty");
        hashMap.put("Sec-Fetch-Mode", "cors");
        hashMap.put("Sec-Fetch-Site", "same-origin");
        hashMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.238.400 QQBrowser/12.4.5623.400");
        hashMap.put("sec-ch-ua", "\"Chromium\";v=\"142\", \"Microsoft Edge\";v=\"142\", \"Not_A Brand\";v=\"99\"");
        hashMap.put("sec-ch-ua-mobile", "?0");
        hashMap.put("sec-ch-ua-platform", "\"Windows\"");
        hashMap.put("Cookie", "enter_pc_once=1; UIFID_TEMP=29a1f63ec682dc0a0df227dd163e2b46e3a6390e403335fa4c2c6d1dc0ec5ffa649cc31323e372d64dea3183ffa05b74aca6b1b47b8cf1de34790a6701803eca2b2d636525c37c32100b7b3d960c6da4; fpk1=U2FsdGVkX19NusbbbQv5nKR6qrsBtKy4ET+2JyNQHHzlW3wZ3yoxRyV6xmI4LyJ22/GV7wvm+Kve77VQ+nq+9A==; fpk2=800cce95768a9a4605cb3f6b181e9057; UIFID=29a1f63ec682dc0a0df227dd163e2b46e3a6390e403335fa4c2c6d1dc0ec5ffa619a5e6377f30f37cfe494accaf4b130bc8ccb70ad0bf5a36881e5a54f8eb38f24b6e8689cd78cd71787daefc722b6062679ad2c7e5883a98bd601f98214a4d69cb9c544a02476e83fa5ac980dd8924c3c3c8599a42ae00dea5a811fc9eeb9ca65f718fe36abc4365aded7fc7c8f85e404ac098f3fe40ab0157cb929d645e625; xgplayer_device_id=93496821212; xgplayer_user_id=537807349986; bd_ticket_guard_client_web_domain=2; SEARCH_RESULT_LIST_TYPE=%22single%22; n_mh=MIpuP22A7OmnsYKF5cQN0IEki-ybyOrsMEeiF02bm4M; SelfTabRedDotControl=%5B%5D; my_rd=2; live_use_vvc=%22false%22; s_v_web_id=verify_mp4xmi43_R2ZADT9W_IKha_4C4e_9b3a_ctEUtT2EsPOe; dy_swidth=1920; dy_sheight=1080; passport_csrf_token=f352ad7476eb923cc41d75f988146701; passport_csrf_token_default=f352ad7476eb923cc41d75f988146701; is_dash_user=1; SEARCH_UN_LOGIN_PV_CURR_DAY=%7B%22date%22%3A1778730075938%2C%22count%22%3A1%7D; passport_assist_user=CkGKaVn4Mvgh6KjcOTGn0aBLfUsqv9lR2wt7Ox4BZiEikQgL6AU5Hg9fTnGgL7ETJIMiDoJrpLu0Iy9CwECEUR3vYRpKCjwAAAAAAAAAAAAAUGtpFBHHlCMR1zUOix0CffXxrXn2ro17wDTTMlJ1Oi2OkoYkuNMPVFwBgjcu07qYDJsQ1rSRDhiJr9ZUIAEiAQNsJAG0; sid_guard=bb2575b5064ef00a67f75b1dfcb285b6%7C1778730095%7C5184000%7CMon%2C+13-Jul-2026+03%3A41%3A35+GMT; uid_tt=41927bc825f2ebf4df1940a884f37b0d; uid_tt_ss=41927bc825f2ebf4df1940a884f37b0d; sid_tt=bb2575b5064ef00a67f75b1dfcb285b6; sessionid=bb2575b5064ef00a67f75b1dfcb285b6; sessionid_ss=bb2575b5064ef00a67f75b1dfcb285b6; session_tlb_tag=sttt%7C19%7CuyV1tQZO8Apn91sd_LKFtv________-73rt8JSHvfHR4UCAErqD2KhEVOClfitaPwlLX4QAdaz0%3D; is_staff_user=false; has_biz_token=false; sid_ucp_v1=1.0.0-KDc3NDRjNjdmYjg3ZDk0ZmRhOWFkMTczMGY4NTllZDIwODQ5NzNhOWEKIQick6CK_c2hAxDviJXQBhjvMSAMML6o9LcGOAdA9AdIBBoCbGYiIGJiMjU3NWI1MDY0ZWYwMGE2N2Y3NWIxZGZjYjI4NWI2; ssid_ucp_v1=1.0.0-KDc3NDRjNjdmYjg3ZDk0ZmRhOWFkMTczMGY4NTllZDIwODQ5NzNhOWEKIQick6CK_c2hAxDviJXQBhjvMSAMML6o9LcGOAdA9AdIBBoCbGYiIGJiMjU3NWI1MDY0ZWYwMGE2N2Y3NWIxZGZjYjI4NWI2; _bd_ticket_crypt_cookie=9d4a9f6a26d4f147251d4b37a11a5a2f; __security_mc_1_s_sdk_sign_data_key_web_protect=a91cf128-4b49-a094; __security_mc_1_s_sdk_cert_key=8337bff5-4880-b203; __security_mc_1_s_sdk_crypt_sdk=ccf1d04a-4afa-be74; __security_server_data_status=1; login_time=1778730098709; publish_badge_show_info=%220%2C0%2C0%2C1778730102870%22; download_guide=%223%2F20260514%2F0%22; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.021%7D; __druidClientInfo=JTdCJTIyY2xpZW50V2lkdGglMjIlM0E1NDYlMkMlMjJjbGllbnRIZWlnaHQlMjIlM0E4NTclMkMlMjJ3aWR0aCUyMiUzQTU0NiUyQyUyMmhlaWdodCUyMiUzQTg1NyUyQyUyMmRldmljZVBpeGVsUmF0aW8lMjIlM0ExJTJDJTIydXNlckFnZW50JTIyJTNBJTIyTW96aWxsYSUyRjUuMCUyMChXaW5kb3dzJTIwTlQlMjAxMC4wJTNCJTIwV2luNjQlM0IlMjB4NjQpJTIwQXBwbGVXZWJLaXQlMkY1MzcuMzYlMjAoS0hUTUwlMkMlMjBsaWtlJTIwR2Vja28pJTIwQ2hyb21lJTJGMTQ4LjAuMC4wJTIwU2FmYXJpJTJGNTM3LjM2JTIwRWRnJTJGMTQ4LjAuMC4wJTIyJTdE; is_support_rtm_web_ts=1; strategyABtestKey=%221778817978.058%22; ttwid=1%7CmzV7UW6bxIn7RYmfIuUU-8tSB_Aj1PQZRLjt5L5kXKQ%7C1778817972%7Cdf64bd9cf7ef04e1ee760b888e4af980eebd2db78f1803d0743e8fae6be6c400; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAALSIgU7MFq8KK0DblB6_a65JZTLhc6wINrwUTO2mSIJ0lMnntlVyxkCi_ob3vhA6W%2F1778860800000%2F0%2F1778818124877%2F0%22; webcast_local_quality=null; live_private_user=0; FOLLOW_NUMBER_YELLOW_POINT_INFO=%22MS4wLjABAAAALSIgU7MFq8KK0DblB6_a65JZTLhc6wINrwUTO2mSIJ0lMnntlVyxkCi_ob3vhA6W%2F1778860800000%2F0%2F0%2F1778831304887%22; __live_version__=%221.1.5.1831%22; live_can_add_dy_2_desktop=%220%22; live_debug_info=%7B%22roomId%22%3A%227640011575180430134%22%2C%22resolution%22%3A%7B%22width%22%3A540%2C%22height%22%3A960%7D%2C%22fps%22%3A44%2C%22audioDataRate%22%3A48000%2C%22droppedFrames%22%3A0%2C%22totalFrames%22%3A5%2C%22videoBuffer%22%3A%5B%5D%2C%22src%22%3A%22https%3A%2F%2Fpull-hs-f5.flive.douyincdn.com%2Fthird%2Fstream-407605594764870315_ld.flv%3Fexpire%3D1779434900%26sign%3De56af1cd813819ef7b57d836e4bea166%26volcSecret%3De56af1cd813819ef7b57d836e4bea166%26volcTime%3D1779434900%26neq%3D1%26arch_hrchy%3Dw1%26exp_hrchy%3Dw1%26major_anchor_level%3Dcommon%26unique_id%3Dstream-407605594764870315_683_flv_ld%26t_id%3D037-202605151528198914B8848866B0D2C5F2-XIWYXv%26_session_id%3D037-202605151528198914B8848866B0D2C5F2-XIWYXv.1778830106840.61396%26rsi%3D1%26abr_pts%3D-800%22%2C%22linkmicInfo%22%3A%7B%22uiLayout%22%3A0%2C%22playModes%22%3A%5B%5D%2C%22allDevices%22%3A%22%E8%BF%9E%E7%BA%BF%E8%AE%BE%E5%A4%87%EF%BC%9A%E7%94%B3%E8%AF%B7%E8%BF%9E%E7%BA%BF%E5%90%8E%E6%89%8D%E8%8E%B7%E5%8F%96%22%2C%22audioInputs%22%3A%5B%5D%2C%22videoInputs%22%3A%5B%5D%7D%2C%22href%22%3A%22https%3A%2F%2Flive.douyin.com%2F108701796243%3Fanchor_id%3D529317319942250%26category_name%3Dall%26is_vs%3D0%26page_type%3Dmain_category_page%26vs_ep_group_id%3D%26vs_episode_id%3D%26vs_episode_stage%3D%26vs_season_id%3D%22%7D; PhoneResumeUidCacheV1=%7B%221836664670914972%22%3A%7B%22time%22%3A1778830114508%2C%22noClick%22%3A1%7D%7D; biz_trace_id=9939a984; totalRecommendGuideTagCount=15; playRecommendGuideTagNegative=1; playRecommendGuideTagCount=0; __ac_nonce=06a06e8390049f983d39e; __ac_signature=_02B4Z6wo00f01BBxkLgAAIDAnjzmj60P9VwQUZQAAG4hf9; home_can_add_dy_2_desktop=%220%22; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A1920%2C%5C%22screen_height%5C%22%3A1080%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A24%2C%5C%22device_memory%5C%22%3A32%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A50%7D%22; IsDouyinActive=false; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCTnBXWkpTTFpiRzJrYy9EdjNZYUQrR2hscHlYSjR5WFhKQnVhTFQ3SDFFSFFCUVAyRmZCdEhoRWRxZEZjUkpZMzZJczljcDM1U3p6N0RuYnlQbFhoMTg9IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoyfQ%3D%3D; bd_ticket_guard_client_data_v2=eyJyZWVfcHVibGljX2tleSI6IkJOcFdaSlNMWmJHMmtjL0R2M1lhRCtHaGxweVhKNHlYWEpCdWFMVDdIMUVIUUJRUDJGZkJ0SGhFZHFkRmNSSlkzNklzOWNwMzVTeno3RG5ieVBsWGgxOD0iLCJ0c19zaWduIjoidHMuMi5iYTk3YWQ1MmRjODgwOGI4ZjYyNzhiNjcyNGU5OWZhYTU0Y2VkNTlkODJiZGU0Y2VkN2Q1OGZkN2VkNmY0NmE2YzRmYmU4N2QyMzE5Y2YwNTMxODYyNGNlZGExNDkxMWNhNDA2ZGVkYmViZWRkYjJlMzBmY2U4ZDRmYTAyNTc1ZCIsInJlcV9jb250ZW50Ijoic2VjX3RzIiwicmVxX3NpZ24iOiJBeS9HZWdwRlBLcHJnczE5SHhyTkNqS2lYNldXenVxYTlEZllEYm1lTzdFPSIsInNlY190cyI6IiM1eis1WWJsT2xLV05TUWxPR3BORVFUOVlpQURLQWFuZWhWajhaNDRJUDV2Nm8xTllXVndwMFdaZlNLckwifQ%3D%3D; odin_tt=4ac666d6acdfc837140fa348a99070f2d4243179486cb5b2d092e0297510dc70d1b2430cf9531cf277e0c051a56f161cba54a6ebd2101144722b5770c7bd8aee");
        return hashMap;
    }

    /**
     * 获取正则匹配的字符串
     *
     * @param str
     * @param regex
     * @return
     */
    public static String getRegexString(String str, String regex, int group) {
        if (str.equals(regex)) {
            return str;
        }
        // 创建一个 Pattern 对象
        Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        // 创建一个 Matcher 对象
        Matcher matcher = pattern.matcher(str);
        String result = null;
        // 检查是否匹配
        if (matcher.find()) {
            result = matcher.group(group);
        }
        return result;
    }

    public static String decodeUnicode(String input) {
        StringBuilder output = new StringBuilder();
        int i = 0;
        while (i < input.length()) {
            if (i < input.length() - 1 && input.charAt(i) == '\\' && input.charAt(i + 1) == 'u') {
                if (i + 6 <= input.length()) {
                    String hex = input.substring(i + 2, i + 6);
                    try {
                        char c = (char) Integer.parseInt(hex, 16);
                        output.append(c);
                        i += 6;
                        continue;
                    } catch (NumberFormatException e) {
                        log.warn("无效的Unicode转义序列: \\u{}", hex);
                    }
                }
            }
            output.append(input.charAt(i));
            i++;
        }
        return output.toString();
    }
}
