package com.srs.comprehensive.service.impl;

import ch.qos.logback.classic.LoggerContext;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.mapper.*;
import com.srs.comprehensive.service.GxsdxySjzx005XsxxService;
import com.srs.comprehensive.service.ISrsMajorsService;
import com.srs.system.domain.SysUserRole;
import com.srs.system.mapper.SysDeptMapper;
import com.srs.system.mapper.SysRoleMapper;
import com.srs.system.mapper.SysUserRoleMapper;
import com.srs.system.service.ISysUserService;
import org.apache.commons.lang3.ThreadUtils;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;

/**
 * (GxsdxySjzx005Xsxx)表服务实现类
 *
 * @author Chao
 * @since 2023-07-31 10:41:09
 */
@Service("gxsdxySjzx005XsxxService")
public class GxsdxySjzx005XsxxServiceImpl implements GxsdxySjzx005XsxxService {
    @Resource
    private GxsdxySjzx005XsxxMapper gxsdxySjzx005XsxxMapper;

    @Autowired
    Gxsdxy01ZzjgMapper gxsdxy01ZzjgMapper;

    @Autowired
    private SrsMajorsMapper srsMajorsMapper;

    @Autowired
    private SrsClassMapper srsClassMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SrsGradeMapper srsGradeMapper;

    @Autowired
    private SrsStudentMapper srsStudentMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private  ClassCounMapper classCounMapper;

    @Autowired
    private  CphTeacherMapper cphTeacherMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;




    /**
     * 查询所有数据
     *
     * @return 实例对象集合
     */
    @Override
    public List<GxsdxySjzx005Xsxx> queryAll() {
        return this.gxsdxySjzx005XsxxMapper.queryAll();
    }

    /**
     * 同步专业信息
     * @return
     */
    @Transactional
    @Override
    public Map<String, Integer> majorDataSync() {
        HashMap<String, Integer> map = new HashMap<>();
        int success =0;
        int error =0;
        List<GxsdxySjzx005Xsxx> majors = gxsdxySjzx005XsxxMapper.selectMajorAll();
        for (GxsdxySjzx005Xsxx major : majors) {
            try {
                SrsMajors majorCode = srsMajorsMapper.selectSrsMajorsByMajorCode(major.getZybh());
                SrsMajors srsMajors = new SrsMajors();
                srsMajors.setMajorCode(major.getZybh());
                srsMajors.setMajorName(major.getZymc());
                Gxsdxy01Zzjg xy = gxsdxy01ZzjgMapper.selectDeptByName(major.getDwmc());
                SysDept sysDept = sysDeptMapper.selectDeptByDeptCode(xy.getBmbh());
                sysDept.getParentId();
                srsMajors.setCollegeId(sysDept.getDeptId());
                if (majorCode != null){
                    srsMajorsMapper.updateSrsMajors(srsMajors);
                }else {
                    srsMajorsMapper.insertSrsMajors(srsMajors);
                }
                success++;
            }catch (Exception e){
                error++;
                System.out.println(e);
            }
        }
        map.put("success",success);
        map.put("error",error);
        return map;
    }

