package com.yutou.bilibili.services;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LiveApi;
import com.yutou.biliapi.bean.live.LiveAnchorInfo;
import com.yutou.biliapi.bean.live.LiveRoomConfig;
import com.yutou.biliapi.bean.live.LiveRoomInfo;
import com.yutou.biliapi.bean.live.LiveRoomPlayInfo;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.live.database.LiveVideoDatabaseBean;
import com.yutou.biliapi.databases.BiliLiveConfigDatabase;
import com.yutou.biliapi.databases.BiliLiveDatabase;
import com.yutou.biliapi.net.BiliLiveNetApiManager;
import com.yutou.bilibili.Tools.DateFormatUtils;
import com.yutou.bilibili.datas.web.LiveData;
import com.yutou.common.okhttp.BaseBean;
import com.yutou.common.okhttp.HttpLoggingInterceptor;
import com.yutou.common.utils.FFmpegUtils;
import com.yutou.common.utils.Log;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class LiveService {
    BiliLiveConfigDatabase liveConfigDatabase;
    @Resource
    LiveVideoDownloadService videoDownloadService;
    @Resource
    LiveDanmuService danmuService;
    LiveApi api;

    public LiveService() {
        liveConfigDatabase = new BiliLiveConfigDatabase();
        api = BiliLiveNetApiManager.getInstance().getApi(null);
    }

    public int getConfigCount() {
        return liveConfigDatabase.getAllConfig().size();
    }

    public List<LiveData> getLiveList(int page, int limit) {
        List<LiveConfigDatabaseBean> allConfig = liveConfigDatabase.getAllConfig();
        List<LiveData> liveDataList = new ArrayList<>();
        if (allConfig.isEmpty()) {
            return liveDataList;
        }
        JSONArray uids = new JSONArray();
        JSONObject param = new JSONObject();
        for (LiveConfigDatabaseBean bean : allConfig) {
            uids.add(bean.getAnchorUid());
        }
        param.put("uids", uids);
        try {
            Map<String, LiveAnchorInfo> map = api.getLiveRoomStatus(param).execute().body().getData();
            if (map == null) {
                map = new HashMap<>();
            }
            List<LiveAnchorInfo> onlineList = new ArrayList<>();
            List<LiveAnchorInfo> offlineList = new ArrayList<>();
            for (LiveAnchorInfo info : map.values()) {
                if (info.getLiveStatus() == 1) {
                    onlineList.add(info);
                } else {
                    offlineList.add(info);
                }
            }
            onlineList.addAll(offlineList);
            int totalSize = onlineList.size();
            int fromIndex = (page - 1) * limit;
            int toIndex = Math.min(fromIndex + limit, totalSize);
            if (fromIndex >= totalSize) {
                return new ArrayList<>(); // 返回空列表
            }
            List<LiveAnchorInfo> list = onlineList.subList(fromIndex, toIndex);
            for (LiveAnchorInfo info : list) {
                LiveData liveData = new LiveData();
                liveData.setRoomId(info.getRoomId());
                liveData.setAnchorUid(info.getUid());
                liveData.setAnchorName(info.getUname());
                liveData.setAnchorFace(info.getFace());
                if (info.getLiveTime() == 0) {
                    liveData.setLiveTime("未开播");
                } else {
                    liveData.setLiveTime(DateFormatUtils.getInstance().formatMillis(System.currentTimeMillis() - info.getLiveTime() * 1000));
                }
                liveData.setDownloadVideo(videoDownloadService.checkDownload(info.getRoomId()));
                liveData.setDanmu(danmuService.check(info.getRoomId()));
                liveData.setTitle(info.getTitle());
                liveData.setLive(info.getLiveStatus() == 1);
                if (info.getLiveStatus() == 1 && StringUtils.hasText(info.getKeyframe())) {
                    liveData.setCover(info.getKeyframe());
                } else {
                    liveData.setCover(info.getCoverFromUser());
                }
                liveDataList.add(liveData);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return liveDataList;
    }

    public JSONObject getGiftInfo(String roomId, String videoId) {
        BiliLiveDatabase database = new BiliLiveDatabase(LiveRoomConfig.buildConfig(roomId));
        LiveVideoDatabaseBean videoBean = database.getVideo(videoId);
        if (videoBean == null) {
            return null;
        }
        long startTime = videoBean.getStartTime().getTime();
        long endTime = videoBean.getStopTime() == null ? System.currentTimeMillis() : videoBean.getStopTime().getTime();
        return database.getGiftInfo(startTime, endTime);
    }

    public static void main(String[] args) {
        HttpLoggingInterceptor.setLog(true);
        LiveService service = new LiveService();
        List<LiveData> data = service.getLiveList(1, 16);
        System.out.println(data.size());
    }
}
