package com.srs.comprehensive.service.impl;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.common.core.domain.entity.SysRole;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.enums.CampusNameEnum;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.StringUtils;
import com.srs.common.utils.bean.BeanValidators;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.StuDataSelcetDto;
import com.srs.comprehensive.domain.Vo.*;
import com.srs.comprehensive.mapper.*;
import com.srs.comprehensive.util.ListSliceUtil;
import com.srs.system.domain.SysUserRole;
import com.srs.system.domain.vo.StuStatus;
import com.srs.system.mapper.*;
import com.srs.system.service.ISysUserService;
import com.srs.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.service.ISrsStudentService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.validation.Validator;

/**
 * 学生信息Service业务层处理
 *
 * @author srs
 * @date 2023-06-27
 */
@Service
public class SrsStudentServiceImpl extends ServiceImpl<SrsStudentMapper, SrsStudent> implements ISrsStudentService
{
    private static final Logger log = LoggerFactory.getLogger(SrsStudentServiceImpl.class);
    @Autowired
    private SrsStudentMapper srsStudentMapper;
    @Autowired
    private SrsClassMapper srsClassMapper;
    @Autowired
    private InfoStudentMapper infoStudentMapper;
    @Autowired
    protected Validator validator;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;


    @Autowired
    private SysRoleMapper sysRoleMapper;

    private List<SysUser> userList;//用户集合

    //辅导员信息
    @Autowired
    private CphTeacherMapper cphTeacherMapper;

    //岗位
    private SysPostMapper sysPostMapper;

    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SrsMajorsMapper _majorMapper;

    @Autowired
    public SrsGradeMapper _gradeMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;



