package yangtz.cs.liu.campus.service.impl.interest;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.framework.util.UserInfoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.interest.SchoolInterestClasses;
import yangtz.cs.liu.campus.domain.interest.SchoolInterestClassesChild;
import yangtz.cs.liu.campus.domain.student.SchoolStudent;
import yangtz.cs.liu.campus.domain.vehicle.SchoolVehicleApplication;
import yangtz.cs.liu.campus.mapper.interest.SchoolInterestClassesChildMapper;
import yangtz.cs.liu.campus.mapper.interest.SchoolInterestClassesMapper;
import yangtz.cs.liu.campus.mapper.student.SchoolStudentMapper;
import yangtz.cs.liu.campus.service.interest.ISchoolInterestClassesChildService;
import yangtz.cs.liu.campus.vo.interest.ChildVO;
import yangtz.cs.liu.campus.vo.interest.StudentVO;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 兴趣班学生Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-10-09
 */
@Service
public class SchoolInterestClassesChildServiceImpl extends ServiceImpl<SchoolInterestClassesChildMapper, SchoolInterestClassesChild> implements ISchoolInterestClassesChildService
{
    @Autowired
    private SchoolInterestClassesChildMapper schoolInterestClassesChildMapper;
    @Autowired
    private SchoolStudentMapper studentMapper;
    @Autowired
    private SchoolInterestClassesMapper classesMapper;
    @Autowired
    UserInfoUtil userInfoUtil;

    /**
     * 查询兴趣班学生列表
     * 
     * @param schoolInterestClassesChild 兴趣班学生
     * @return 兴趣班学生
     */
    @Override
    public List<ChildVO> queryList(SchoolInterestClassesChild schoolInterestClassesChild, Long interestClassesId)
    {
        schoolInterestClassesChild.setInterestClassesId(interestClassesId);
        return schoolInterestClassesChildMapper.queryList(schoolInterestClassesChild);
    }

    /**
     * 新增兴趣班学生，挂载到兴趣班下
     */
    @Override
    public int addStudents(Long interestClassesId, List<Long> idList) {
        if (StringUtils.isNull(idList) || idList.size() == 0) {
            return 0;
        }
        //获取兴趣班人数上限
        SchoolInterestClasses classes = classesMapper.selectById(interestClassesId);
        //检查兴趣班已有学生人数
        List<Long> studentIdList = schoolInterestClassesChildMapper.selectAllStudentIdByInterestClassesId(interestClassesId);
        //兴趣班还可容纳人数
        int containNum = classes.getNumberOfPeople() - studentIdList.size();
        if(containNum >= idList.size()) {
            //查询id对应的学生信息
            LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
            lqw.in(SchoolStudent::getId, idList);
            List<SchoolStudent> studentList = studentMapper.selectList(lqw);
            List<SchoolInterestClassesChild> childList = new ArrayList<>();
            for (SchoolStudent student : studentList) {
                if (studentIdList.contains(student.getId())) {
                    throw new ServiceException("兴趣班下已经有该学员");//兴趣班下已经有该学员
                }
                SchoolInterestClassesChild child = new SchoolInterestClassesChild();
                child.setInterestClassesId(interestClassesId);
                child.setStudentId(student.getId());
                child.setStudentName(student.getStudentName());
                child.setIdCard(student.getIdCard());
                child.insert();
                childList.add(child);
            }
            return schoolInterestClassesChildMapper.insertChilds(childList);
        }else{
            throw new ServiceException("兴趣班人数上限为" + classes.getNumberOfPeople() + "人，还可容纳" + containNum + "人！" );
        }
    }

    /**
     * 查询兴趣班下所有的studentId
     */
    @Override
    public List<Long> selectAllStudentIdByInterestClassesId(Long interestClassesId) {
        return schoolInterestClassesChildMapper.selectAllStudentIdByInterestClassesId(interestClassesId);
    }

