package org.springblade.modules.martial.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.modules.martial.pojo.entity.MartialExceptionEvent;
import org.springblade.modules.martial.mapper.MartialExceptionEventMapper;
import org.springblade.modules.martial.service.IMartialExceptionEventService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 异常事件 服务实现类
 *
 * @author BladeX
 */
@Slf4j
@Service
public class MartialExceptionEventServiceImpl extends ServiceImpl<MartialExceptionEventMapper, MartialExceptionEvent> implements IMartialExceptionEventService {

	/**
	 * Task 2.4: 记录异常事件
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void recordException(Long competitionId, Long scheduleId, Long athleteId,
								Integer eventType, String eventDescription) {
		MartialExceptionEvent event = new MartialExceptionEvent();
		event.setCompetitionId(competitionId);
		event.setScheduleId(scheduleId);
		event.setAthleteId(athleteId);
		event.setEventType(eventType);
		event.setEventDescription(eventDescription);
		event.setStatus(0);  // 待处理

		this.save(event);

		log.warn("📋 异常事件记录 - 赛事ID:{}, 运动员ID:{}, 类型:{}, 描述:{}",
			competitionId, athleteId, getEventTypeName(eventType), eventDescription);
	}

	/**
	 * Task 2.4: 处理异常事件
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void handleException(Long eventId, String handlerName, String handleResult) {
		MartialExceptionEvent event = this.getById(eventId);
		if (event == null) {
			throw new ServiceException("异常事件不存在");
		}

		event.setHandlerName(handlerName);
		event.setHandleResult(handleResult);
		event.setHandleTime(LocalDateTime.now());
		event.setStatus(1);  // 已处理

		this.updateById(event);

		log.info("✅ 异常事件已处理 - 事件ID:{}, 处理人:{}, 结果:{}",
			eventId, handlerName, handleResult);
	}

	/**
	 * 获取事件类型名称
	 */
	private String getEventTypeName(Integer eventType) {
		switch (eventType) {
			case 1: return "器械故障";
			case 2: return "受伤";
			case 3: return "评分争议";
			case 4: return "其他";
			default: return "未知";
		}
	}

}
