package org.springblade.modules.martial.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
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.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.martial.pojo.dto.BatchGenerateInviteDTO;
import org.springblade.modules.martial.pojo.dto.GenerateInviteDTO;
import org.springblade.modules.martial.pojo.entity.MartialJudgeInvite;
import org.springblade.modules.martial.pojo.vo.MartialJudgeInviteVO;
import org.springblade.modules.martial.service.IMartialJudgeInviteService;
import org.springframework.web.bind.annotation.*;

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

/**
 * 裁判邀请码 控制器
 *
 * @author BladeX
 */
@RestController
@AllArgsConstructor
@RequestMapping("/martial/judgeInvite")
@Tag(name = "裁判邀请码管理", description = "裁判邀请码接口")
public class MartialJudgeInviteController extends BladeController {

	private final IMartialJudgeInviteService judgeInviteService;

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

	/**
	 * 分页列表（关联裁判信息）
	 */
	@GetMapping("/list")
	@Operation(summary = "分页列表", description = "分页查询，关联裁判信息")
	public R<IPage<MartialJudgeInviteVO>> list(MartialJudgeInvite judgeInvite, Query query) {
		IPage<MartialJudgeInviteVO> pages = judgeInviteService.selectJudgeInvitePage(judgeInvite, query);
		return R.data(pages);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Operation(summary = "新增或修改", description = "传入实体")
	public R submit(@RequestBody MartialJudgeInvite judgeInvite) {
		return R.status(judgeInviteService.saveOrUpdate(judgeInvite));
	}

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

	/**
	 * 获取邀请统计信息
	 */
	@GetMapping("/statistics")
	@Operation(summary = "邀请统计", description = "传入赛事ID")
	public R<Map<String, Object>> statistics(@RequestParam Long competitionId) {
		Map<String, Object> statistics = judgeInviteService.getInviteStatistics(competitionId);
		return R.data(statistics);
	}

	/**
	 * 生成邀请码
	 */
	@PostMapping("/generate")
	@Operation(summary = "生成邀请码", description = "为评委生成邀请码")
	public R<MartialJudgeInvite> generateInviteCode(@RequestBody GenerateInviteDTO dto) {
		MartialJudgeInvite invite = judgeInviteService.generateInviteCode(dto);
		return R.data(invite);
	}

	/**
	 * 批量生成邀请码
	 */
	@PostMapping("/generate/batch")
	@Operation(summary = "批量生成邀请码", description = "为多个评委批量生成邀请码")
	public R<List<MartialJudgeInvite>> batchGenerateInviteCode(@RequestBody BatchGenerateInviteDTO dto) {
		List<MartialJudgeInvite> invites = judgeInviteService.batchGenerateInviteCode(dto);
		return R.data(invites);
	}

	/**
	 * 重新生成邀请码
	 */
	@PutMapping("/regenerate/{inviteId}")
	@Operation(summary = "重新生成邀请码", description = "重新生成邀请码（旧码失效）")
	public R<MartialJudgeInvite> regenerateInviteCode(@PathVariable Long inviteId) {
		MartialJudgeInvite invite = judgeInviteService.regenerateInviteCode(inviteId);
		return R.data(invite);
	}

	/**
	 * 查询评委的邀请码
	 */
	@GetMapping("/byJudge")
	@Operation(summary = "查询评委邀请码", description = "根据评委ID和赛事ID查询邀请码")
	public R<MartialJudgeInvite> getInviteByJudge(
		@RequestParam Long competitionId,
		@RequestParam Long judgeId
	) {
		MartialJudgeInvite invite = judgeInviteService.lambdaQuery()
			.eq(MartialJudgeInvite::getCompetitionId, competitionId)
			.eq(MartialJudgeInvite::getJudgeId, judgeId)
			.eq(MartialJudgeInvite::getIsDeleted, 0)
			.orderByDesc(MartialJudgeInvite::getCreateTime)
			.last("LIMIT 1")
			.one();
		return R.data(invite);
	}

	/**
	 * 发送邀请
	 */
	@PostMapping("/send")
	@Operation(summary = "发送邀请", description = "向评委发送邀请")
	public R sendInvite(@RequestBody MartialJudgeInvite judgeInvite) {
		// TODO: 实现邮件/短信发送逻辑
		judgeInvite.setInviteStatus(0); // 待回复
		judgeInvite.setInviteTime(java.time.LocalDateTime.now());
		return R.status(judgeInviteService.saveOrUpdate(judgeInvite));
	}

	/**
	 * 重发邀请
	 */
	@PostMapping("/resend/{inviteId}")
	@Operation(summary = "重发邀请", description = "重新发送邀请")
	public R resendInvite(@PathVariable Long inviteId) {
		MartialJudgeInvite invite = judgeInviteService.getById(inviteId);
		if (invite == null) {
			return R.fail("邀请记录不存在");
		}
		// TODO: 实现邮件/短信重发逻辑
		invite.setInviteTime(java.time.LocalDateTime.now());
		return R.status(judgeInviteService.updateById(invite));
	}

	/**
	 * 取消邀请
	 */
	@PostMapping("/cancel/{inviteId}")
	@Operation(summary = "取消邀请", description = "取消邀请")
	public R cancelInvite(@PathVariable Long inviteId, @RequestParam(required = false) String reason) {
		MartialJudgeInvite invite = judgeInviteService.getById(inviteId);
		if (invite == null) {
			return R.fail("邀请记录不存在");
		}
		invite.setInviteStatus(3); // 已取消
		invite.setCancelReason(reason);
		return R.status(judgeInviteService.updateById(invite));
	}

	/**
	 * 确认邀请
	 */
	@PostMapping("/confirm/{inviteId}")
	@Operation(summary = "确认邀请", description = "确认接受邀请")
	public R confirmInvite(@PathVariable Long inviteId) {
		MartialJudgeInvite invite = judgeInviteService.getById(inviteId);
		if (invite == null) {
			return R.fail("邀请记录不存在");
		}
		if (invite.getInviteStatus() != 1) {
			return R.fail("只能确认已接受的邀请");
		}
		// TODO: 实现确认逻辑（如分配场地、项目等）
		return R.success("确认成功");
	}

	/**
	 * 发送提醒
	 */
	@PostMapping("/reminder/{inviteId}")
	@Operation(summary = "发送提醒", description = "提醒评委回复邀请")
	public R sendReminder(@PathVariable Long inviteId, @RequestParam(required = false) String message) {
		MartialJudgeInvite invite = judgeInviteService.getById(inviteId);
		if (invite == null) {
			return R.fail("邀请记录不存在");
		}
		// TODO: 实现提醒发送逻辑（邮件/短信）
		return R.success("提醒发送成功");
	}

	/**
	 * 从评委库导入
	 */
	@PostMapping("/import/pool")
	@Operation(summary = "从评委库导入", description = "从评委库批量导入评委")
	public R importFromPool(@RequestParam Long competitionId, @RequestParam String judgeIds) {
		// TODO: 实现从评委库导入逻辑
		List<Long> ids = Func.toLongList(judgeIds);
		// 为每个评委生成邀请码
		return R.success("导入成功");
	}

	/**
	 * 导出邀请数据
	 */
	@GetMapping("/export")
	@Operation(summary = "导出邀请数据", description = "导出邀请数据为Excel")
	public void exportInvites(MartialJudgeInvite judgeInvite) {
		// TODO: 实现Excel导出逻辑
		// 使用EasyExcel或POI导出
	}


	/**
	 * 更新邀请的项目分配
	 */
	@PutMapping("/updateProjects")
	@Operation(summary = "更新项目分配", description = "更新裁判邀请的项目分配")
	public R updateProjects(@RequestBody java.util.Map<String, Object> params) {
		Long inviteId = Long.valueOf(params.get("inviteId").toString());
		String projects = params.get("projects").toString();
		
		MartialJudgeInvite invite = judgeInviteService.getById(inviteId);
		if (invite == null) {
			return R.fail("邀请记录不存在");
		}
		
		invite.setProjects(projects);
		boolean success = judgeInviteService.updateById(invite);
		return success ? R.success("更新成功") : R.fail("更新失败");
	}

}
