package com.nexo.module.api.douyin.utils;

import com.alibaba.fastjson2.JSONObject;
import com.nexo.common.core.utils.OkHttpClientUtils;
import com.nexo.module.api.douyin.domain.NexoDouyinUserInfo;
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.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class DouYinUtils {

    public static NexoDouyinUserInfo getUserInfo(String secuid, String path) {
        NexoDouyinUserInfo item = new NexoDouyinUserInfo();
        String params = "?device_platform=webapp&aid=6383&channel=channel_pc_web&publish_video_strategy_type=2&source=channel_pc_web&sec_user_id=" + secuid + "&personal_center_strategy=1&profile_other_record_enable=1&land_to=1&update_version_code=170400&pc_client_type=1&pc_libra_divert=Windows&support_h265=0&support_dash=1&cpu_core_num=24&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=Win32&browser_name=Edge&browser_version=148.0.0.0&browser_online=true&engine_name=Blink&engine_version=148.0.0.0&os_name=Windows&os_version=10&device_memory=32&platform=PC&downlink=10&effective_type=4g&round_trip_time=50&webid=7639313678160397875";
        String aBogus = DouYinUtils.getABogus(params, path);
        String url = "https://www.douyin.com/aweme/v1/web/user/profile/other/" + params + "&a_bogus=" + aBogus + "&verifyFp=verify_mp4xmi43_R2ZADT9W_IKha_4C4e_9b3a_ctEUtT2EsPOe&fp=verify_mp4xmi43_R2ZADT9W_IKha_4C4e_9b3a_ctEUtT2EsPOe";
        log.info("请求地址：{}", url);
        Map<String, String> header = DouYinUtils.getHeader();
        log.info("请求头：{}", JSONObject.toJSONString(header));
        String reqStr = OkHttpClientUtils.doGet(url, null, header);
        // 解析json
        try {
            JSONObject reqJson = JSONObject.parseObject(reqStr);
            log.info("用户信息：{}", reqJson);
            item.setUserId(reqJson.getJSONObject("user").getString("uid"));
            item.setSecUid(reqJson.getJSONObject("user").getString("sec_uid"));
            item.setUniqueId(reqJson.getJSONObject("user").getString("unique_id"));
            item.setNickname(reqJson.getJSONObject("user").getString("nickname"));
            item.setSignature(reqJson.getJSONObject("user").getString("signature"));
            item.setIpLocation(reqJson.getJSONObject("user").getString("ip_location"));
            item.setAvatar(reqJson.getJSONObject("user").getJSONObject("avatar_medium").getJSONArray("url_list").getString(0));
            item.setLiveStatus(reqJson.getJSONObject("user").getLong("live_status"));
            item.setUserAge(reqJson.getJSONObject("user").getLong("user_age"));
            item.setTotalFavorited(reqJson.getJSONObject("user").getLong("total_favorited"));
            item.setFollowerCount(reqJson.getJSONObject("user").getLong("follower_count"));
            item.setFollowingCount(reqJson.getJSONObject("user").getLong("following_count"));
            item.setAwemeCount(reqJson.getJSONObject("user").getLong("aweme_count"));
            item.setCoverUrl(reqJson.getJSONObject("user").getJSONArray("cover_url").getJSONObject(0).getJSONArray("url_list").getString(0));
            item.setRoomId(reqJson.getJSONObject("user").getString("room_id"));
        } catch (Exception e) {
            throw new RuntimeException("查询用户信息时解析失败");
        }
        return item;
    }


    public static String getABogus(String prams, String path) {
        // 创建脚本引擎管理器
        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();
        }
        // 执行JS文件
        try {
            engine.eval(new FileReader(path));
        } 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", "__live_version__=%221.1.5.2026%22; live_use_vvc=%22false%22; enter_pc_once=1; UIFID_TEMP=ee69abbd54cdddb154b01110285f038c0f724c22a9fa6fa6ff8c47d6ab1f845cd288006b385faaf7b8a06744b30d5e0f13041b4a1e76d608c80b551a3410e9fd0e9220d933598f67dcf50896270312c4; s_v_web_id=verify_mpfflhpy_KDyypjKP_ntwT_4vKi_83tJ_FCY0B144nsdC; dy_swidth=1920; dy_sheight=1080; fpk1=U2FsdGVkX1+1pSHNzM3+AxJpec9fXS+sQDNAWBiBH/MnnFo5s5L0RZDaTbnrjkaIWmABvcq3jPWIDJh3N/sUQg==; fpk2=d782f8d891caba24ff6aeba315180cac; is_dash_user=1; UIFID=ee69abbd54cdddb154b01110285f038c0f724c22a9fa6fa6ff8c47d6ab1f845cd288006b385faaf7b8a06744b30d5e0fc392b3595bf8c12670e555bb7d639cd27631b69e4976fb9761962854a37db4ae13eb1f8c29a6f4d5ce02a15cd3bd6ace5021238750fd7eeba4521527198911e2b74a799ccd6869f89ae333150cd89ead559283b0fea47c6f7620e7712da286266e43c2d6a34337b591644300a35e852d; passport_csrf_token=e4446a3655f4099d12eeb733ae77dbfa; passport_csrf_token_default=e4446a3655f4099d12eeb733ae77dbfa; bd_ticket_guard_client_web_domain=2; download_guide=%223%2F20260521%2F0%22; passport_assist_user=CkE3bkbFO7udAtnZcJPDLZPgJ5ys0d0uz56yB1YsCXKI4XB_6sXglhpQfmZIlDztbJQa7S_XYu3MGbHb8By-JzfIKxpKCjwAAAAAAAAAAAAAUHK2qdrD9tMR7msWkYhFzVyVMiCTF19PUGajET14_rTiJvWL75s9_4-MO133dLKzP6wQ84WSDhiJr9ZUIAEiAQPG_aBz; n_mh=MIpuP22A7OmnsYKF5cQN0IEki-ybyOrsMEeiF02bm4M; sid_guard=a0c71d817d1ba1fca6a7366afac36e74%7C1779369122%7C5184000%7CMon%2C+20-Jul-2026+13%3A12%3A02+GMT; uid_tt=d8b1fb3cb218bfc2d98083c7fca2d37a; uid_tt_ss=d8b1fb3cb218bfc2d98083c7fca2d37a; sid_tt=a0c71d817d1ba1fca6a7366afac36e74; sessionid=a0c71d817d1ba1fca6a7366afac36e74; sessionid_ss=a0c71d817d1ba1fca6a7366afac36e74; session_tlb_tag=sttt%7C6%7CoMcdgX0bofympzZq-sNudP_________EliQ1uagNw70PU8o8NIMK_axbMCnwmqK_jy_HXsebtVg%3D; is_staff_user=false; has_biz_token=false; sid_ucp_v1=1.0.0-KGE3NjljNWM3MzZlZjVkYmUwOTRiMGI1YjkyOGY2YzUwODM1Njk0YjgKIQick6CK_c2hAxCiibzQBhjvMSAMML6o9LcGOAdA9AdIBBoCaGwiIGEwYzcxZDgxN2QxYmExZmNhNmE3MzY2YWZhYzM2ZTc0; ssid_ucp_v1=1.0.0-KGE3NjljNWM3MzZlZjVkYmUwOTRiMGI1YjkyOGY2YzUwODM1Njk0YjgKIQick6CK_c2hAxCiibzQBhjvMSAMML6o9LcGOAdA9AdIBBoCaGwiIGEwYzcxZDgxN2QxYmExZmNhNmE3MzY2YWZhYzM2ZTc0; _bd_ticket_crypt_cookie=2fa3bea575ff4706cf079c9c43e3526e; __security_server_data_status=1; login_time=1779369122709; publish_badge_show_info=%220%2C0%2C0%2C1779369124132%22; my_rd=2; SelfTabRedDotControl=%5B%5D; live_private_user=0; PhoneResumeUidCacheV1=%7B%221836664670914972%22%3A%7B%22time%22%3A1779369642605%2C%22noClick%22%3A1%7D%7D; volume_info=%7B%22isMute%22%3Afalse%2C%22isUserMute%22%3Afalse%2C%22volume%22%3A0.5%7D; __druidClientInfo=JTdCJTIyY2xpZW50V2lkdGglMjIlM0ExNzUyJTJDJTIyY2xpZW50SGVpZ2h0JTIyJTNBODU4JTJDJTIyd2lkdGglMjIlM0ExNzUyJTJDJTIyaGVpZ2h0JTIyJTNBODU4JTJDJTIyZGV2aWNlUGl4ZWxSYXRpbyUyMiUzQTElMkMlMjJ1c2VyQWdlbnQlMjIlM0ElMjJNb3ppbGxhJTJGNS4wJTIwKFdpbmRvd3MlMjBOVCUyMDEwLjAlM0IlMjBXaW42NCUzQiUyMHg2NCklMjBBcHBsZVdlYktpdCUyRjUzNy4zNiUyMChLSFRNTCUyQyUyMGxpa2UlMjBHZWNrbyklMjBDaHJvbWUlMkYxNDguMC4wLjAlMjBTYWZhcmklMkY1MzcuMzYlMjBFZGclMkYxNDguMC4wLjAlMjIlN0Q=; FOLLOW_RED_POINT_INFO=%221%22; live_debug_info=%7B%22roomId%22%3A%227642876793640225572%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%3A11%2C%22videoBuffer%22%3A%5B%5D%2C%22src%22%3A%22https%3A%2F%2Fpull-hs-f5.flive.douyincdn.com%2Fthird%2Fstream-407650326641115819_ld.flv%3Fexpire%3D1780108966%26sign%3D7c5dd7a4fcbd1752bf19d1a89bc0df63%26volcSecret%3D7c5dd7a4fcbd1752bf19d1a89bc0df63%26volcTime%3D1780108966%26neq%3D1%26arch_hrchy%3Dw1%26exp_hrchy%3Dw1%26major_anchor_level%3Dcommon%26unique_id%3Dstream-407650326641115819_683_flv_ld%26t_id%3D037-2026052310424683EB1625576F2876A1F9-FYAlNo%26biz_quality%3Dld%26biz_protocol%3Dflv%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%2F91022741723%3Fanchor_id%3D%22%7D; live_can_add_dy_2_desktop=%221%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; __security_mc_1_s_sdk_crypt_sdk=45800f64-40d2-80a3; __security_mc_1_s_sdk_cert_key=c7922efc-49ef-9b3b; __security_mc_1_s_sdk_sign_data_key_web_protect=2477cd8a-44c2-9528; strategyABtestKey=%221779768431.165%22; ttwid=1%7C1mHAtWHkBQCSjgTpkatZZ3kjYkU_0o2RkKBVLcQ1dS8%7C1779768422%7C51449018df78289fda355847932e8de789f28937eff16c708c8d6bf606d7a2b6; FOLLOW_LIVE_POINT_INFO=%22MS4wLjABAAAALSIgU7MFq8KK0DblB6_a65JZTLhc6wINrwUTO2mSIJ0lMnntlVyxkCi_ob3vhA6W%2F1779811200000%2F0%2F0%2F1779780939496%22; is_support_rtm_web_ts=1; biz_trace_id=d466d9d2; sdk_source_info=7e276470716a68645a606960273f276364697660272927676c715a6d6069756077273f276364697660272927666d776a68605a607d71606b766c6a6b5a7666776c7571273f275e58272927666a6b766a69605a696c6061273f27636469766027292762696a6764695a7364776c6467696076273f275e582729277672715a646971273f2763646976602729277f6b5a666475273f2763646976602729276d6a6e5a6b6a716c273f2763646976602729276c6b6f5a7f6367273f27636469766027292771273f2734333d313430343c323c323234272927676c715a75776a716a666a69273f2763646976602778; bit_env=-SU6xbSYpn9NDo-z8yILJlL_78Yl9sfymO9rF6mrbq3mKEpHxFB-nh54TOlucL4IAw4E0tOvOyB-eTj3TbifoGatzni02eXUt4991e0WvtMW2ikF4xreW5lr82oytjnoLemdmr-Hx-yR10nkthhmHVUgY9c2lPwmqs4h6CaWd7iSaP4R8-5sIZJY4mMnIHmMdr1Yi2uZgUgcWW1BJjvTj92Q7nlnvCAJWL340pJilkUSAc1uamFH706TMx1AUNa6blAN-qW4S7kGsMU3xZcIGYgJbF7BA0Zwmz6AC-_JMEqWvDpMMJWTdMdTzZQ_Vz4JeJLAfpHAXfv81B3accqFSs88tTueEnQxvo_hTTjfZCcJayST3tczsmmT2ICUj7sOnRsxS_jn_tBipWWtcoaCc79ThOTEZSB5-imFHlj34NAkSvbpckA58MqdBF-BjOV8K5V9pmtHSccUyA4ZVqCg-MBG1R1Yf0TVwpNaKdr7Pq-UB121Hp3vrdJF2TKrkt0O3UCDn5jHCPKmAjZ0nlATylAF9HUA2B2PiLowSnhmf0Y%3D; gulu_source_res=eyJwX2luIjoiMDM5NTkxYTlhNTA5ZWZjZTcyNGNiODBkODlkYjA1MzhiZWI3MTY2MGUxYTI2YWRiY2Q4MjNlYjY3M2Y5NmZjNCJ9; passport_auth_mix_state=j5anvvabb3qlv1cfqkqfgpad24nlpi1j45qlorka0f49jjcv; __ac_nonce=06a15777b00a5152c509f; __ac_signature=_02B4Z6wo00f01HOdw7QAAIDA.dC1g3PvrnRzvccAAHb5b1; IsDouyinActive=true; odin_tt=f4652b9ba185a06b61827c8e3f337b8457e3ed001a34ff3a8808e8e8498fcdd5c8927eb2f68b31d1e27e4f34e7fcb86c714bb44e88722642a64657655e745c29; home_can_add_dy_2_desktop=%221%22; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCS1NmZVdUL2dsVnU4UjdNdTV4Y2dBYzZJQUNTVnBjd1FMbFpEdEFhWGZYRWdSVUlWTnNYMGxUSmFKRS93WkVBejRIQkJpc05uRzRibUQ4WlhuWFB1Mm89IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoyfQ%3D%3D; FOLLOW_NUMBER_YELLOW_POINT_INFO=%22MS4wLjABAAAALSIgU7MFq8KK0DblB6_a65JZTLhc6wINrwUTO2mSIJ0lMnntlVyxkCi_ob3vhA6W%2F1779811200000%2F0%2F0%2F1779792950629%22; bd_ticket_guard_client_data_v2=eyJyZWVfcHVibGljX2tleSI6IkJLU2ZlV1QvZ2xWdThSN011NXhjZ0FjNklBQ1NWcGN3UUxsWkR0QWFYZlhFZ1JVSVZOc1gwbFRKYUpFL3daRUF6NEhCQmlzTm5HNGJtRDhaWG5YUHUybz0iLCJ0c19zaWduIjoidHMuMi40MTRmYjM5OGE5OWM1YTBiMzU3ODg5N2M2ZWE1N2UwYWM4ODBkZGFiNDZmN2ExMzJlNDhlNDZmOWIxOTE4ZTdmYzRmYmU4N2QyMzE5Y2YwNTMxODYyNGNlZGExNDkxMWNhNDA2ZGVkYmViZWRkYjJlMzBmY2U4ZDRmYTAyNTc1ZCIsInJlcV9jb250ZW50Ijoic2VjX3RzIiwicmVxX3NpZ24iOiI1YnRVNXYwY0ExRXRIRlhlMFZSOS9KTWRQSjVySTNxT3VzdmliQnZXZ3RJPSIsInNlY190cyI6IiNvalZ2QlpoZ1g3RWhUL1ExZzBPRnBjSmpLMVFoeGVYemdmQTY4NUg2UHZiZ0pObGMwb0VEckQzZ29PNHgifQ%3D%3D");
        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();
    }
}
