package com.yutou.bilibili.Controllers;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.bean.live.FollowLive;
import com.yutou.biliapi.bean.live.database.LiveConfigDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.bilibili.Tools.DateFormatUtils;
import com.yutou.bilibili.Tools.Tools;
import com.yutou.bilibili.datas.ResultData;
import com.yutou.bilibili.datas.ReturnCode;
import com.yutou.bilibili.services.LiveConfigService;
import com.yutou.bilibili.services.LiveLoginService;
import com.yutou.bilibili.services.LiveUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/live/config/")
public class LiveConfigController {
    @Resource
    LiveConfigService configService;
    @Resource
    LiveUserService userService;
    @Resource
    LiveLoginService loginService;


    @ResponseBody
    @RequestMapping("follow")
    public JSONObject getFollow(String userId, int page, int limit) {
        UserFollowingsBean bean = userService.getUserFollowings(userId, page, limit);
        if (bean == null) {
            return ResultData.fail(ReturnCode.RC999);
        }
        return ResultData.success(bean, bean.getTotal());
    }

    @ResponseBody
    @RequestMapping("followLive")
    public JSONObject getFollowLive(String userId) {
        List<FollowLive.Room> followLive = userService.getUserFollowLive(userId);
        if (followLive == null) {
            return ResultData.fail(ReturnCode.RC999);
        }
        followLive.forEach(item -> item.setLiveTime(DateFormatUtils.getInstance().convertSeconds(Long.parseLong(item.getLiveTime()))));
        return ResultData.success(followLive, followLive.size());
    }

    @ResponseBody
    @RequestMapping("follow/add")
    public JSONObject addFollow(String uid, String anchorId) {
        int flag = userService.followAnchor(uid, anchorId);
        if (flag == 1) {
            return ResultData.success(ReturnCode.RC100);
        } else {
            return switch (flag) {
                case 0 -> ResultData.fail(-flag, "关注失败");
                case -1 -> ResultData.fail(-flag, "关注失败，程序异常");
                case -2 -> ResultData.fail(-flag, "关注失败，UP未开通直播间");
                case -3 -> ResultData.fail(-flag, "账号可能被风控,请从配置页手动配置");
                case 2 -> ResultData.fail(-flag, "已在关注列表");
                default -> ResultData.fail(ReturnCode.RC999);
            };
        }
    }

    @ResponseBody
    @RequestMapping("follow/addList")
    public JSONObject addFollowList(String uid, String array) {
        if (!StringUtils.hasText(array)) {
            return ResultData.fail(ReturnCode.RC500);
        }
        JSONArray jsonArray = JSONArray.parseArray(array);
        List<UserFollowingsBean.Follow> list = jsonArray.stream()
                .map(o -> {
                    JSONObject jsonObject = (JSONObject) o;
                    UserFollowingsBean.Follow follow = new UserFollowingsBean.Follow();
                    follow.setMid(jsonObject.getString("mid"));
                    follow.setUname(jsonObject.getString("uname"));
                    return follow;
                }).toList();
        return ResultData.success(userService.followAll(uid, list));
    }

    @ResponseBody
    @RequestMapping("follow/roomId/addList")
    public JSONObject addFollowListToRoomId(String array) {
        if (!StringUtils.hasText(array)) {
            return ResultData.fail(ReturnCode.RC500);
        }
        JSONArray jsonArray = JSONArray.parseArray(array);
        List<LiveConfigDatabaseBean> list = jsonArray.stream().map(o -> {
            JSONObject jsonObject = (JSONObject) o;
            return configService.addConfig(jsonObject.getString("roomId"), new LiveConfigDatabaseBean());
        }).toList();
        return ResultData.success(list, list.size());
    }

    @ResponseBody
    @RequestMapping("follow/check")
    public JSONObject checkFollow(String userId) {
        List<ResultData<String>> list = new ArrayList<>();
        if (StringUtils.hasText(userId)) {
            list.add(getFollowStatus(userId, userService.checkFollow(userId)));
        } else {
            for (LoginUserDatabaseBean user : loginService.getAllUser()) {
                list.add(getFollowStatus(user.getUserInfo().getMid(), userService.checkFollow(user.getUserInfo().getMid())));
            }
        }
        return ResultData.success(list);

    }

    @ResponseBody
    @RequestMapping("follow/all")
    public JSONObject getAllFollow(String userId) {
        return ResultData.success(userService.followAll(userId));
    }

    @ResponseBody
    @RequestMapping("follow/confirm")
    public JSONObject confirmAllFollow(String userId) {
        userService.confirmFollow(userId);
        return ResultData.success(ReturnCode.RC100);
    }