    /**
     *新增弹框查询
     */
    @Override
    public List<SchoolStudent> selectAddList(SchoolStudent student, List<Long> studentIdList) {
        List<SchoolStudent> list = schoolInterestClassesChildMapper.selectAddList(studentIdList,student);
        return list;
    }


    //导入学生
    @Override
    public String importStudent(List<StudentVO> studentList, Long interestClassesId) {
        if (StringUtils.isNull(studentList) || studentList.size() == 0) {
            throw new ServiceException("导入学生数据不能为空！请您重新编辑");
        }
        // 准备记录日志数据
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (StudentVO student : studentList) {
            try {
                if (null == student.getIdcard() || StringUtils.isEmpty(student.getIdcard())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
                } else if (!Pattern.matches("^\\d{17}(\\d|X|x)$", student.getIdcard())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、身份证号 " + student.getIdcard() + "  格式不规范, 请您重新输入! ");
                } else {
                    SchoolStudent s = new SchoolStudent();
                    s.setIdCard(student.getIdcard());
                    LambdaQueryWrapper<SchoolStudent> lqw = new LambdaQueryWrapper<>();
                    lqw
                            .eq(isNotNull(s.getIdCard()), SchoolStudent::getIdCard,s.getIdCard())
                    ;
                    //查出该身份证号的学生是否存在
                    SchoolStudent schoolStudent = studentMapper.selectList(lqw).get(0);
                    //如果学生不存在
                    if (null == schoolStudent) {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、身份证号为: " + student.getIdcard() + " 学生不存在,请您重新输入! ");
                    } else {
                        //学生存在,
                        // 判断是否已挂载到兴趣班下
                        SchoolInterestClassesChild childObj = schoolInterestClassesChildMapper.selectInterestChild(interestClassesId,schoolStudent.getIdCard());
                        if (null != childObj) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、身份证号为: " + student.getIdcard() + " 学生已添加进该兴趣班下! ");
                        } else {
                                //挂载兴趣班
                                SchoolInterestClassesChild c = new SchoolInterestClassesChild();
                                BeanUtils.copyProperties(schoolStudent, c);
                                c.setStudentId(schoolStudent.getId());
                                c.insert();
                                schoolInterestClassesChildMapper.insert(c);
                                successNum++;
                                successMsg.append("<br/>" + successNum + "、身份证号为 " + student.getIdcard() + " 导入成功");
                        }
                    }
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、身份证号为 " + student.getIdcard() + " 导入失败：";
                failureMsg.append(msg);
                log.error(msg, e);
                throw new ServiceException("导入失败");
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共 " + successNum + " 条，数据如下：");
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(successMsg.toString() + "<br/>" + failureMsg.toString());
        }
        return successMsg.toString();
    }

    /**
     * 微信学生报名
     * */
    @Override
    public int addChild(Long interestClassesId) {
        //当前登录学生id
        Long studentId = userInfoUtil.getStudentId();
        //获取兴趣班人数上限
        SchoolInterestClasses classes = classesMapper.selectById(interestClassesId);
        //检查兴趣班已有学生人数
        List<Long> studentIdList = schoolInterestClassesChildMapper.selectAllStudentIdByInterestClassesId(interestClassesId);
        //兴趣班还可容纳人数
        int containNum = classes.getNumberOfPeople() - studentIdList.size();
        if(containNum >= 1) {
            //当前还可报名该兴趣班
            if(studentIdList.contains(studentId)){
                throw new ServiceException("兴趣班下已经有该学员");
            }else{
                //查询id对应的学生信息
                SchoolStudent student = studentMapper.selectById(studentId);
                SchoolInterestClassesChild child = new SchoolInterestClassesChild();
                child.setInterestClassesId(interestClassesId);
                child.setStudentId(studentId);
                child.setStudentName(student.getStudentName());
                child.setIdCard(student.getIdCard());
                child.setCreateBy(userInfoUtil.getParentName());
                return schoolInterestClassesChildMapper.insert(child);
            }
        }else{
            //兴趣班人数已满
            throw new ServiceException("当前兴趣班报名人数已满！");
        }
    }
}
