package com.yutou.qqbot.bilibili;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.bilibili.api.LoginAPI;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.utlis.*;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

public class BiliLogin {

    BiliBiliUtils biliUtils;
    private long qq;


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

    public JSONObject login() {
        JSONObject login = JSON.parseObject(HttpTools.get(LoginAPI.LOGIN_QRCODE));
        JSONObject json = new JSONObject();
        System.out.println("login = " + login);
        json.put("code", login.getInteger("code"));
        json.put("url", login.getJSONObject("data").getString("url"));
        new Thread(() -> waitLogin(login.getJSONObject("data").getString("qrcode_key"))).start();
        return json;
    }

    public void loginAsQQ() {
        String url = login().getString("url");
        File code = QRCodeUtils.createQRCode("bili_login", url);
        QQBotManager.getInstance().sendMessage(code, qq, "B站未登录,请扫码登陆后再试");
    }

    public void waitLogin(String oauthKey) {
        long time = System.currentTimeMillis();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                String bd = "gourl=https%3A%2F%2Fpassport.bilibili.com%2Fajax%2FminiLogin%2Fredirect&oauthKey=" + oauthKey;
                if ((System.currentTimeMillis() - time) > 5 * 60 * 1000) {
                    cancel();
                    return;
                }
                JSONObject json = biliUtils.http_login_getSid(LoginAPI.LOGIN_QRCODE_POLL + "?qrcode_key=" + oauthKey);
                Log.i("B站登陆", json.toJSONString());
                if (json.getInteger("code") == 0 && json.getJSONObject("data").getInteger("code") == 0) {

                    String[] split = json.getString("cookie").split(";");
                    JSONObject ck = new JSONObject();
                    for (String string : split) {
                        if (!ck.containsKey(string) && !StringUtils.isEmpty(string) && string.contains("=")) {
                            String key = string.split("=")[0].trim();
                            String value = string.split("=")[1].trim();
                            if (key.contains("Expires")) {
                                SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMMM yyyy HH:mm:ss z", Locale.ENGLISH);
                                sdf.setTimeZone(TimeZone.getDefault());
                                Date date = sdf.parse(value, new ParsePosition(0));
                                value = String.valueOf(date.getTime() / 1000);
                            }
                            ck.put(key, value);
                        }
                    }
                    ck.put("gourl", bd);
                    ConfigTools.saveFile(new File(qq + "_bilibili.cookie"), ck.toJSONString());
                    cancel();
                }
            }
        }, 1000, 3000);

    }

    public boolean testLogin() {
        if (biliUtils == null) {
            return false;
        }
        JSONObject jsonObject = biliUtils.getLoginInfo();
        return jsonObject.getInteger("code") == 0;
    }

    public static String getCookieToken(Long qq) {
        if (StringUtils.isEmpty(ConfigTools.readFile(new File(qq + "_bilibili.cookie")))) {
            return null;
        }
        JSONObject json = JSON.parseObject(ConfigTools.readFile(new File(qq + "_bilibili.cookie")));
        return json.getString("bili_jct");
    }


    public static void main(String[] args) throws ParseException {
        String http = "{\"code\":0,\"message\":\"0\",\"ttl\":1,\"data\":{\"url\":\"https://passport.biligame.com/x/passport-login/web/crossDomain?DedeUserID=96300&DedeUserID__ckMd5=c506a12068157a3a&Expires=1720252437&SESSDATA=c383a8e0,1720252437,9ba5c*11CjCBp3_j-6zYtK27tzUVrmFZNgjyeDW6pcdfmRBJU5cVfz4OhVmujjKCZsGAkXL6ll8SVnplZ2JONlBleHdFOGgzUzNJYUxIbzJwRVhTYVM2LWVuQnJyQVQxQnRWTUFZbUYybV95Y1RELTdGeF9mNlpXV3RDTjdsMVBaYkhxZGZyblRkTUJCMGV3IIEC&bili_jct=e786885293c24eb7198dc0538b56d6d8&gourl=https%3A%2F%2Fwww.bilibili.com\",\"refresh_token\":\"347b83e7c4a1e24f4681f06f28f71b11\",\"timestamp\":1704700437058,\"code\":0,\"message\":\"\"},\"cookie\":\";SESSDATA=c383a8e0%2C1720252437%2C9ba5c%2A11CjCBp3_j-6zYtK27tzUVrmFZNgjyeDW6pcdfmRBJU5cVfz4OhVmujjKCZsGAkXL6ll8SVnplZ2JONlBleHdFOGgzUzNJYUxIbzJwRVhTYVM2LWVuQnJyQVQxQnRWTUFZbUYybV95Y1RELTdGeF9mNlpXV3RDTjdsMVBaYkhxZGZyblRkTUJCMGV3IIEC; Path=/; Domain=bilibili.com; Expires=Sat, 06 Jul 2024 07:53:57 GMT; HttpOnly; Secure;bili_jct=e786885293c24eb7198dc0538b56d6d8; Path=/; Domain=bilibili.com; Expires=Sat, 06 Jul 2024 07:53:57 GMT;DedeUserID=96300; Path=/; Domain=bilibili.com; Expires=Sat, 06 Jul 2024 07:53:57 GMT;DedeUserID__ckMd5=c506a12068157a3a; Path=/; Domain=bilibili.com; Expires=Sat, 06 Jul 2024 07:53:57 GMT;sid=ger7871m; Path=/; Domain=bilibili.com; Expires=Sat, 06 Jul 2024 07:53:57 GMT\"}";
        JSONObject body = JSON.parseObject(http);
        BiliLogin login = new BiliLogin(583819556L);
        boolean testLogin = login.testLogin();
        System.out.println("testLogin = " + testLogin);
        System.out.println(BiliBiliUtils.getInstance(583819556L).getLoginInfo());
        //JSONObject json = login.login();
        //System.out.println("json = " + json);
        //   QRCodeUtils.createQRCode("bili_login", json.getString("url"));
    }
}