    @RequestMapping(value = "set/array", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject addArrayConfig(@RequestBody JSONObject jsonObject) {
        LiveConfigDatabaseBean bean = jsonObject.getJSONObject("config").to(LiveConfigDatabaseBean.class);
        if (!bean.verifyLiveTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "视频录制时间格式错误");
        }
        if (!bean.verifyDanmuTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "弹幕录制时间格式错误");
        }
        JSONArray jsonArray = jsonObject.getJSONArray("array");
        List<LiveConfigDatabaseBean> list = jsonArray.stream().map(roomId -> configService.addConfig(roomId.toString(), bean)).toList();
        int countNull = list.stream().filter(Objects::isNull).toList().size();
        return ResultData.success("成功配置" + (list.size() - countNull) + "个直播间");
    }

    @RequestMapping(value = "delete/array", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteArrayConfig(@RequestBody JSONArray jsonArray) {
        List<Boolean> list = jsonArray.stream().map(roomId -> configService.deleteConfig(roomId.toString())).toList();
        int countNull = list.stream().filter(it -> !it).toList().size();
        return ResultData.success("成功删除" + (list.size() - countNull) + "个直播间");
    }
    @RequestMapping(value = "delete/all", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject deleteAllConfig() {
        for (LiveConfigDatabaseBean bean : configService.getAllConfig()) {
            configService.deleteConfig(bean.getRoomId());
        }
        if(configService.getAllConfig().isEmpty()) {
            return ResultData.success("成功删除");
        }else{
            return ResultData.fail(-1,"删除失败,剩余:"+configService.getAllConfig().size()+"个直播间");
        }
    }

    @RequestMapping(value = "set", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject setConfig(String url, LiveConfigDatabaseBean bean) {
        if (!bean.verifyLiveTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "视频录制时间格式错误");
        }
        if (!bean.verifyDanmuTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "弹幕录制时间格式错误");
        }
        if (!url.startsWith("https://live.bilibili.com/")) {
            if (!configService.checkUrl(url)) {
                return ResultData.fail(ReturnCode.RC999.getCode(), "房间地址/房间号错误");
            }
        }
        LiveConfigDatabaseBean config = configService.addConfig(url, bean);
        if (config != null) {
            return ResultData.success(config.toJson());
        }
        return ResultData.fail(ReturnCode.RC999);
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateConfig(String roomId, LiveConfigDatabaseBean bean) {
        if (!bean.verifyLiveTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "视频录制时间格式错误");
        }
        if (!bean.verifyDanmuTimer()) {
            return ResultData.fail(ReturnCode.RC999.getCode(), "弹幕录制时间格式错误");
        }

        LiveConfigDatabaseBean config = configService.updateConfig(new String(roomId), bean);
        if (config != null) {
            return ResultData.success(config.toJson());
        }
        return ResultData.fail(ReturnCode.RC999);
    }

    @RequestMapping(value = "get", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getConfig(String roomId) {
        if ("0".equals(roomId) || !StringUtils.hasText(roomId)) {
            return ResultData.fail(ReturnCode.RC999);
        }
        LiveConfigDatabaseBean config = configService.getConfig(roomId);
        if (config != null) {
            return ResultData.success(config);
        }
        return ResultData.fail(ReturnCode.RC999);
    }

    @RequestMapping(value = "all", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getAllConfig(int page, int limit) {
        List<LiveConfigDatabaseBean> config;
        if (page == -1 || limit == -1) {
            config = configService.getAllConfig();
        } else {
            config = configService.getConfigs(page, limit);
        }
        if (config != null) {
            return ResultData.success(config, configService.getConfigCount());
        }
        return ResultData.fail(ReturnCode.RC999);
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject deleteConfig(String roomId) {
        if ("0".equals(roomId) || !StringUtils.hasText(roomId)) {
            return ResultData.fail(ReturnCode.RC999);
        }
        boolean flag = configService.deleteConfig(roomId);
        if (flag) {
            return ResultData.success(ReturnCode.RC100);
        }
        return ResultData.fail(ReturnCode.RC999);
    }

    @RequestMapping(value = "face", method = RequestMethod.GET)
    public ResponseEntity<FileSystemResource> getFace(String roomId) {
        return Tools.getFile(configService.getFace(roomId));
    }

    private ResultData<String> getFollowStatus(String userId, ResultData<UserFollowingsBean.Follow> follow) {
        ResultData<String> resultData = new ResultData<>();
        resultData.setData(userId);
        if (follow == null) {
            resultData.setMessage(userId + ":没有相关任务");
            resultData.setStatus(-1);
            return resultData;
        }
        resultData.setCount(follow.getCount());
        if (follow.getStatus() == -100) {
            resultData.setMessage(userId + ":处理完成");
            resultData.setStatus(-100);
        } else {
            if (follow.getData() == null) {
                resultData.setMessage(userId + ":正在等待");
            } else {
                resultData.setMessage(userId + ":正在处理:" + follow.getData().getUname() + "(" + follow.getStatus() + "/" + follow.getCount() + ")");
            }
            resultData.setStatus(follow.getStatus());
        }
        return resultData;
    }
}
