package com.yutou.qqbot.bilibili;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.bilibili.BaseAPI;
import com.yutou.bilibili.api.LiveAPI;
import com.yutou.bilibili.api.VideoApi;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.models.BiliBili.BiliVideo;
import com.yutou.qqbot.utlis.AppTools;
import com.yutou.qqbot.utlis.BiliBiliWbiSign;
import com.yutou.qqbot.utlis.HttpTools;

import javax.net.ssl.HttpsURLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class BiliBiliAppUtils {
    private static final String AppKey = "1d8b6e7d45233436";
    private static final String AppSec = "560c52ccd288fed045859ed18bffd973";

    private BiliBiliUtils biliUtils;

    public BiliBiliAppUtils(Long qq) {
        biliUtils = BiliBiliUtils.getInstance(qq);
    }

    public String getAccessToken() {
        try {
            String tmpUrl = BaseAPI.MCBBS_PNG;
            String sign = AppTools.getMD5("api=" + tmpUrl + AppSec);
            JSONObject get = biliUtils.http_get(BaseAPI.ACCESS_TOKEN+"?appkey=" + AppKey + "&api=" + tmpUrl + "&sign=" + sign);
            assert get != null;
            String uri = get.getJSONObject("data").getString("confirm_uri");
            HttpsURLConnection connection = biliUtils.getBiliHttpGet(uri, biliUtils.getCookie());
            connection.connect();
            if (connection.getResponseCode() == 200) {
                Map<String, String> params = HttpTools.getUrlParams(connection.getURL().toString());
                return params.get("access_key");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map<String, String> sign(Map<String, String> map) {
        map.putAll(getDefaultBody());
        map = sort(map);
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            builder.append(key).append("=").append(map.get(key)).append("&");
        }
        String param = builder.substring(0, builder.length() - 1);
        map.put("sign", AppTools.getMD5(param + AppSec));
        return map;
    }

    private Map<String, String> getDefaultBody() {
        Map<String, String> map = new TreeMap<>();
        map.put("access_key", getAccessToken());
        map.put("actionKey", "appkey");
        map.put("appkey", AppKey);
        map.put("build", "7120200");
        map.put("c_locale", "zh_CN");
        map.put("channel", "xiaomi_cn_tv.danmaku.bili_20210930");
        map.put("device", "android");
        map.put("disable_rcmd", "0");
        map.put("mobi_app", "android");
        map.put("platform", "android");
        map.put("s_locale", "zh_CN");
        map.put("statistics", URLEncoder.encode("{\"appId\":1,\"platform\":3,\"version\":\"7.12.0\",\"abtest\":\"\"}", Charset.defaultCharset()));
        map.put("ts", (System.currentTimeMillis() / 1000) + "");
        return map;
    }

    private LinkedHashMap<String, String> sort(Map<String, String> map) {
        return new LinkedHashMap<>(new TreeMap<>(map));
    }

    private Map<String, String> getHeaderMap() {
        String md5_1 = AppTools.getMD5(System.currentTimeMillis() + "");
        String md5_2 = AppTools.getMD5(System.currentTimeMillis() + "");
        String trace_id = md5_1 + ":" + md5_2.substring(0, 16) + ":0:0";
        Map<String, String> map = new TreeMap<>();
        map.put("x-bili-mid", "96300");
        map.put("x-bili-trace-id", trace_id);
        map.put("x-bili-aurora-zone", "");
        map.put("x-bili-aurora-eid", "WFICRlE=");
        map.put("APP-KEY", "android64");
        map.put("bili-http-engine", "cronet");
        map.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        map.put("session_id", md5_1.substring(0, 8));
        map.put("Host", "api.live.bilibili.com");
        map.put("Connection", "keep-alive");
        map.put("fp_local", md5_1 + md5_2);
        map.put("fp_remote", md5_1 + md5_2);
        map.put("env", "prod");
        map.put("buvid", "XUF43FCF17D1747514C79C6D3D43B64C8D1B2");
        map.put("Accept-Encoding", "gzip, deflate, br");
        map.put("User-Agent", "Mozilla/5.0 BiliDroid/7.4.0 (bbcallen@gmail.com) os/android model/22061218C mobi_app/android build/7040300 channel/xiaomi_cn_tv.danmaku.bili_20210930 innerVer/7040310 osVer/12 network/2");
        return map;
    }

    public AppUserTask getTaskProgress() {
        JSONObject task = biliUtils.http_get(LiveAPI.LIVE_TASK_PROGRESS);
        System.out.println("task = " + task);
        assert task != null;
        return task.getObject("data", AppUserTask.class);
    }

    private void setUserTaskProgress(int index) {
        Map<String, String> map = new TreeMap<>();
        map.put("target_id", "33989");
        map.put("reward_index", index + "");

        JSONObject httpGet = biliUtils.http(
                LiveAPI.LIVE_SET_TASK_PROGRESS,
                BiliBiliUtils.HTTP.POST,
                HttpTools.toUrlParams(sign(map)),
                getHeaderMap(),
                BiliBiliUtils.RET_MODEL.JSON
        );
        System.out.println("任务 " + index + " :" + httpGet);
    }

    public AppUserTask startAppTask() {
        AppUserTask task = getTaskProgress();
        if (task.getDayTask().getStatus() == 2) {
            setUserTaskProgress(0);
        }
        List<AppUserTask.WeekTask> taskList = task.getWeekTask();
        taskList.forEach(weekTask -> {
            if (weekTask.getStatus() == 2) {
                setUserTaskProgress(weekTask.getId());
            }
        });
        return task;
    }
    public static String getVideoAI(String url){
        if(url.startsWith("https://b23.tv")){
            url=b23ToUrl(url);
        }
        JSONObject videoInfo = new BiliVideo().getVideoInfo(url);
        if(videoInfo==null){
            return null;
        }
        String cid = videoInfo.getJSONObject("data").getString("cid");
        TreeMap<String,String> body=new TreeMap<>();
        body.put("cid",cid);
        body.put("up_mid",videoInfo.getJSONObject("data").getJSONObject("owner").getString("mid"));
        body.put("bvid",videoInfo.getJSONObject("data").getString("bvid"));
        BiliBiliWbiSign.getWbiSign(body);
        JSONObject object = BiliBiliUtils.getInstance(QQBotManager.defQQ)
                .http_get(VideoApi.VIDEO_AI +"?"+HttpTools.toUrlParams(body));
        if(object.getInteger("code")==0){
            if(object.getJSONObject("data").getInteger("code")==0) {
                return object.getJSONObject("data").getJSONObject("model_result").getString("summary");
            }else{
                return "没得省流";
            }
        }
        return null;
    }
    public static String b23ToUrl(String url){
        try {
            HttpsURLConnection connection = BiliBiliUtils.getInstance(QQBotManager.defQQ).getBiliHttpGet(url, BiliBiliUtils.getInstance(QQBotManager.defQQ).getCookie());
            connection.setInstanceFollowRedirects(false);
            connection.connect();
            if(connection.getResponseCode()==302){
                connection.setConnectTimeout(5000);
                return connection.getHeaderField("Location");
            }
            return connection.getURL().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        BiliBiliWbiSign.updateRawWbiKey();
        String url="https://b23.tv/NtqDorB?share_medium=android&share_source=qq&bbid=XUDCA4BDD60B5853ACDC17794BFAEF91F874A&ts=1705470976484";
       // url="https://www.bilibili.com/video/BV1fw411E75p/?buvid=XUDCA4BDD60B5853ACDC17794BFAEF91F874A&from_spmid=tm.recommend.0.0&is_story_h5=false&mid=7G8S%2B4e7nx6XSaU3oMQKXA%3D%3D&p=1&plat_id=116&share_from=ugc&share_medium=android&share_plat=android&share_session_id=ab27db6e-47a5-43b5-b0ec-b027bcfdeccc&share_source=QQ&share_tag=s_i&spmid=main.ugc-video-detail.0.0&timestamp=1705470976&unique_k=NtqDorB&up_id=1156809979";
        String ai = getVideoAI(url);
        System.out.println("ai = " + ai);
    }
}
