package org.springblade.modules.martial.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.time.LocalDateTime;
import java.util.List;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.martial.pojo.entity.MartialAthlete;
import org.springblade.modules.martial.pojo.entity.MartialCompetition;
import org.springblade.modules.martial.pojo.vo.AthleteListResultVO;
import org.springblade.modules.martial.pojo.vo.MartialAthleteVO;
import org.springblade.modules.martial.service.IMartialAthleteService;
import org.springblade.modules.martial.service.IMartialCompetitionService;
import org.springframework.web.bind.annotation.*;

/**
 * 参赛选手 控制器
 *
 * @author BladeX
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/martial/athlete")
@Tag(name = "参赛选手管理", description = "参赛选手接口")
public class MartialAthleteController extends BladeController {

	private final IMartialAthleteService athleteService;
	private final IMartialCompetitionService competitionService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@Operation(summary = "详情", description = "传入ID")
	public R<MartialAthlete> detail(@RequestParam Long id) {
		MartialAthlete detail = athleteService.getById(id);
		return R.data(detail);
	}

	/**
	 * 分页列表（包含关联字段）- 管理后台使用
	 */
	@GetMapping("/list")
	@Operation(summary = "分页列表", description = "分页查询")
	public R<IPage<MartialAthleteVO>> list(MartialAthlete athlete, Query query) {
		IPage<MartialAthleteVO> pages = athleteService.selectAthleteVOPage(Condition.getPage(query), athlete);
		return R.data(pages);
	}

	/**
	 * 公开分页列表 - 报名端使用
	 * 报名未结束时返回空列表和提示信息
	 */
	@GetMapping("/public-list")
	@Operation(summary = "公开分页列表", description = "报名端使用，报名未结束时返回空列表")
	public R<AthleteListResultVO> publicList(MartialAthlete athlete, Query query) {
		AthleteListResultVO result = new AthleteListResultVO();
		
		if (athlete.getCompetitionId() != null) {
			MartialCompetition competition = competitionService.getById(athlete.getCompetitionId());
			if (competition != null && competition.getRegistrationEndTime() != null) {
				LocalDateTime now = LocalDateTime.now();
				boolean registrationEnded = now.isAfter(competition.getRegistrationEndTime());
				
				result.setRegistrationEnded(registrationEnded);
				result.setRegistrationEndTime(competition.getRegistrationEndTime());
				
				if (!registrationEnded) {
					result.setPage(new Page<>());
					result.setMessage("报名尚未结束，暂不显示参赛选手");
					return R.data(result);
				}
			}
		}
		
		IPage<MartialAthleteVO> pages = athleteService.selectAthleteVOPage(Condition.getPage(query), athlete);
		result.setPage(pages);
		result.setRegistrationEnded(true);
		return R.data(result);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Operation(summary = "新增或修改", description = "传入实体")
	public R submit(@RequestBody MartialAthlete athlete) {
		Long userId = AuthUtil.getUserId();
		log.info("=== 提交选手 === userId: {}, playerName: {}", userId, athlete.getPlayerName());
		if (athlete.getId() == null) {
			athlete.setCreateUser(userId);
		}
		athlete.setUpdateUser(userId);
		return R.status(athleteService.saveOrUpdate(athlete));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@Operation(summary = "删除", description = "传入ID")
	public R remove(@RequestParam String ids) {
		return R.status(athleteService.removeByIds(Func.toLongList(ids)));
	}

	/**
	 * Task 2.1: 运动员签到
	 */
	@PostMapping("/checkin")
	@Operation(summary = "运动员签到", description = "比赛日签到")
	public R checkIn(@RequestParam Long athleteId, @RequestParam Long scheduleId) {
		athleteService.checkIn(athleteId, scheduleId);
		return R.success("签到成功");
	}

	/**
	 * Task 2.1: 完成比赛
	 */
	@PostMapping("/complete")
	@Operation(summary = "完成比赛", description = "标记运动员完成表演")
	public R completePerformance(@RequestParam Long athleteId, @RequestParam Long scheduleId) {
		athleteService.completePerformance(athleteId, scheduleId);
		return R.success("已标记完成");
	}

	/**
	 * Task 2.6: 更新比赛状态
	 */
	@PostMapping("/status")
	@Operation(summary = "更新比赛状态", description = "状态流转：0-待出场，1-进行中，2-已完成")
	public R updateStatus(@RequestParam Long athleteId, @RequestParam Integer status) {
		athleteService.updateCompetitionStatus(athleteId, status);
		return R.success("状态更新成功");
	}

	/**
	 * 获取已报名选手列表（用于检查重复报名）
	 */
	@GetMapping("/registered")
	@Operation(summary = "获取已报名选手", description = "查询指定赛事和项目的已报名选手")
	public R<List<MartialAthlete>> getRegisteredAthletes(
			@RequestParam Long competitionId,
			@RequestParam(required = false) String projectIds) {
		LambdaQueryWrapper<MartialAthlete> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MartialAthlete::getCompetitionId, competitionId)
			.eq(MartialAthlete::getIsDeleted, 0)
			.eq(MartialAthlete::getRegistrationStatus, 1);
		
		if (Func.isNotBlank(projectIds)) {
			wrapper.in(MartialAthlete::getProjectId, Func.toLongList(projectIds));
		}
		
		List<MartialAthlete> list = athleteService.list(wrapper);
		return R.data(list);
	}

}
