package com.micer.easyball.controller;

import com.micer.easyball.ApiVersion;

import com.micer.easyball.pojo.Dto.GameDto;
import com.micer.easyball.pojo.ResponseResult;
import com.micer.easyball.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.micer.easyball.pojo.Game;
import com.micer.easyball.pojo.Dto.GameDetailDto;
import com.micer.easyball.pojo.Dto.WeatherDto;
import com.micer.easyball.service.WeatherService;
import com.micer.easyball.mapper.ClubMapper;
import com.micer.easyball.mapper.EventMapper;
import java.text.SimpleDateFormat;


import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(ApiVersion.V1)
public class GameController {

    @Autowired
    GameService gameService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private EventMapper eventMapper;

    /**
     * 查询某年份的所有场次
     * option：true（日期升序）， false（日期降序）
     */
    @GetMapping("/game/getGames/{year}")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_PLAYER')")
    public ResponseResult getGames(@PathVariable Long year,
                                   @RequestParam Boolean option)
    {
        return gameService.getGames(year,option);
    }

    /**
     * 获取新场次ID
     */
    @GetMapping("/game/getNewGameId")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_ADMIN')")
    public ResponseResult getNewGameId()
    {
        return gameService.getNewGameId();
    }

    /**
     * 添加新场次
     */
    @PostMapping("/game/addGame")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_ADMIN')")
    public ResponseResult addGame(@RequestBody GameDto gameDto)
    {
        return gameService.addGame(gameDto);
    }

    /**
     * 删除场次
     */
    @DeleteMapping("/game/deleteGame")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_ADMIN')")
    public ResponseResult deleteGame(@RequestParam String gameId)
    {
        return gameService.deleteGame(gameId);
    }

    /**
     * 修改场次
     */
    @PutMapping("/game/editGame")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_ADMIN')")
    public ResponseResult editGame(@RequestBody javax.validation.Valid com.micer.easyball.pojo.Dto.GameUpdateDto gameDto)
    {
        return gameService.editGame(gameDto);
    }

    /**
     * 俱乐部年度总结
     */
    @GetMapping("/game/getClubStatistics/{year}")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_PLAYER')")
    public ResponseResult getClubStatistics(@PathVariable("year") Long year)
    {
        return gameService.getClubStatistics(year);
    }

    /**
     * 球员年度总结
     */
    @GetMapping("/game/getPlayerStatistics/{year}")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_PLAYER')")
    public ResponseResult getPlayerStatistics(@PathVariable("year") Long year,
                                            @RequestParam String playerId)
    {
        return gameService.getPlayerStatistics(year, playerId);
    }

    /**
     * 查询比赛详情（含天气）
     * 扩展功能：引入第三方天气 API，展示 API10 不安全消费漏洞
     */
    @GetMapping("/game/getGameDetail/{gameId}")
    @PreAuthorize("@ex.hasRole('ROLE_CLUB_PLAYER')")
    public ResponseResult getGameDetail(@PathVariable String gameId) {
        // 查询比赛基本信息
        Game game = gameService.getGameById(gameId);
        if (game == null) {
            return new ResponseResult(404, "比赛不存在");
        }

        // 查询天气（不安全：直接消费第三方 API，未校验响应）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String gameDate = sdf.format(game.getDate());
        ResponseResult weatherResult = weatherService.getWeather(game.getVenue(), gameDate);

        // 组装详情
        GameDetailDto detail = new GameDetailDto(game);
        detail.setOurTeamName(clubMapper.selectById(game.getOurTeamId()).getName());
        detail.setEventName(eventMapper.selectById(game.getEventId()).getName());
        detail.setWeather((WeatherDto) weatherResult.getData());

        return new ResponseResult(200, "成功", detail);
    }
}
