package org.springblade.modules.martial.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.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.dto.RegistrationSubmitDTO;
import org.springblade.modules.martial.service.IMartialAthleteService;
import org.springblade.modules.martial.service.IMartialRegistrationOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

	private final IMartialRegistrationOrderService registrationOrderService;
	private final IMartialAthleteService athleteService;

	/**
	 * 详情
	 */
	@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<MartialRegistrationOrder>> list(MartialRegistrationOrder registrationOrder, Query query) {
		// 获取当前登录用户ID
		Long userId = AuthUtil.getUserId();
		
		// 构建查询条件 - 只查询当前用户的订单
		LambdaQueryWrapper<MartialRegistrationOrder> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(MartialRegistrationOrder::getUserId, userId);
		
		// 如果传入了状态参数，添加状态过滤
		if (registrationOrder.getStatus() != null) {
			queryWrapper.eq(MartialRegistrationOrder::getStatus, registrationOrder.getStatus());
		}
		
		// 按创建时间倒序
		queryWrapper.orderByDesc(MartialRegistrationOrder::getCreateTime);
		
		// 分页查询
		IPage<MartialRegistrationOrder> page = new Page<>(query.getCurrent(), query.getSize());
		IPage<MartialRegistrationOrder> pages = registrationOrderService.page(page, queryWrapper);
		
		return R.data(pages);
	}

	/**
	 * 提交报名订单
	 * 接收前端传来的 athleteIds 和 projectIds，更新选手的 orderId
	 */
	@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("联系电话: {}", dto.getContactPhone());
		log.info("总金额: {}", dto.getTotalAmount());
		
		// 1. 创建订单实体
		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());
		
		// 解析选手ID列表
		List<Long> athleteIds = Func.toLongList(dto.getAthleteIds());
		order.setTotalParticipants(athleteIds.size());
		
		// 2. 保存订单
		boolean saved = registrationOrderService.save(order);
		if (!saved) {
			return R.fail("创建订单失败");
		}
		
		Long orderId = order.getId();
		log.info("订单创建成功，订单ID: {}", orderId);
		
		// 3. 解析项目ID列表
		List<Long> projectIds = Func.toLongList(dto.getProjectIds());
		Long firstProjectId = projectIds.isEmpty() ? null : projectIds.get(0);
		
		// 4. 更新选手的 orderId、competitionId 和 projectId
		if (!athleteIds.isEmpty()) {
			LambdaUpdateWrapper<MartialAthlete> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.in(MartialAthlete::getId, athleteIds)
					.set(MartialAthlete::getOrderId, orderId)
					.set(MartialAthlete::getCompetitionId, dto.getCompetitionId());
			
			// 如果只有一个项目，设置项目ID
			if (firstProjectId != null) {
				updateWrapper.set(MartialAthlete::getProjectId, firstProjectId);
			}
			
			boolean updated = athleteService.update(updateWrapper);
			log.info("更新选手关联，选手数量: {}, 更新结果: {}", athleteIds.size(), updated);
		}
		
		// 5. 返回订单信息
		return R.data(order);
	}

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

}
