package com.qmth.paper.library.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.qmth.paper.library.business.bean.result.SelectResult;
import com.qmth.paper.library.business.entity.ExamCourse;
import com.qmth.paper.library.business.mapper.ExamCourseMapper;
import com.qmth.paper.library.business.service.ExamCourseService;
import com.qmth.paper.library.common.entity.ExamStudent;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考生课程表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2024-03-11
 */
@Service
public class ExamCourseServiceImpl extends MppServiceImpl<ExamCourseMapper, ExamCourse> implements ExamCourseService {

    @Override
    public void removeByExamIdAndCourseCode(Long examId, String courseCode) {
        QueryWrapper<ExamCourse> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ExamCourse> lambda = queryWrapper.lambda();
        lambda.eq(ExamCourse::getExamId, examId);
        if (StringUtils.isNotBlank(courseCode)) {
            lambda.eq(ExamCourse::getCourseCode, courseCode);
        }
        this.remove(queryWrapper);
    }

    @Override
    public List<SelectResult> listConditionByExamId(Long examId) {
        List<SelectResult> selectResults = new ArrayList<>();
        for (ExamCourse examCourse : this.listByExamId(examId)) {
            SelectResult selectResult = new SelectResult();
            selectResult.setCode(examCourse.getCourseCode());
            selectResult.setName(examCourse.getCourseName());
            selectResults.add(selectResult);
        }
        return selectResults;
    }

    @Override
    public List<ExamCourse> listByExamId(Long examId) {
        QueryWrapper<ExamCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExamCourse::getExamId, examId)
                .orderByDesc(ExamCourse::getCourseCode);
        return this.list(queryWrapper);
    }

    @Override
    public void saveStudentCourse(Long examId, ExamStudent examStudent) {
        ExamCourse examCourse = this.selectByMultiId(new ExamCourse(examId, examStudent.getCourseCode()));
        if (examCourse == null) {
            this.save(new ExamCourse(examId, examStudent.getCourseCode(), examStudent.getCourseName()));
        } else if (!examCourse.getCourseName().equals(examStudent.getCourseName())) {
            throw ExceptionResultEnum.ERROR.exception(String.format("考试下已存在课程代码[%s]，课程名称为[%s]", examStudent.getCourseCode(), examCourse.getCourseName()));
        }

    }
}
