package org.dromara.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.main.domain.MainExamApply;
import org.dromara.main.domain.MainStudent;
import org.dromara.main.domain.vo.MainExamApplyRecordVo;
import org.dromara.main.domain.vo.MainExamApplyVo;
import org.dromara.main.mapper.MainExamApplyMapper;
import org.dromara.main.mapper.MainStudentMapper;
import org.dromara.main.service.IMainExamApplyService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 测评申请Service业务层处理
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MainExamApplyServiceImpl implements IMainExamApplyService {

    private final MainExamApplyMapper baseMapper;
    private final MainStudentMapper studentMapper;
    private final Converter converter;

    @Override
    public MainExamApplyVo createExamApply(Long evaluationId, Long studentId) {
        log.info("创建测评申请，evaluationId: {}, studentId: {}", evaluationId, studentId);
        
        // 检查学生是否存在
        MainStudent student = studentMapper.selectById(studentId);
        if (student == null) {
            throw new ServiceException("学生不存在");
        }

        // 检查是否已经申请过
        LambdaQueryWrapper<MainExamApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MainExamApply::getEvaluationId, evaluationId)
                   .eq(MainExamApply::getStudentId, studentId)
                   .eq(MainExamApply::getDelFlag, "0");
        
        MainExamApply existingApply = baseMapper.selectOne(queryWrapper);
        if (existingApply != null) {
            log.info("学生已申请过该测评，返回现有申请记录");
            return converter.convert(existingApply, MainExamApplyVo.class);
        }

        // 创建新的申请记录
        MainExamApply examApply = new MainExamApply();
        examApply.setEvaluationId(evaluationId);
        examApply.setStudentId(studentId);
        examApply.setTenantId(student.getTenantId());
        examApply.setApplySource("1"); // 默认来源：小程序
        examApply.setApplyStatus("0"); // 默认状态：待开始
        examApply.setScheduleStartTime(new Date()); // 预定开始时间为当前时间
        examApply.setMaxAttemptCount(1); // 默认最大尝试次数为1
        examApply.setDelFlag("0");
        
        // 设置截止时间（默认24小时后）
        Date deadlineTime = new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000);
        examApply.setDeadlineTime(deadlineTime);

        int result = baseMapper.insert(examApply);
        if (result > 0) {
            log.info("测评申请创建成功，申请ID: {}", examApply.getId());
            return converter.convert(examApply, MainExamApplyVo.class);
        } else {
            throw new ServiceException("创建测评申请失败");
        }
    }

    @Override
    public MainExamApplyVo queryById(Long id) {
        MainExamApply examApply = baseMapper.selectById(id);
        if (examApply == null) {
            throw new ServiceException("测评申请不存在");
        }
        return converter.convert(examApply, MainExamApplyVo.class);
    }

    @Override
    public List<MainExamApplyRecordVo> queryRecordList(Long studentId) {
        if (studentId == null) {
            throw new ServiceException("学生ID不能为空");
        }
        return baseMapper.selectRecordListByStudentId(studentId);
    }

    @Override
    public Boolean updateApplyStatus(Long id, String status) {
        MainExamApply examApply = baseMapper.selectById(id);
        if (examApply == null) {
            throw new ServiceException("测评申请不存在");
        }
        
        examApply.setApplyStatus(status);
        if ("2".equals(status)) { // 如果状态为已完成
            examApply.setFinishedTime(new Date());
        }
        
        return baseMapper.updateById(examApply) > 0;
    }
}
