package com.ruoyi.cai.controller.app;

import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.dto.app.RankIdReq;
import com.ruoyi.cai.dto.app.vo.rank.RankRemark;
import com.ruoyi.cai.dto.app.vo.rank.RankNodeInvite;
import com.ruoyi.cai.dto.app.vo.rank.RankNodeLove;
import com.ruoyi.cai.enums.GenderEnum;
import com.ruoyi.cai.manager.AwardManager;
import com.ruoyi.cai.rank.RankManager;
import com.ruoyi.cai.rank.RankNode;
import com.ruoyi.cai.service.RankService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/rank")
@Tag(name = "排行榜接口")
public class RankAppController {

    @Autowired
    private RankManager rankManager;
    @Autowired
    private UserService userService;
    @Autowired
    private RankService rankService;
    @Autowired
    private AwardManager awardManager;

    @GetMapping("/loveRemark")
    @Operation(summary = "魅力榜榜单说明")
    public R<RankRemark> loveRemark(){
        String remark =
                "(魅力上周榜排名奖励）\n" +
                "第一名：888元\n" +
                "第二名：588元\n" +
                "第三名：388元\n" +
                "第四名：288元\n" +
                "第五名：188元\n" +
                "第六至十名：138元\n" +
                "（魅力昨日榜排名奖励）\n" +
                "第一名：138元\n" +
                "第二名：108元\n" +
                "第三名：88元\n" +
                "第四名：58元\n" +
                "第五名：38元\n" +
                "第六至十名：28元\n" +
                "提示：凡是刷魅力榜的封号，平台拥有对本次活动的最终解释权。";
        RankRemark res = new RankRemark();
        res.setRemark(remark);
        return R.ok(res);
    }

    @GetMapping("/inviteRemark")
    @Operation(summary = "邀请榜榜单说明")
    public R<RankRemark> inviteRemark(){
        String remark =
                "(邀请上周榜排名奖励）\n" +
                "第一名：888元\n" +
                "第二名：588元\n" +
                "第三名：388元\n" +
                "第四名：288元\n" +
                "第五名：188元\n" +
                "第六至十名：138元\n" +
                "（邀请昨日榜排名奖励）\n" +
                "第一名：138元\n" +
                "第二名：108元\n" +
                "第三名：88元\n" +
                "第四名：58元\n" +
                "第五名：38元\n" +
                "第六至十名：28元\n" +
                "提示：凡是刷邀请榜的封号，平台拥有对本次活动的最终解释权。";
        RankRemark res = new RankRemark();
        res.setRemark(remark);
        return R.ok(res);
    }

    @PostMapping("/giveRank")
    @Operation(summary = "领取榜单")
    public R<Void> inviteRank(@RequestBody RankIdReq rankIdReq){
        Long userId = LoginHelper.getUserId();
        awardManager.giveRank(rankIdReq.getRankId(),userId);
        return R.ok();
    }

    @GetMapping("/love")
    @Operation(summary = "魅力榜")
    public R<List<RankNodeLove>> loveRank(
            @Parameter(description = "类型 1-上周 2-昨日 3-日榜 4-周榜 5-月榜 6-总榜") Integer type){
        if(type == null){
            return R.ok(Collections.emptyList());
        }
        List<RankNode> rankNodeList;
        if(type == 1){
            rankNodeList = rankService.getLoveRankLastWeek(10);
        }else if(type == 2){
            rankNodeList = rankService.getLoveRankLastDay(10);
        }else if(type == 3){
            rankNodeList = rankManager.getLoveRankToday(30);
        }else if(type == 4){
            rankNodeList = rankManager.getLoveRankWeek(30);
        }else if(type == 5){
            rankNodeList = rankManager.getLoveRankMonth(30);
        }else if(type == 6){
            rankNodeList = rankManager.getLoveRankTotal(30);
        }else{
            rankNodeList = Collections.emptyList();
        }
        if(rankNodeList.isEmpty()){
            return R.ok(Collections.emptyList());
        }
        List<RankNodeLove> res = new ArrayList<>();
        Set<Long> userIds = rankNodeList.stream().map(RankNode::getUserId).collect(Collectors.toSet());
        List<User> userList = userService.listByIds(userIds);
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        long lastLove = 0;
        for (int i = 0; i < rankNodeList.size(); i++) {
            RankNode rankNode = rankNodeList.get(i);
            User user = userMap.get(rankNode.getUserId());
            if(user == null){
                continue;
            }
            RankNodeLove love = new RankNodeLove();
            love.setUserId(user.getId());
            love.setAvatar(user.getAvatar());
            love.setNickname(user.getNickname());
            love.setValue(rankNode.getScore());
            love.setDraw(rankNode.getDraw() == null || rankNode.getDraw());
            love.setRankId(rankNode.getRankId());
            love.setHide(false);
            if(i == 0){
                love.setDiffLastValue(0L);
            }else{
                love.setDiffLastValue(lastLove - rankNode.getScore());
            }
            lastLove = rankNode.getScore();
            res.add(love);
        }
        return R.ok(res);
    }

    @GetMapping("/invite")
    @Operation(summary = "邀请榜")
    public R<List<RankNodeInvite>> inviteRank(
            @Parameter(description = "类型 1-上周 2-昨日 3-日榜 4-周榜 5-月榜 6-总榜") Integer type){
        if(type == null){
            return R.ok(Collections.emptyList());
        }
        List<RankNode> rankNodeList;
        if(type == 1){
            rankNodeList = rankService.getInviteRankLastWeek(10);
        }else if(type == 2){
            rankNodeList = rankService.getInviteRankLastDay(10);
        }else if(type == 3){
            rankNodeList = rankManager.getInviteRankToday(30);
        }else if(type == 4){
            rankNodeList = rankManager.getInviteRankWeek(30);
        }else if(type == 5){
            rankNodeList = rankManager.getInviteRankMonth(30);
        }else if(type == 6){
            rankNodeList = rankManager.getInviteRankTotal(30);
        }else{
            rankNodeList = Collections.emptyList();
        }
        if(rankNodeList.isEmpty()){
            return R.ok(Collections.emptyList());
        }
        List<RankNodeInvite> res = new ArrayList<>();
        Set<Long> userIds = rankNodeList.stream().map(RankNode::getUserId).collect(Collectors.toSet());
        List<User> userList = userService.listByIds(userIds);
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        long lastLove = 0;
        for (int i = 0; i < rankNodeList.size(); i++) {
            RankNode rankNode = rankNodeList.get(i);
            User user = userMap.get(rankNode.getUserId());
            if(user == null){
                continue;
            }
            RankNodeInvite invite = new RankNodeInvite();
            invite.setAvatar(GenderEnum.WOMEN.getDefaultAvatar());
            invite.setNickname(minNickname(user.getNickname()));
            invite.setValue(rankNode.getScore());
            invite.setDraw(rankNode.getDraw() == null || rankNode.getDraw());
            invite.setRankId(rankNode.getRankId());
            if(i == 0){
                invite.setDiffLastValue(0L);
            }else{
                invite.setDiffLastValue(lastLove - rankNode.getScore());
            }
            lastLove = rankNode.getScore();
            res.add(invite);
        }
        return R.ok(res);
    }

    private static String minNickname(String nickname){
        if(StringUtils.isEmpty(nickname)){
            return "*";
        }
        return "*"+nickname.substring(nickname.length()-1);
    }
}
