package org.springblade.modules.martial.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
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.MartialRegistrationOrder;
import org.springblade.modules.martial.pojo.entity.MartialTeam;
import org.springblade.modules.martial.pojo.entity.MartialTeamMember;
import org.springblade.modules.martial.pojo.dto.RegistrationSubmitDTO;
import org.springblade.modules.martial.pojo.vo.MartialRegistrationOrderVO;
import org.springblade.modules.martial.service.IMartialAthleteService;
import org.springblade.modules.martial.service.IMartialRegistrationOrderService;
import org.springblade.modules.martial.service.IMartialTeamService;
import org.springblade.modules.martial.mapper.MartialTeamMemberMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/martial/registrationOrder")
@Tag(name = "报名订单管理", description = "报名订单接口")
public class MartialRegistrationOrderController extends BladeController {

	private final IMartialRegistrationOrderService registrationOrderService;
	private final IMartialAthleteService athleteService;
	private final IMartialTeamService teamService;
	private final MartialTeamMemberMapper teamMemberMapper;

	@GetMapping("/detail")
	@Operation(summary = "详情", description = "传入ID")
	public R detail(@RequestParam Long id) {
		return R.data(registrationOrderService.getDetailWithRelations(id));
	}

	@GetMapping("/list")
	@Operation(summary = "分页列表", description = "分页查询当前用户的报名记录")
	public R<IPage<MartialRegistrationOrderVO>> list(MartialRegistrationOrder registrationOrder, Query query) {
		Long userId = AuthUtil.getUserId();
		Integer status = registrationOrder.getStatus();
		
		IPage<MartialRegistrationOrderVO> pages = registrationOrderService.getListWithRelations(
				userId, status, query.getCurrent(), query.getSize());
		
		return R.data(pages);
	}

	@PostMapping("/submit")
	@Operation(summary = "提交报名", description = "提交报名订单并关联选手或集体")
	@Transactional(rollbackFor = Exception.class)
	public R submit(@RequestBody RegistrationSubmitDTO dto) {
		log.info("=== 提交报名订单 ===");
		log.info("订单号: {}", dto.getOrderNo());
		log.info("赛事ID: {}", dto.getCompetitionId());
		log.info("项目IDs: {}", dto.getProjectIds());
		log.info("选手IDs: {}", dto.getAthleteIds());
		log.info("集体IDs: {}", dto.getTeamIds());
		log.info("联系电话: {}", dto.getContactPhone());
		log.info("总金额: {}", dto.getTotalAmount());
		
		// Create order entity
		MartialRegistrationOrder order = new MartialRegistrationOrder();
		order.setOrderNo(dto.getOrderNo());
		order.setCompetitionId(dto.getCompetitionId());
		order.setContactPhone(dto.getContactPhone());
		order.setTotalAmount(dto.getTotalAmount());
		order.setUserId(AuthUtil.getUserId());
		order.setUserName(AuthUtil.getUserName());
		
		// Parse IDs
		List<Long> athleteIds = Func.toLongList(dto.getAthleteIds());
		List<Long> teamIds = Func.toLongList(dto.getTeamIds());
		List<Long> projectIds = Func.toLongList(dto.getProjectIds());
		
		// Determine if this is a team registration
		boolean isTeamRegistration = !teamIds.isEmpty();
		
		if (isTeamRegistration) {
			order.setTotalParticipants(teamIds.size());
		} else {
			order.setTotalParticipants(athleteIds.size());
		}
		
		// Save order
		boolean saved = registrationOrderService.save(order);
		if (!saved) {
			return R.fail("创建订单失败");
		}
		
		Long orderId = order.getId();
		log.info("订单创建成功，订单ID: {}", orderId);
		
		if (isTeamRegistration) {
			// Handle team registration - create record for each team and each project
			for (Long teamId : teamIds) {
				MartialTeam team = teamService.getById(teamId);
				if (team == null) {
					log.warn("集体不存在: {}", teamId);
					continue;
				}
				
				// Create a record for each project
				for (Long projectId : projectIds) {
					MartialAthlete teamAthlete = new MartialAthlete();
					teamAthlete.setOrderId(orderId);
					teamAthlete.setCompetitionId(dto.getCompetitionId());
					teamAthlete.setProjectId(projectId);
					teamAthlete.setTeamName(team.getTeamName());
					teamAthlete.setPlayerName(team.getTeamName());
					teamAthlete.setOrganization(team.getTeamName());
					teamAthlete.setRegistrationStatus(1);
					teamAthlete.setCompetitionStatus(0);
					teamAthlete.setCreateUser(AuthUtil.getUserId());
					teamAthlete.setCreateTime(new java.util.Date());
					teamAthlete.setTenantId("000000");
					teamAthlete.setIsDeleted(0);
					teamAthlete.setStatus(1);
					
					athleteService.save(teamAthlete);
					log.info("创建集体参赛记录: teamName={}, projectId={}", team.getTeamName(), projectId);
				}
			}
		} else {
			// Handle individual registration - create record for each athlete and each project
			for (Long athleteId : athleteIds) {
				MartialAthlete existingAthlete = athleteService.getById(athleteId);
				if (existingAthlete == null) {
					log.warn("选手不存在: {}", athleteId);
					continue;
				}
				
				// Create a record for each project
				for (Long projectId : projectIds) {
					MartialAthlete newRecord = new MartialAthlete();
					newRecord.setOrderId(orderId);
					newRecord.setCompetitionId(dto.getCompetitionId());
					newRecord.setProjectId(projectId);
					newRecord.setPlayerName(existingAthlete.getPlayerName());
					newRecord.setGender(existingAthlete.getGender());
					newRecord.setIdCard(existingAthlete.getIdCard());
					newRecord.setIdCardType(existingAthlete.getIdCardType());
					newRecord.setContactPhone(existingAthlete.getContactPhone());
					newRecord.setOrganization(existingAthlete.getOrganization());
					newRecord.setTeamName(existingAthlete.getTeamName());
					newRecord.setRegistrationStatus(1);
					newRecord.setCompetitionStatus(0);
					newRecord.setCreateUser(AuthUtil.getUserId());
					newRecord.setCreateTime(new java.util.Date());
					newRecord.setTenantId("000000");
					newRecord.setIsDeleted(0);
					newRecord.setStatus(1);
					
					athleteService.save(newRecord);
					log.info("创建选手参赛记录: playerName={}, projectId={}", existingAthlete.getPlayerName(), projectId);
				}
			}
		}
		
		return R.data(order);
	}

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

}
