package com.hhh.cloud.framework.demo.clazz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhh.cloud.framework.demo.clazz.entity.ClazzStudent;
import com.hhh.cloud.framework.demo.clazz.mapper.ClazzStudentMapper;
import com.hhh.cloud.framework.demo.clazz.service.IClazzStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.cloud.framework.util.enumeration.CodeEnum;
import com.hhh.cloud.framework.util.exception.BusinessException;
import com.hhh.cloud.framework.util.result.TableResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 3hhjs
 * @since 2021-05-19
 */
@Service
public class ClazzStudentServiceImpl extends ServiceImpl<ClazzStudentMapper, ClazzStudent> implements IClazzStudentService {

    @Override
    public boolean existsStudent(String name) {
        if(StringUtils.isBlank(name)) {
            throw new BusinessException("姓名不能为空");
        }
        QueryWrapper<ClazzStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return null != baseMapper.selectOne(queryWrapper);
    }

    @Override
    public TableResult<List<ClazzStudent>> pageStudent(ClazzStudent student, int page, int limit) {
        QueryWrapper<ClazzStudent> queryWrapper = new QueryWrapper<>();
        formatQuery(queryWrapper, student);
        IPage<ClazzStudent> searchPage = baseMapper.selectPage(new Page<>(page, limit), queryWrapper);
        return new TableResult<>(CodeEnum.SUCCESS.get(), searchPage.getRecords(), searchPage.getTotal(), "");
    }

    private void formatQuery(QueryWrapper<ClazzStudent> queryWrapper, ClazzStudent student) {
        if(StringUtils.isNotBlank(student.getName())) {
            queryWrapper.like("name", "%"+student.getName()+"%");
        }
        if(StringUtils.isNotBlank(student.getClassNo())) {
            queryWrapper.eq("class_no", student.getClassNo());
        }
        queryWrapper.in("gender", 0, 1);
        queryWrapper.orderByAsc("name");
    }

    @Override
    public TableResult<List<ClazzStudent>> pageStudent2(ClazzStudent student, int page, int limit) {
        Page<ClazzStudent> searchPage = baseMapper.selectPageStudent(new Page<>(page, limit), student);
        return new TableResult<>(CodeEnum.SUCCESS.get(), searchPage.getRecords(), searchPage.getTotal(), "");
    }
}
