package com.yutou.bilibili.services;

import com.yutou.biliapi.api.UserApi;
import com.yutou.biliapi.bean.live.FollowLive;
import com.yutou.biliapi.bean.live.SpiBean;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.biliapi.bean.user.UserHomeInfoBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliLiveNetApiManager;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.biliapi.net.WebSignManager;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.utils.Log;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Service
public class LiveUserService {
    @Resource
    LiveLoginService userLoginService;
    @Resource
    LiveConfigService configService;

    public List<FollowLive.Room> getUserFollowLive(String userId) {
        try {
            FollowLive followLive = BiliLiveNetApiManager.getInstance().getApi(userId).getUserFollowLive(true, System.currentTimeMillis()).execute().body().getData();
            return followLive.getRooms();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public UserFollowingsBean getUserFollowings(String userId, int page, int num) {
        LoginCookieDatabaseBean cookie = userLoginService.getCookie(userId);
        UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
        try {
            HttpBody<UserFollowingsBean> body = api.getFollowings(cookie.getDedeUserID(), "", num, page).execute().body();
            return body.getData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public UserHomeInfoBean getUserHome(LoginCookieDatabaseBean cookie, String mid, UserInfoBean userInfo, SpiBean spiBean) {
        try {
            TreeMap<String, Object> map = new TreeMap<>();
            map.put("mid", mid);
//            map.put("web_location", "1550101");
//            map.put("dm_img_inter", JSONObject.parseObject("{\"ds\":[],\"wh\":[5746,6797,28],\"of\":[276,552,276]}"));
            map.put("dm_img_list", "[]");
            map.put("dm_img_str", "V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ");
            map.put("dm_cover_img_str", "QU5HTEUgKEFNRCwgQU1EIFJhZGVvbiA3ODBNIEdyYXBoaWNzICgweDAwMDAxNUJGKSBEaXJlY3QzRDExIHZzXzVfMCBwc181XzAsIEQzRDExKUdvb2dsZSBJbmMuIChBTU");
            map = WebSignManager.getWebSign(map, userInfo);
            HashMap<String, String> tmap = new HashMap<>();
            tmap.put("buvid3", spiBean.getB_3());
            tmap.put("buvid4", spiBean.getB_4());
            Response<HttpBody<UserHomeInfoBean>> execute = BiliUserNetApiManager.getInstance().getUserApi(cookie, tmap).getWbiAccInfo(map).execute();
            if (execute.body().getCode() == -352) {
                return null;
            }
            return execute.body().getData();
        } catch (Exception e) {
            Log.e(e);
        }
        return null;
    }

    public int followAnchor(String uid, String anchorUid) {
        try {
            LoginCookieDatabaseBean cookie = BiliBiliLoginDatabase.getInstance().getCookie(uid);
            UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
            UserInfoBean userInfo = api.getUserInfo().execute().body().getData();
            SpiBean spiBean = api.getFingerSpi().execute().body().getData();
            UserHomeInfoBean userHome = getUserHome(cookie, anchorUid, userInfo, spiBean);
            if (userHome == null) {
                return -3;//账号被风控
            }
            if (userHome.getLiveRoom() == null || userHome.getLiveRoom().getRoomid() == 0) {
                return -2;//未开通直播间
            }
            LiveConfigDatabaseBean bean = configService.getConfig(String.valueOf(userHome.getLiveRoom().getRoomid()));
            if (bean != null) {
                return 2;//已关注
            }
            LiveConfigDatabaseBean config = configService.addConfig(userHome.getLiveRoom().getUrl(), new LiveConfigDatabaseBean());
            if (config != null) {
                return 1;
            }
        } catch (Exception e) {
            Log.e(e);
            return -1;//其他异常
        }
        return 0;//添加失败
    }

    public void confirmFollow(String uid) {
        if (followTaskMap.containsKey(uid)) {
            followTaskMap.get(uid).setStop(true);
        }
        followTaskMap.remove(uid);
    }

    public ResultData<UserFollowingsBean.Follow> checkFollow(String uid) {
        if (followTaskMap.containsKey(uid)) {
            return followTaskMap.get(uid).getFollowCount();
        }
        return null;
    }

    private final Map<String, FollowTask> followTaskMap = new HashMap<>();

    public ResultData<UserFollowingsBean.Follow> followAll(String userId, List<UserFollowingsBean.Follow> follows) {
        if (followTaskMap.containsKey(userId)) {
            return followTaskMap.get(userId).getFollowCount();
        }
        FollowTask task = new FollowTask();
        task.setUid(userId);
        task.setFollowList(follows);
        followTaskMap.put(userId, task);
        task.start();

        return task.getFollowCount();
    }

    public ResultData<UserFollowingsBean.Follow> followAll(String userId) {
        return followAll(userId, null);
    }

    private class FollowTask extends Thread {
        @Setter
        private String uid;
        @Setter
        private List<UserFollowingsBean.Follow> followList = null;
        @Getter
        private ResultData<UserFollowingsBean.Follow> followCount = new ResultData<>();
        @Setter
        private boolean isStop = false;

        @Override
        public void run() {
            int page = 1;
            UserFollowingsBean bean = null;
            if (followList == null) {
                bean = getUserFollowings(uid, page, 50);
            } else {
                bean = new UserFollowingsBean();
                bean.setTotal(followList.size());
                bean.setList(followList);

            }
            int count = bean.getList().size();
            while (count != bean.getTotal() && !isStop && followList == null) {
                UserFollowingsBean tmp = getUserFollowings(uid, ++page, 50);
                count += tmp.getList().size();
                bean.getList().addAll(tmp.getList());
            }
            followCount.setCount(bean.getTotal());
            followCount.setStatus(1);
            count = 0;
            for (UserFollowingsBean.Follow follow : bean.getList()) {
                if (isStop) {
                    break;
                }
                if (followAnchor(uid, follow.getMid()) == 1) {
                    followCount.setData(follow);
                    followCount.setMessage(follow.getUname());
                    followCount.setStatus(++count);
                }
            }
            followCount.setStatus(-100);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LiveUserService service = new LiveUserService();
        service.userLoginService = new LiveLoginService();
        service.configService = new LiveConfigService();
        while (service.followAll("96300").getStatus() != 100) {
            System.out.println("关注:" + service.checkFollow("96300"));
            if (service.checkFollow("96300").getStatus() == 10) {
                service.confirmFollow("96300");
                break;
            }

        }
        System.out.println(service.checkFollow("96300"));
    }
}