    @Override
    public AjaxResult doDept(CphSearch param){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            SysDept dept = sysDeptMapper.selectById(param.getDeptId());
            if(dept == null){
                throw new Exception("部门不存在");
            }
            SrsGrade grade = _gradeMapper.selectById(param.getGradeId());
            if(grade == null){
                throw new Exception("年级不存在");
            }
            SysDept college = sysDeptMapper.selectById(param.getCollegeId());
            if(college == null){
                throw new Exception("学院不存在");
            }
            if(!Objects.equals(dept.getParentId(), college.getDeptId())){
                throw new Exception("请选择正确的部门");
            }

            CphSearch stuQuery = new CphSearch();
            stuQuery.setDeptId(college.getDeptId());
            stuQuery.setGradeId(param.getGradeId());
            List<Map<String,Object>> studentList = srsStudentMapper.selectViewStuInfo(stuQuery);
            if(studentList.size() == 0){
                throw new Exception("该年级学院下无学生");
            }

            SysRole stuRole = sysRoleMapper.selectRoleByRoleKey("teststu");
            if(stuRole == null){
                throw new Exception("学生角色不存在");
            }

            for(Map<String,Object> stu : studentList){
                QueryWrapper<SysDept> deptQuery = new QueryWrapper<>();
                deptQuery.eq("dept_name",stu.get("class_name").toString());
                SysDept stuDept = sysDeptMapper.selectOne(deptQuery);
                if(stuDept == null){
                    stuDept = new SysDept();
                    stuDept.setDeptName(stu.get("class_name").toString());
                    stuDept.setParentId(dept.getDeptId());
                    stuDept.setDeptCode(stu.get("class_code").toString());
                    stuDept.setOrderNum(0);
                    int res = sysDeptMapper.insert(stuDept);
                    if(res == 0){
                        throw new Exception("创建"+stu.get("class_name").toString()+"班级部门失败");
                    }
                }

                SysUser user = sysUserMapper.selectUserByUserName(stu.get("stu_no").toString());
                if(user == null){
                    user = new SysUser();
                    user.setUserName(stu.get("stu_no").toString());
                    user.setNickName(stu.get("stu_name").toString());
                    user.setPassword(SecurityUtils.encryptPassword("#A"+stu.get("stu_no").toString()+"A#"));
                    user.setDeptId(stuDept.getDeptId());
                    int res1 = sysUserMapper.insert(user);
                    if(res1 == 0){
                        throw new Exception("创建"+stu.get("stu_name").toString()+"学生用户失败");
                    }else{
                        SysUserRole userRole = new SysUserRole();
                        userRole.setUserId(user.getUserId());
                        userRole.setRoleId(stuRole.getRoleId());
                        int res2 = sysUserRoleMapper.insert(userRole);
                        if(res2 == 0){
                            throw new Exception("创建"+stu.get("stu_name").toString()+"学生角色失败");
                        }
                    }
                }else{
                    user.setDeptId(stuDept.getDeptId());
                    int res3 = sysUserMapper.updateById(user);
                    if(res3 == 0){
                        throw new Exception("更新"+stu.get("stu_name").toString()+"学生用户失败");
                    }
                }
            }


            transactionManager.commit(status);
            return AjaxResult.success();
        }catch(Exception ex){
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<Map<String,Object>> countGradeStuNew(){
        return srsStudentMapper.countGradeStuNew();
    }

    @Override
    public List<Map<String,Object>> countDeptStuNew(){
        return srsStudentMapper.countDeptStuNew();
    }



    @Override
    public List<Map<String,Object>> countMajorStuByDept(CphSearch param){
        return srsStudentMapper.countMajorStuByDept(param);
    }

    @Override
    public List<Map<String,Object>> countDeptGradeStuNew(){
        return srsStudentMapper.countDeptGradeStuNew();
    }


    @Override
    public List<StuCount> countParkStu(){
        return srsStudentMapper.countParkStu();
    }

    @Override
    public List<StuCount> countLakeGradeStu(){
        return srsStudentMapper.countLakeGradeStu();
    }


    @Override
    public List<StuCount> countGoodGradeStu(){
        return srsStudentMapper.countGoodGradeStu();
    }

    @Override
    public List<StuCount> countGoodBiyeGradeStu(){
        return srsStudentMapper.countGoodBiyeGradeStu();
    }

    @Override
    public List<StuCount> countDeptGradeStu(){
        return srsStudentMapper.countDeptGradeStu();
    }

    @Override
    public List<StuCount> countDeptStu(){
        return srsStudentMapper.countDeptStu();
    }


    @Override
    public AjaxResult changeStuInfo(SrsStudent param){
        try{
            QueryWrapper<SrsStudent> query = new QueryWrapper<>();
            query.eq("stu_no",param.getStuNo())
                    .last("limit 1");
            SrsStudent stu = srsStudentMapper.selectOne(query);
            if(stu == null){
                throw new Exception("学号不存在");
            }
            param.setStuId(stu.getStuId());

            SrsStudent dto = new SrsStudent();
            dto.setStuId(param.getStuId());
            dto.setPhone(param.getPhone());
            dto.xhk = param.xhk;
            //dto.setIdCard(param.getIdCard());
            dto.bankAddr = param.bankAddr;
            dto.setBirthday(param.getBirthday());

            int res = srsStudentMapper.updateById(dto);
            if(res == 0){
                throw new Exception("更新失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public SrsStudent getStuInfo(String stuNo){
        QueryWrapper<SrsStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no",stuNo)
                .last("limit 1");
        //SrsStudent stu = srsStudentMapper.selectOne(queryWrapper);
        SrsStudent stu = srsStudentMapper.selectSrsStudentByStuNo(stuNo);
        if(stu == null){
            return null;
        }
        if(stu.getClassId() != null){
            SrsClass srsClass = srsClassMapper.selectById(stu.getClassId());
            if(srsClass != null){
                stu.setSrsClass(srsClass);
                Long gradeId = srsClass.getGradeId();
                if(gradeId != null) {
                    SrsGrade grade = _gradeMapper.selectById(gradeId);
                    if (grade != null) {
                        stu.setGradeName(grade.getGradeName());
                    }
                }

                if(srsClass.getMajorId() != null){
                    SrsMajors major = _majorMapper.selectById(srsClass.getMajorId());
                    if(major != null){
                        stu.setSrsMajors(major);
                        if(major.getCollegeId() != null){
                            SysDept dept = sysDeptMapper.selectById(major.getCollegeId());
                            if(dept != null){
                                stu.setDept(dept);
                            }
                        }
                    }
                }

            }
        }

        return stu;
    }



    /**
     * 查询学生信息
     *
     * @param stuId 学生信息主键
     * @return 学生信息
     */
    @Override
    public SrsStudent selectSrsStudentByStuId(Long stuId)
    {
        return srsStudentMapper.selectSrsStudentByStuId(stuId);
    }
    @Override
    public SrsStudent getSrsStudentByStuNo(String stuNo)
    {
        return srsStudentMapper.selectSrsStudentByStuNo(stuNo);
    }
    @Override
    public SrsStudent getSrsStudentByStuNoNew(String stuNo)
    {
        return srsStudentMapper.selectSrsStudentByStuNoNew(stuNo);
    }
    @Override
    public StuClass getOwnClass(String stuNo){
        List<StuClass> res =  srsStudentMapper.getOwnClass(stuNo);
        if(res.size() != 0){
            return res.get(0);
        }else{
            return null;
        }
    }

    @Override
    public List<SrsStudent> listEnableStu(){
        return srsStudentMapper.listEnableStu();
    }


    /**
     * 通过班级id查询学生列表
     *
     *
     * @return 学生信息
     */
    public List<Map<String,Object>>selectSrsStudentNameList(Long id)
    {
//        SrsStudent srsStudent = new SrsStudent();
//        List<SrsStudent> student = srsStudentMapper.selectSrsStudentList(srsStudent);
//        ArrayList<Object> list = new ArrayList<>();
//
//        for (SrsStudent stu : student) {
//            HashMap<String,Object> hashMap = new HashMap<>();
//            hashMap.put("id",stu.getStuId());
//            System.out.println(hashMap.toString());
//            hashMap.put("name",stu.getName());
//            list.add(hashMap);
//        }

        return  srsStudentMapper.selectSrsStudentNameList(id);
    }
    /**
     * 查询学生信息列表
     *
     * @param srsStudent 学生信息
     * @return 学生信息
     */
    @Override
    public List<SrsStudent> selectSrsStudentList(SrsStudent srsStudent)
    {
        return srsStudentMapper.selectSrsStudentList(srsStudent);
    }
    /**
     * 查询学生信息列表 连表查询
     *
     * @param srsStudent 学生信息
     * @return 学生信息
     */
    @Override
    public List<SrsStudent> selectSrsStudentListJoin(SrsStudent srsStudent) {
        return srsStudentMapper.selectSrsStudentListJoin(srsStudent);
    }

    /**
     *
     * @param stuNO 学号
     * @return
     */
    @Override
    public SrsStudent selectSrsStudentByStuNo(String stuNO) {
        return srsStudentMapper.selectSrsStudentByStuNo(stuNO);
    }

    /**
     * 新增学生信息
     *
     * @param srsStudent 学生信息
     * @return 结果
     */
    @Override
    public int insertSrsStudent(SrsStudent srsStudent)
    {
        srsStudent.setCreateTime(DateUtils.getNowDate());
        return srsStudentMapper.insertSrsStudent(srsStudent);
    }

    /**
     * 修改学生信息
     *
     * @param srsStudent 学生信息
     * @return 结果
     */
    @Override
    public int updateSrsStudent(SrsStudent srsStudent)
    {
        srsStudent.setUpdateTime(DateUtils.getNowDate());
        return srsStudentMapper.updateSrsStudent(srsStudent);
    }

    /**
     * 批量删除学生信息
     *
     * @param stuIds 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteSrsStudentByStuIds(Long[] stuIds)
    {
        return srsStudentMapper.deleteSrsStudentByStuIds(stuIds);
    }

    /**
     * 删除学生信息信息
     *
     * @param stuId 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteSrsStudentByStuId(Long stuId)
    {
        return srsStudentMapper.deleteSrsStudentByStuId(stuId);
    }

    /**
     * 导入学生信息数据
     * @param studentList 学生信息列表
     * @param operName 操作人
     * @return
     */
    @Override
    public String importStudent(List<SrsStudent> studentList, String operName)
    {
        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 (SrsStudent student : studentList )
        {
            try
            {
                // 验证是否存在这个学生
                SrsStudent stu = srsStudentMapper.selectSrsStudentByStuNo(student.getStuNo());
                if (StringUtils.isNull(stu))
                {
                    failureNum++;
                    failureMsg.append("<br/> 学生 " + student.getStuNo() + "学号错误，请检查");
                }
                else{
                    student.setUpdateBy(operName);
                    student.setStuId(stu.getStuId());
                    int res = srsStudentMapper.updateById(student);
                    if(res == 1){
                        successNum++;
                        successMsg.append("<br/> 学生 " + student.getStuNo() + " 更新成功");
                    }else{
                        failureNum++;
                        failureMsg.append("<br/> 学生 " + student.getStuNo() + " 更新失败");
                    }
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 学生 " + student.getStuNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 从中间表同步学生数据
     * @return
     */
    @Transactional
    @Override
    public Map<String, Object> studentDataSync(){
        HashMap<String, Object> map = new HashMap<>();
        int sNum = 0; //成功数量
        int eNum = 0;//失败数量
        List<InfoStudent> infoStudents = infoStudentMapper.queryAll();

        for (InfoStudent student : infoStudents) {
            try {
                SrsClass srsClass = srsClassMapper.selectSrsClassByClassCode(student.getClassCode());
                SrsStudent srsStudent = new SrsStudent();
                srsStudent.setStuNo(student.getStuNo());
                srsStudent.setName(student.getName());
                srsStudent.setClassId(srsClass.getClassId());
                srsStudent.setGender(student.getGender());
                srsStudent.setBirthday(student.getBirthday());
                srsStudent.setPhone(student.getPhone());
                srsStudent.setIdCard(student.getIdCard());
                srsStudent.setRoomId(srsStudent.getRoomId());
                srsStudent.setAddress(student.getAddr());
                int result = srsStudentMapper.insertSrsStudent(srsStudent);

                if (result>0){
                    student.setChmodStatus("2");
                    student.setReadTime(DateUtils.getNowDate());
                    infoStudentMapper.update(student);
                    sNum++;
                }
            }catch (Exception e){
                System.out.println(e);
                eNum++;
            }

        }
        map.put("success",sNum);
        map.put("error",eNum);
        return  map;
    }

    //单个初始化用户密码
    @Override
    public int updateUserPwd(SysUser sysUser1){
        sysUser1.setPassword(SecurityUtils.encryptPassword("#A"+sysUser1.getUserName()+"A#"));
        return sysUserMapper.initializePwdS(sysUser1);
    }

    //批量初始化用户密码
    @Override
    @Transactional
    public int initializePwd() {
        long start = System.currentTimeMillis();
//        List<SrsStudent> srsStudentList = new ArrayList<>();//用户修改集合
//        //查询辅导员
//        CphTeacher cphTeacher = cphTeacherMapper.searchTeacherByTno(getUsername());
//        SysUser sysUser = sysUserMapper.selectUserByUserName(getUsername());
//        //查询岗位
//        SysPost xgc = sysPostMapper.selectPostCode("fdy");
//        //查询用户对应岗位
//        SysUserPost sysUserPost = sysUserPostMapper.selectByUserId(sysUser.getUserId());
//        if (cphTeacher!=null&&sysUserPost.getPostId()==xgc.getPostId()) {
//            //查询班级
//            SrsClass srsClass = new SrsClass();
//            srsClass.setTeacherId(cphTeacher.getTeacherId());
//            List<SrsClass> srsClasses = srsClassMapper.selectSrsClassListTeacherId(srsClass);//班级
//            //查询辅导员所带的班级学生
//            for (SrsClass scs : srsClasses) {
//                SrsStudent srsStudent = new SrsStudent();
//                srsStudent.setClassId(scs.getClassId());
//                srsStudent.setStatus("01");
//                //根据班级id查询学生
//                List<SrsStudent> srsStudentList1 = srsStudentMapper.selectSrsStudentList(srsStudent);
//                srsStudentList.addAll(srsStudentList1);
//            }
//
//        }else if (Objects.equals(getUsername(), "admin")){
//            List<CphTeacher> cphTeachers = cphTeacherMapper.selectCphTeacherList(null);//查询所有辅导员
//            for (CphTeacher ct:cphTeachers){
//                SrsStudent srsStudent = new SrsStudent();
//                srsStudent.setStuNo(ct.getEmployeeId());//辅导员工号
//                srsStudentList.add(srsStudent);
//            }
//            //查询学工处
//
//        }else {
//            throw new RuntimeException("没有权限");
//        }

        List<SysUser> sysUserList = sysUserMapper.selectUserDepId();//用户
        SrsStudent srsStudent1 = new SrsStudent();
        srsStudent1.setStatus("01");
        List<SrsStudent> srsStudentList = srsStudentMapper.selectSrsStudentList(srsStudent1);//学生列表
        for (SysUser su:sysUserList){
             SrsStudent srsStudent = new SrsStudent();
             srsStudent.setStuNo(su.getUserName());
             srsStudentList.add(srsStudent);
        }
        ExecutorService executors = Executors.newFixedThreadPool(200);//创建一个线程池，数量100
        userList=new Vector<>();
        try {
            for (SrsStudent map : srsStudentList) {
                executors.submit(()->{
                    addDefault(map);
                });
            }

            executors.shutdown();//关闭线程池
            executors.awaitTermination(30, TimeUnit.MINUTES);//等待6分钟
            int userListSize=userList.size();
            int sum=userListSize/1000;
            int sums=userListSize%1000;
            if (sums!=0){
                sum++;
            }
            List<List<SysUser>> listList=new ArrayList<>();
            int sumIm=0;
            for (int i=0;i<sum;i++){
                List<SysUser> objects = new ArrayList<>();
                int listSum=1000;
                if (sums!=0&&i==sum-1){
                    listSum=sums;
                }
                for (int j=0;j<listSum;j++){
                    objects.add(userList.get(sumIm));
                    sumIm++;
                }
                listList.add(objects);
            }
//            for (SysUser su:userList){
//                sysUserMapper.initializePwdS(su);
//            }
            for (List<SysUser> userList1:listList){
                sysUserMapper.initializePwdSS(userList1);
            }
        } catch (InterruptedException e) {
            executors.shutdownNow();//强制关闭线程池
            e.printStackTrace();
            throw new ServiceException("系统异常，请重试");
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start));
        return 1;
    }
    private void addDefault(SrsStudent sysUser){
        SysUser sysUser1 = new SysUser();
        sysUser1.setUserName(sysUser.getStuNo());
        sysUser1.setPassword(SecurityUtils.encryptPassword("#A"+sysUser.getStuNo()+"A#"));
//        sysUser1.setUpdateTime(DateUtils.getNowDate());
//        sysUser1.setUpdateBy(getUsername());
        userList.add(sysUser1);
    }

    //sqlserver同步学生数据到mysql
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public List<Map>  sqlserverSynchronousMYSQL(List<Map> mapList){
        //List<SrsStudent> srsStudentList = srsStudentMapper.selectSrsStudentList(null);//学生列表
        List<Map> addMap = new ArrayList<>(mapList);//添加列表
        Long aLong = srsStudentMapper.selectCount(null);//总数
        int pageNum=1;
        int pageSize=500;
        long sum=aLong/ pageSize;//需要循环的次数
        long sumS=aLong%pageSize>0? sum + 1: sum;
        QueryWrapper<SrsStudent> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.orderByDesc("stu_no");
        for (pageNum=1; pageNum <= sumS; pageNum++) {
            List<SrsStudent> srsStudentList = srsStudentMapper
                    .selectPage(new Page<>(pageNum, pageSize), objectQueryWrapper).getRecords();
            List<Map> updateMap = mapList.stream()
                    .filter(obj1 -> srsStudentList
                            .stream().anyMatch(obj2 -> {
                                Object xhObj = obj1.get("xh");
                                if (xhObj != null) {
                                    String xh = xhObj.toString();
                                    return obj2.getStuNo().equals(xh);
                                }
                                return false;
                            }))
                    .collect(Collectors.toList());
            //添加需要
//            List<String> kshList2 = srsStudentList.stream()
//                    .map(SrsStudent::getStuNo)
//                    .collect(Collectors.toList());
//
//            List<Map> insertMap = mapList.stream()
//                    .filter(obj -> {
//                        Object xhObj = obj.get("xh");
//                        return xhObj != null && !kshList2.contains(xhObj.toString());
//                    })
//                    .collect(Collectors.toList());
            Iterator<Map> iterator = addMap.iterator();
            while (iterator.hasNext()) {
                Map map = iterator.next();
                for (Map m : updateMap) {
                    if (map.get("xh").toString().equals(m.get("xh").toString())) {
                        iterator.remove();
                        break;
                    }
                }
            }

            //修改
            List<SrsStudent> updateSrsStudent = new ArrayList<>();
            for (Map map:updateMap){
                SrsStudent srsStudent = new SrsStudent();
                Object xhObj = map.get("xh");
                if (xhObj != null) {
                    srsStudent.setStuNo(xhObj.toString());
                }

                Object xmObj = map.get("xm");
                if (xmObj != null) {
                    srsStudent.setName(xmObj.toString());
                }
                Object xbObj = map.get("xb");
                if (xbObj != null) {
                    srsStudent.setGender(xbObj.toString());
                }
                /*Object sfzhObj = map.get("sfzh");
                if (sfzhObj != null && !Objects.equals(sfzhObj.toString(), "null")) {
                    if (sfzhObj.toString().length()>20){
                        srsStudent.setIdCard(sfzhObj.toString().substring(0,20));
                    }else {
                        srsStudent.setIdCard(sfzhObj.toString());
                    }
                }*/
                Object bjdmObj = map.get("bjdm");
                if (bjdmObj != null) {
                    Long l = srsStudentMapper.selectClassId(bjdmObj.toString());
                    if (l != null) {
                        srsStudent.setClassId(l);
                    }
                    srsStudent.setClassCode(bjdmObj.toString());
                }
                Object jtdzObj = map.get("jtdz");
                if (jtdzObj != null) {
                    srsStudent.setAddress(jtdzObj.toString());
                }
                Object sfzxobj=map.get("sfzx");
                if (sfzxobj!=null) {
                    if(Objects.equals(sfzxobj.toString(), "1"))
                    {
                        srsStudent.setStatus("01");//在校状态
                    }else
                    if(Objects.equals(sfzxobj.toString(), "2"))
                    {
                        srsStudent.setStatus("02");//在校状态
                    }else
                    if(Objects.equals(sfzxobj.toString(), "3"))
                    {
                        srsStudent.setStatus("03");//在校状态
                    }else {
                        srsStudent.setStatus(sfzxobj.toString());//在校状态
                    }
                }
                srsStudent.setUpdateTime(DateUtils.getNowDate());
                updateSrsStudent.add(srsStudent);
            }
            if (updateSrsStudent.size()!=0) {
                List<List<SrsStudent>> lists = ListSliceUtil.updateSlice(updateSrsStudent);
                if (lists != null) {
                    for (List<SrsStudent> studentList : lists) {
                        srsStudentMapper.updateSrsStudentList(studentList);
                    }
                }
            }
        }
        return addMap;
    }
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public List<Map>  synchronousMYSQL(List<Map> mapList){
        //List<SrsStudent> srsStudentList = srsStudentMapper.selectSrsStudentList(null);//学生列表
        List<Map> addMap = new ArrayList<>(mapList);//添加列表
        Long aLong = srsStudentMapper.selectCount(null);//总数
        int pageNum=1;
        int pageSize=500;
        long sum=aLong/ pageSize;//需要循环的次数
        long sumS=aLong%pageSize>0? sum + 1: sum;
        QueryWrapper<SrsStudent> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.orderByDesc("stu_no");
        for (pageNum=1; pageNum <= sumS; pageNum++) {
            List<SrsStudent> srsStudentList = srsStudentMapper
                    .selectPage(new Page<>(pageNum, pageSize), objectQueryWrapper).getRecords();
            List<Map> updateMap = mapList.stream()
                    .filter(obj1 -> srsStudentList
                            .stream().anyMatch(obj2 -> {
                                Object xhObj = obj1.get("xh");
                                if (xhObj != null) {
                                    String xh = xhObj.toString();
                                    return obj2.getStuNo().equals(xh);
                                }
                                return false;
                            }))
                    .collect(Collectors.toList());
            //添加需要
//            List<String> kshList2 = srsStudentList.stream()
//                    .map(SrsStudent::getStuNo)
//                    .collect(Collectors.toList());
//
//            List<Map> insertMap = mapList.stream()
//                    .filter(obj -> {
//                        Object xhObj = obj.get("xh");
//                        return xhObj != null && !kshList2.contains(xhObj.toString());
//                    })
//                    .collect(Collectors.toList());
            Iterator<Map> iterator = addMap.iterator();
            while (iterator.hasNext()) {
                Map map = iterator.next();
                for (Map m : updateMap) {
                    if (map.get("xh").toString().equals(m.get("xh").toString())) {
                        iterator.remove();
                        break;
                    }
                }
            }

            //修改
            List<SrsStudent> updateSrsStudent = new ArrayList<>();
            for (Map map:updateMap){
                SrsStudent srsStudent = new SrsStudent();
                Object xhObj = map.get("xh");
                if (xhObj != null) {
                    srsStudent.setStuNo(xhObj.toString());
                }

                Object xmObj = map.get("xm");
                if (xmObj != null) {
                    srsStudent.setName(xmObj.toString());
                }
                Object xbObj = map.get("xb");
                if (xbObj != null) {
                    srsStudent.setGender(xbObj.toString());
                }
                /*Object sfzhObj = map.get("sfzh");
                if (sfzhObj != null && !Objects.equals(sfzhObj.toString(), "null")) {
                    if (sfzhObj.toString().length()>20){
                        srsStudent.setIdCard(sfzhObj.toString().substring(0,20));
                    }else {
                        srsStudent.setIdCard(sfzhObj.toString());
                    }
                }*/
                Object bjdmObj = map.get("bjdm");
                if (bjdmObj != null) {
                    Long l = srsStudentMapper.selectClassId(bjdmObj.toString());
                    if (l != null) {
                        srsStudent.setClassId(l);
                    }
                    srsStudent.setClassCode(bjdmObj.toString());
                }
//                Object jtdzObj = map.get("jtdz");
//                if (jtdzObj != null) {
//                    srsStudent.setAddress(jtdzObj.toString());
//                }
                Object sfzxobj=map.get("sfzx");
                if (sfzxobj!=null) {
//                    if(Objects.equals(sfzxobj.toString(), "1"))
//                    {
//                        srsStudent.setStatus("01");//在校状态
//                    }else
//                    if(Objects.equals(sfzxobj.toString(), "2"))
//                    {
//                        srsStudent.setStatus("02");//在校状态
//                    }else
//                    if(Objects.equals(sfzxobj.toString(), "3"))
//                    {
//                        srsStudent.setStatus("03");//在校状态
//                    }else {
//                        srsStudent.setStatus(sfzxobj.toString());//在校状态
//                    }
                    srsStudent.setStatus(sfzxobj.toString());
                }
                srsStudent.setUpdateTime(DateUtils.getNowDate());
                updateSrsStudent.add(srsStudent);
            }
            if (updateSrsStudent.size()!=0) {
                List<List<SrsStudent>> lists = ListSliceUtil.updateSlice(updateSrsStudent);
                if (lists != null) {
                    for (List<SrsStudent> studentList : lists) {
                        srsStudentMapper.updateSrsStudentList(studentList);
                    }
                }
            }
        }
        return addMap;
    }

    //添加学生
    @Override
    public void addStudentData(List<Map> mapList){
        List<SrsStudent> insertStudentList = new ArrayList<>();
        for (Map map:mapList){
            SrsStudent srsStudent = new SrsStudent();
            Object xhObj = map.get("xh");
            if (xhObj != null) {
                srsStudent.setStuNo(xhObj.toString());
            }

            Object xmObj = map.get("xm");
            if (xmObj != null) {
                srsStudent.setName(xmObj.toString());
            }

            Object bjdmObj = map.get("bjdm");
            if (bjdmObj != null) {
                Long l = srsStudentMapper.selectClassId(bjdmObj.toString());
                if (l != null) {
                    srsStudent.setClassId(l);
                }
                srsStudent.setClassCode(bjdmObj.toString());
            }

            Object xbObj = map.get("xb");
            if (xbObj != null) {
                srsStudent.setGender(xbObj.toString());
            }

            /*Object sfzhObj = map.get("sfzh");
            if (sfzhObj != null && !Objects.equals(sfzhObj.toString(), "null")) {
                if (sfzhObj.toString().length()>20){
                    srsStudent.setIdCard(sfzhObj.toString().substring(0,20));
                }else {
                    srsStudent.setIdCard(sfzhObj.toString());
                }
            }*/

            Object jtdzObj = map.get("jtdz");
            if (jtdzObj != null) {
                srsStudent.setAddress(jtdzObj.toString());
            }
            Object sfzxobj=map.get("sfzx");
            if (sfzxobj!=null) {
//                if(Objects.equals(sfzxobj.toString(), "1"))
//                {
//                    srsStudent.setStatus("01");//在校状态
//                }else
//                if(Objects.equals(sfzxobj.toString(), "2"))
//                {
//                    srsStudent.setStatus("02");//在校状态
//                }else
//                if(Objects.equals(sfzxobj.toString(), "3"))
//                {
//                    srsStudent.setStatus("03");//在校状态
//                }else {
//                    srsStudent.setStatus(sfzxobj.toString());//在校状态
//                }
                srsStudent.setStatus(sfzxobj.toString());
            }
            srsStudent.setDelFlag("0");
            srsStudent.setCreateTime(DateUtils.getNowDate());
            insertStudentList.add(srsStudent);
        }
        if (insertStudentList.size()!=0) {
            srsStudentMapper.insertBatchSomeColumn(insertStudentList);
        }
    }

    @Autowired
    private SysUserServiceImpl sysUserService;

    //同步到用户表
    public void Usertb() {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            // 查询所有在校学生(查询各年级的学生)
            SrsStudent param = new SrsStudent();
            param.setStatus("01");
            List<SrsStudent> studentList = srsStudentMapper.selectSrsStudentList(param);
            if (studentList.isEmpty()) {
                throw new Exception("没有在校生数据");
            }

            // 获取所有学生学号
            List<String> stuNos = studentList.stream()
                    .map(SrsStudent::getStuNo)
                    .collect(Collectors.toList());

            // 查询已存在的用户
            QueryWrapper<SysUser> userQuery = new QueryWrapper<>();
            userQuery.in("user_name", stuNos);
            List<SysUser> existingUsers = sysUserMapper.selectList(userQuery);

            // 转换为Map以快速查找
            Map<String, SysUser> userMap = existingUsers.stream()
                    .collect(Collectors.toMap(SysUser::getUserName, user -> user));

            List<SysUser> insertList = new ArrayList<>();
            List<SysUser> updateList = new ArrayList<>();

            // 处理每个学生记录
            for (SrsStudent student : studentList) {
                String stuNo = student.getStuNo();
                SysUser existingUser = userMap.get(stuNo);

                if (existingUser != null) {
                    // 更新现有用户
                    existingUser.setNickName(student.getName());
                    existingUser.setSex(Objects.equals(student.getGender(), "男") ? "0" : "1");
                    updateList.add(existingUser);
                } else {
                    // 创建新用户
                    SysUser newUser = new SysUser();
                    newUser.setUserName(stuNo);
                    newUser.setNickName(student.getName());
                    newUser.setSex(Objects.equals(student.getGender(), "男") ? "0" : "1");
                    newUser.setPassword(SecurityUtils.encryptPassword("#A" + stuNo + "A#"));
                    insertList.add(newUser);
                }
            }

            // 批量插入新用户
            if (!insertList.isEmpty()) {
                boolean res = sysUserService.saveBatch(insertList);
                if(!res){
                    throw new Exception("用户插入失败");
                }
                // 插入用户角色关联
                insertUserrole(insertList);
            }

            // 批量更新现有用户
            if (!updateList.isEmpty()) {
                boolean res = sysUserService.updateBatchById(updateList);
                if(!res){
                    throw new Exception("用户更新失败");
                }
            }

            // 提交事务
            transactionManager.commit(status);
        } catch (Exception ex) {
            // 回滚事务
            transactionManager.rollback(status);
            // 记录异常信息
            log.error("同步学生信息到用户表失败", ex);
            // 可以选择抛出自定义异常
            throw new RuntimeException("同步学生信息失败", ex);
        }
    }


    public void insertUserrole(List<SysUser> insertUser){
        List<SysUserRole> userRoleList=new ArrayList<>();
        for (SysUser sysUser:insertUser){
            SysUserRole sysRole = new SysUserRole();
            sysRole.setUserId(sysUser.getUserId());
            sysRole.setRoleId(101L);
            userRoleList.add(sysRole);
        }
        sysUserRoleMapper.batchUserRole(userRoleList);
    }


    @Override
    public List<DeptLeaveDataVo> getDeptLeveaDataCount() {
        return srsStudentMapper.selectDeptLeveaDataCount();
    }

    @Override
    public SysUser getTeacherByStuNo(String stuNo) {
        return sysUserMapper.selectTeacherByStuNo(stuNo);
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getStuQuitSchoolCount() {
        return srsStudentMapper.selectStuQuitSchoolCount();
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getStuDropOutSchoolCount() {
        return srsStudentMapper.selectStuDropOutSchoolCount();
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getStuPunishCount() {
        return srsStudentMapper.selectStuPunishCount();
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getKnrdCount() {
        return srsStudentMapper.selectKnrdCount();
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getZxjCount() {
        return srsStudentMapper.selectZxjCount();
    }

    @Override
    public List<DeptStuQuitPunisDataVo> getDeptCountByCampus(String campusName) {
        if (campusName.equals(CampusNameEnum.CHANGGANG)){
            return srsStudentMapper.selectDeptCountByCampusLJ();
        }else {
            return srsStudentMapper.selectDeptCountByCampusCG();
        }
    }

    @Override
    public List<GradeStuDataVo> getGradeCount() {
        return srsStudentMapper.selectGradeCount();
    }
    @Override
    public List<RtStuQuitSchoolVo> getRtStuQuitSchool(StuDataSelcetDto stuDataSelcetDto){
        return  srsStudentMapper.getRtStuQuitSchool(stuDataSelcetDto);
    }
    @Override
   public List<RtStuDisciplinaryApplicationVo> getRtStuDisciplinaryApplication(StuDataSelcetDto stuDataSelcetDto){
        List<RtStuDisciplinaryApplicationVo> rtStuDisciplinaryApplication = srsStudentMapper.getRtStuDisciplinaryApplication(stuDataSelcetDto);
        return rtStuDisciplinaryApplication;
    }

    @Override
    public List<RtStuDropOutSchoolVo> getRtStuDropOutSchool(StuDataSelcetDto stuDataSelcetDto) {
        return  srsStudentMapper.getRtStuDropOutSchool(stuDataSelcetDto);
    }
    @Override
    public List<SrsKnrdApplyVo> getSrsKnrdApply(StuDataSelcetDto stuDataSelcetDto){
        return srsStudentMapper.getSrsKnrdApply(stuDataSelcetDto);
    }
    @Override
   public List<SrsZxjApplyVo> getSrsZxjApply(StuDataSelcetDto stuDataSelcetDto){
        return srsStudentMapper.getSrsZxjApply(stuDataSelcetDto);
    }
    @Override
    public List<Map<String,Object>> countStuMZ(){
        return srsStudentMapper.countStuMZ();
    }
    @Override
    public  List<Map<String,Object>> getSrsHZCount(){
        return srsStudentMapper.getSrsHZCount();
    }
    @Override
    public  List<Map<String,Object>> getSrsZZCount(){
        return  srsStudentMapper.getSrsZZCount();
    }
    @Override
    public  List<Map<String,Object>> getSrsGenderCount(){
        return srsStudentMapper.getSrsGenderCount();
    }
    @Override
    public  List<Map<String,Object>> getSrsknrdCount(){
        return srsStudentMapper.getSrsknrdCount();
    }
    @Override
    public List<Map<String,Object>> getSrsAgeCount(){
        return srsStudentMapper.getSrsknrdCount();
    }
    @Override
    public List<Map<String,Object>> getCountbyCity(){
        return srsStudentMapper.getCountbyCity();
    }
    @Override
    public List<Map<String,Object>> getSchoolCountbyGrade(){
        return srsStudentMapper.getSchoolCountbyGrade();
    }
    @Override
    public List<Map<String,Object>> getSchoolTotalCount(){
        return srsStudentMapper.getSchoolTotalCount();
    }
    @Override
    public List<Map<String,Object>> getNotSchoolTotalCount(){
        return  srsStudentMapper.getNotSchoolTotalCount();
    }
    @Override
    public  List<Map<String,Object>> getMajorsCount(){
        return  srsStudentMapper.getMajorsCount();
    }
    @Override
    public List<Map<String,Object>> getFiveSchoolTotalCount(){
        return  srsStudentMapper.getFiveSchoolTotalCount();
    }
    @Override
    public List<StuStatus> statusList(){
       return  srsStudentMapper.statusList();
    }
}
