package top.awinx.stu01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.awinx.stu01.dto.StudentAddDTO;
import top.awinx.stu01.dto.StudentQueryDTO;
import top.awinx.stu01.entity.Student;
import top.awinx.stu01.exception.BusinessException;
import top.awinx.stu01.mapper.StudentMapper;
import top.awinx.stu01.service.StudentService;

import java.util.List;

/**
 * 学生Service实现类
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    /**
     * 添加学生：校验学号唯一性，转换DTO为实体并保存
     */
    @Override
    public Student addStudent(StudentAddDTO addDTO) {
        // 1. 校验学号是否已存在
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStuNo, addDTO.getStuNo());
        if (this.count(wrapper) > 0) {
            throw new BusinessException("学号" + addDTO.getStuNo() + "已存在");
        }

        // 2. DTO转换为实体
        Student student = new Student();
        student.setStuNo(addDTO.getStuNo());
        student.setName(addDTO.getName());
        student.setMajor(addDTO.getMajor());
        student.setUserId(addDTO.getUserId());

        // 3. 保存学生信息
        this.save(student);
        return student;
    }

    /**
     * 模糊查询学生：学号精确匹配，姓名/专业模糊匹配
     */
    @Override
    public List<Student> queryStudent(StudentQueryDTO queryDTO) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();

        // 学号：精确匹配
        if (queryDTO.getStuNo() != null && !queryDTO.getStuNo().isEmpty()) {
            wrapper.eq(Student::getStuNo, queryDTO.getStuNo());
        }

        // 姓名：模糊匹配（包含）
        if (queryDTO.getName() != null && !queryDTO.getName().isEmpty()) {
            wrapper.like(Student::getName, queryDTO.getName());
        }

        // 专业：模糊匹配（包含）
        if (queryDTO.getMajor() != null && !queryDTO.getMajor().isEmpty()) {
            wrapper.like(Student::getMajor, queryDTO.getMajor());
        }

        // 按创建时间降序排列
        wrapper.orderByDesc(Student::getCreateTime);

        // 查询并返回结果
        return this.list(wrapper);
    }
}
