package com.linearpast.minecraftmanager.controller;

import com.linearpast.minecraftmanager.entity.Operators;
import com.linearpast.minecraftmanager.entity.Players;
import com.linearpast.minecraftmanager.entity.view.PlayerInfoView;
import com.linearpast.minecraftmanager.service.inter.PlayersService;
import com.linearpast.minecraftmanager.utils.Result;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/whitelist")
public class WhitelistController {

    @Autowired
    private PlayersService playersService;

    /**
     * 获取白名单列表（已通过的玩家，status=1）
     */
    @GetMapping("/list")
    public Result<?> getWhitelist(
            @RequestParam(required = false) String playerName,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        Page<PlayerInfoView> players = playersService.getPlayers(
                playerName, null, null, (byte) 1,
                null, null, PageRequest.of(page - 1, size)
        );
        return Result.successPage(players.getContent(), players.getTotalElements());
    }

    /**
     * 获取待审核列表（status=2）
     */
    @GetMapping("/pending")
    public Result<?> getPending(
            @RequestParam(required = false) String playerName,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        Page<PlayerInfoView> players = playersService.getPlayers(
                playerName, null, null, (byte) 2,
                null, null, PageRequest.of(page - 1, size)
        );
        return Result.successPage(players.getContent(), players.getTotalElements());
    }

    /**
     * 获取被拒绝列表（status=0）
     */
    @GetMapping("/rejected")
    public Result<?> getRejected(
            @RequestParam(required = false) String playerName,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        Page<PlayerInfoView> players = playersService.getPlayers(
                playerName, null, null, (byte) 0,
                null, null, PageRequest.of(page - 1, size)
        );
        return Result.successPage(players.getContent(), players.getTotalElements());
    }

    /**
     * 通过审核（加入白名单）
     */
    @PostMapping("/approve/{id}")
    public Result<?> approve(@PathVariable Integer id, HttpSession session) {
        Operators operators = (Operators) session.getAttribute("adminAccount");
        int code = playersService.updatePlayerStatus(id, (byte) 1, operators);
        return code > 0 ? Result.success().msg("已加入白名单") : Result.error("操作失败，Rcon连接错误或玩家不存在");
    }

    /**
     * 拒绝申请
     */
    @PostMapping("/reject/{id}")
    public Result<?> reject(@PathVariable Integer id, HttpSession session) {
        Operators operators = (Operators) session.getAttribute("adminAccount");
        int code = playersService.updatePlayerStatus(id, (byte) 0, operators);
        return code > 0 ? Result.success().msg("已拒绝申请") : Result.error("操作失败，Rcon连接错误或玩家不存在");
    }

    /**
     * 从白名单移除
     */
    @DeleteMapping("/remove/{id}")
    public Result<?> removeFromWhitelist(@PathVariable Integer id) {
        return playersService.deletePlayer(id) ? Result.success().msg("已从白名单移除") : Result.error("操作失败");
    }

    /**
     * 批量通过
     */
    @PostMapping("/batchApprove")
    public Result<?> batchApprove(@RequestBody List<Integer> ids, HttpSession session) {
        Operators operators = (Operators) session.getAttribute("adminAccount");
        int code = playersService.updatePlayersStatus(ids, (byte) 1, operators);
        return code > 0 ? Result.success().msg("成功处理：" + code + "/" + ids.size()) : Result.error("操作失败");
    }

    /**
     * 批量拒绝
     */
    @PostMapping("/batchReject")
    public Result<?> batchReject(@RequestBody List<Integer> ids, HttpSession session) {
        Operators operators = (Operators) session.getAttribute("adminAccount");
        int code = playersService.updatePlayersStatus(ids, (byte) 0, operators);
        return code > 0 ? Result.success().msg("成功处理：" + code + "/" + ids.size()) : Result.error("操作失败");
    }

    /**
     * 批量移除白名单
     */
    @DeleteMapping("/batchRemove")
    public Result<?> batchRemove(@RequestBody List<Integer> ids) {
        int code = playersService.deletePlayers(ids);
        return code > 0 ? Result.success().msg("成功移除：" + code + "/" + ids.size()) : Result.error("操作失败");
    }

    /**
     * 获取白名单统计信息
     */
    @GetMapping("/stats")
    public Result<?> getStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("approved", playersService.getPlayersCountByStatus((byte) 1));
        stats.put("pending", playersService.getPlayersCountByStatus((byte) 2));
        stats.put("rejected", playersService.getPlayersCountByStatus((byte) 0));
        return Result.success(stats);
    }

    /**
     * 查询玩家白名单状态
     */
    @GetMapping("/check/{playerName}")
    public Result<?> checkPlayer(@PathVariable String playerName) {
        Players player = playersService.getPlayer(playerName);
        if (player == null) {
            return Result.success(Map.of("exists", false));
        }
        Map<String, Object> info = new HashMap<>();
        info.put("exists", true);
        info.put("status", player.getStatus());
        info.put("playerName", player.getPlayerName());
        info.put("qq", player.getQq());
        info.put("uuid", player.getUuid());
        String statusText = switch (player.getStatus()) {
            case 1 -> "已通过";
            case 2 -> "待审核";
            default -> "已拒绝";
        };
        info.put("statusText", statusText);
        return Result.success(info);
    }

    /**
     * 获取玩家得分
     */
    @GetMapping("/score/{id}")
    public Result<?> getPlayerScore(@PathVariable Integer id) {
        Integer score = playersService.getPlayerScoreById(id);
        if (score == null) {
            return Result.error("玩家不存在");
        }
        return Result.success(Map.of("playerId", id, "totalScore", score));
    }
}
