package com.example.system.controller;

import com.example.system.model.CompetitionTable;
import com.example.system.model.Result;
import com.example.system.service.CompetitionService;
import com.example.system.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/competition")
public class CompetitionController {

    @Autowired
    private CompetitionService competitionService;



    /**
     * 添加竞赛信息
     *
     * @param competition 竞赛信息的请求体
     * @return 竞赛信息实体，包含数据库保存后的完整信息
     */
    @PostMapping("/add")
    public Object addCompetition(CompetitionTable competition, HttpServletRequest request) {
        log.info("添加竞赛信息 competition: {}", competition);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer a = (Integer) claims.get("userPrivileges");
        // 检查用户是否有权限添加竞赛信息
        if (2 == a) {
            // 如果用户无权限，禁止访问
            return Result.fail("无权限添加竞赛信息");
        }
        // 调用服务层添加竞赛信息，并返回添加的竞赛信息
        CompetitionTable competitionTable = competitionService.addCompetition(competition);
        return competitionTable;
    }



    /**
     * 删除竞赛信息
     *
     * @param id 竞赛信息的ID
     * @return 删除成功的提示信息
     */
    @DeleteMapping(value = "/delete/{id}", produces = "application/json")
    public Object deleteCompetition(@PathVariable Long id, HttpServletRequest request) {
        log.info("删除竞赛信息 id: {}", id);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer a = (Integer) claims.get("userPrivileges");
        // 检查用户是否有权限删除竞赛信息
        if (2 == a) {
            return Result.fail("无权限删除竞赛信息");
        }
        // 尝试删除竞赛信息，若竞赛信息不存在，抛出404异常
        boolean isDeleted = competitionService.deleteCompetition(id);
        if (!isDeleted) {
            return Result.fail("未找到要删除的竞赛信息");
        }
        return "竞赛信息删除成功";
    }

    /**
     * 更新竞赛信息
     *
     * @param competition 待更新的竞赛信息
     * @return 更新后的竞赛信息
     */
    @PutMapping("/update")
    public Object updateCompetition(CompetitionTable competition, HttpServletRequest request) {
        log.info("更新竞赛信息 competition: {}", competition);
        String toKen =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(toKen);
        Integer a = (Integer) claims.get("userPrivileges");
        // 检查用户是否有权限进行更新操作
        if (2 == a) {
            return Result.fail("无权限修改竞赛信息");
        }

        // 验证待更新的竞赛信息是否存在
        Optional<CompetitionTable> existingCompetition = competitionService.getCompetitionById(Long.valueOf(competition.getCompetitionId()));
        if (!existingCompetition.isPresent()) {
            return Result.fail("未找到指定的竞赛信息，无法进行更新");
        }

        // 执行更新操作
        try {
            return competitionService.updateCompetition(competition);
        } catch (Exception e) {
            // 处理更新操作中可能出现的异常
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "更新竞赛信息时发生错误");
        }
    }


    /**
     * 根据搜索词条模糊匹配竞赛名称或简介
     *
     * @param searchTerm 搜索词条，可以是竞赛的一部分名称或简介
     * @return 匹配到的竞赛信息列表
     */
    @GetMapping("/search")
    public Object searchCompetitions(String searchTerm) {

        // 调用服务层的方法来执行基于competitionName的模糊搜索
        List<CompetitionTable> competitions = competitionService.searchCompetitionsByName(searchTerm);
        if (competitions.isEmpty()) {
            return Result.fail("未找到匹配的竞赛信息");
        }
        return competitions;
    }

    /**
     * 获取所有竞赛信息的列表。
     *
     * @return 竞赛信息列表
     */
    @GetMapping("/list")
    public Object listCompetitions() {
        return competitionService.getAllCompetitions();
    }
}