    /**
     * 同步班级信息
     * @return
     */
    @Transactional
    @Override
    public Map<String, Integer> classDataSync() {
        int update =0;
        int insert =0;
        HashMap<String, Integer> map = new HashMap<>();
        try {
            List<GxsdxySjzx005Xsxx> classAll = gxsdxySjzx005XsxxMapper.selectClassAll();
            List<SrsClass> classList = srsClassMapper.selectSrsClassList(null);
            List<SrsGrade> gradeList = srsGradeMapper.selectSrsGradeList(null);
            List<SrsMajors> majorsList = srsMajorsMapper.selectSrsMajorsList(null);
            List<ClassCoun> classCouns = classCounMapper.queryAll();
            List<CphTeacher> teacherList = cphTeacherMapper.selectCphTeacherList(null);

            List<SrsClass> insertClass = new ArrayList<>();
            List<SrsClass> updateClass = new ArrayList<>();
            // 创建一个固定大小的线程池，最大线程数为 10
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            Object lock = new Object(); // 定义一个对象作为锁
            for (GxsdxySjzx005Xsxx cl : classAll) {
                executorService.submit(() -> {
                        Optional<SrsClass> classes = classList.stream()
                                .filter(obj -> obj.getClassCode().equals(cl.getBjbh()))
                                .findFirst();
                        SrsClass srsClass = new SrsClass();
                        srsClass.setClassCode(cl.getBjbh());
                        srsClass.setClassName(cl.getBjmc());

                        Optional<SrsGrade> srsGrade = gradeList.stream()
                                .filter(obj -> obj.getGradeCode().equals(cl.getSznj()))
                                .findFirst();
                        srsClass.setGradeId(srsGrade.get().getGradeId());

                        Optional<SrsMajors> srsMajors = majorsList.stream()
                                .filter(obj -> obj.getMajorCode().equals(cl.getZybh()))
                                .findFirst();
                        srsClass.setMajorId(srsMajors.get().getMajorId());

                        Optional<ClassCoun> calssTeacher = classCouns.stream()
                                .filter(obj -> obj.getClassCode().equals(cl.getBjbh()))
                                .findFirst();

                        Optional<CphTeacher> teacher = teacherList.stream()
                                .filter(obj -> obj.getEmployeeId().equals(calssTeacher.get().getCounCode()))
                                .findFirst();
                        srsClass.setTeacherId(teacher.get().getTeacherId());
                    synchronized (lock) { // 使用 synchronized 关键字对关键代码块进行线程同步
                        if (classes != null) {
                            updateClass.add(srsClass);
//                        srsClassMapper.updateSrsClass(srsClass);
                        } else {
//                        srsClassMapper.insertSrsClass(srsClass);
                            insertClass.add(srsClass);

                        }
                        }

                    });

            }
            executorService.shutdown();
            try {
                executorService.awaitTermination(10, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                executorService.shutdownNow();//强制关闭线程池
                System.out.println(e);
                throw new ServiceException("错误");
            }

            if (!insertClass.isEmpty()) {
                insert  = srsClassMapper.batchInsert(insertClass);

                    System.out.println("插入数量"+insert );

            }

            if (!updateClass.isEmpty()) {
                int i = srsClassMapper.batchUpdate(updateClass);
                if (i>0){
                    update = updateClass.size();
                    System.out.println("更新数量"+update);
                }
            }

        }catch (Exception e){
            System.out.println(e);
        }


        map.put("update",update);
        map.put("insert",insert);
        return map;

    }

    /**
     * 同步学生信息
     * @return
     */
    @Override
    @Transactional
    public Map<String, Integer> studentDataSync() {
        long start = System.currentTimeMillis();
        HashMap<String, Integer> map = new HashMap<>();
        int update=0;
        int insert=0;
        try{
            List<SrsStudent> insertStudents = new ArrayList<>();
            List<SrsStudent> updateStudents = new ArrayList<>();
            List<SysUser> insertUsers = new ArrayList<>();
            List<GxsdxySjzx005Xsxx> students = queryAll();
            List<SrsStudent> studentList = srsStudentMapper.selectSrsStudentList(null);
            List<SrsClass> classList = srsClassMapper.selectSrsClassList(null);
            List<SysDept> deptList = sysDeptMapper.selectAll();
            // 创建一个固定大小的线程池，最大线程数为 10
            ExecutorService executorService = Executors.newFixedThreadPool(50);
            Object lock = new Object(); // 定义一个对象作为锁
            AtomicInteger counter = new AtomicInteger(students.size());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            SysUser sysUser1 = new SysUser();
            List<SysUser> sysUsers = sysUserService.selectUserList(sysUser1);
            for (GxsdxySjzx005Xsxx student : students) {
                executorService.submit(() -> {
                    counter.decrementAndGet();
//
                        SrsStudent srsStudent = new SrsStudent();
                        srsStudent.setName(student.getXm());
                        srsStudent.setGender(student.getXbdmmc());
                        srsStudent.setStuNo(student.getXh());
                        srsStudent.setStatus(student.getXsdqztdm());
                        srsStudent.setGender(student.getXbdmmc());
                        Optional<SrsClass> srsClass = classList.stream()
                                .filter(obj -> obj.getClassCode().equals(student.getBjbh()))
                                .findFirst();
                        srsStudent.setClassId (srsClass.get().getClassId());


                        boolean stu = studentList.stream()
                                .anyMatch(obj -> obj.getStuNo().equals(student.getXh()));
                    // 使用 synchronized 关键字对关键代码块进行线程同步
                            synchronized (lock) {
                                if (stu) {
                                updateStudents.add(srsStudent);



                                } else {
                                    insertStudents.add(srsStudent);
                                    if (student.getXsdqztdm().equals("01")) {
                                        boolean b = sysUsers.stream().anyMatch(obj -> obj.getUserName().equals(student.getXh()));
                                        if (!b){
                                            SysUser sysUser = new SysUser();
                                            sysUser.setUserName(student.getXh());
                                            sysUser.setPassword(passwordEncoder.encode(student.getXh()));
                                            sysUser.setNickName(student.getXm());
//                                        insertUsers.add(sysUser);
                                            //                                Optional<SysDept> sysDept = deptList.stream()
                                            //                                        .filter(obj -> obj.getDeptCode().equals(student.getBjbh()))
                                            //                                        .findFirst();
                                            //                                sysUser.setDeptId(sysDept.get().getDeptId());
                                            Long[] role = {101L};
                                            sysUser.setRoleIds(role);
                                            synchronized (lock) {
                                                sysUserService.insertUser(sysUser);
                                            }

                                        }


                                    }

                                }
                            }

                        int remainingTasks = counter.get();
                        System.out.println("剩余任务数量：" + remainingTasks);

                });



            }
            executorService.shutdown();
            try {

                executorService.awaitTermination(30, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                executorService.shutdownNow();//强制关闭线程池
                System.out.println(e);
                throw new ServiceException("错误");
            }

            if (!insertStudents.isEmpty()) {
                int i  = srsStudentMapper.batchInsertSrsStudent(insertStudents);

                if (i>0){
                    insert = insertStudents.size();
                    System.out.println("插入数量"+insert);
                }
            }
//            if (!insertUsers.isEmpty()) {
//                List<Long> longs = sysUserService.batchUser(insertUsers);
//                List<SysUserRole> sysUserRoles = new ArrayList<>();
//                for (Long l : longs) {
//                    SysUserRole sysUserRole = new SysUserRole();
//                    sysUserRole.setRoleId(101L);
//                    sysUserRole.setUserId(l);
//                    sysUserRoles.add(sysUserRole);
//                }
//                sysUserRoleMapper.batchUserRole(sysUserRoles);
//            }
            if (!updateStudents.isEmpty()) {
                int i = srsStudentMapper.batchUpdateSrsStudent(updateStudents);
                if (i>0){
                    update = updateStudents.size();
                    System.out.println("更新数量"+update);
                }
            }

        }catch (Exception e){
            System.out.println(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start));
        map.put("insert",insert);
        map.put("update",update);
        return map;

    }



}

