package com.qmth.exam.reserve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.exam.reserve.bean.course.CourseVO;
import com.qmth.exam.reserve.dao.StudentCourseDao;
import com.qmth.exam.reserve.entity.StudentCourseEntity;
import com.qmth.exam.reserve.service.StudentCourseService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class StudentCourseServiceImpl extends ServiceImpl<StudentCourseDao, StudentCourseEntity> implements StudentCourseService {

    @Override
    public List<CourseVO> getStudentCourses(Long studentId) {
        LambdaQueryWrapper<StudentCourseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(StudentCourseEntity::getCourseCode, StudentCourseEntity::getCourseName);
        wrapper.eq(StudentCourseEntity::getStudentId, studentId);
        List<StudentCourseEntity> entities = this.list(wrapper);

        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }

        List<CourseVO> courses = new ArrayList<>();
        for (StudentCourseEntity entity : entities) {
            CourseVO vo = new CourseVO();
            vo.setCourseCode(entity.getCourseCode());
            vo.setCourseName(entity.getCourseName());
            courses.add(vo);
        }
        return courses;
    }

    @Override
    @Transactional
    public void removeStudentCourses(Long studentId, String courseCode) {
        LambdaQueryWrapper<StudentCourseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentCourseEntity::getStudentId, studentId);
        wrapper.eq(StringUtils.isNotEmpty(courseCode), StudentCourseEntity::getCourseCode, courseCode);
        this.remove(wrapper);
    }

}
