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.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.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.CphExport;
import com.srs.comprehensive.domain.Vo.*;
import com.srs.comprehensive.mapper.ClassCounMapper;
import com.srs.comprehensive.mapper.Gxsdxy02JzgxxMapper;
import com.srs.comprehensive.mapper.InfoTeacherMapper;
import com.srs.comprehensive.util.ListSliceUtil;
import com.srs.system.domain.QgzxTeacher;
import com.srs.system.domain.SysPost;
import com.srs.system.domain.SysUserRole;
import com.srs.system.mapper.QgzxTeacherMapper;
import com.srs.system.mapper.SysRoleMapper;
import com.srs.system.mapper.SysUserMapper;
import com.srs.system.mapper.SysUserRoleMapper;
import com.srs.system.service.ISysDeptService;
import com.srs.system.service.ISysPostService;
import com.srs.system.service.ISysRoleService;
import com.srs.system.service.ISysUserService;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.CphTeacherMapper;
import com.srs.comprehensive.service.ICphTeacherService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 辅导员信息Service业务层处理
 *
 * @author srs
 * @date 2023-07-03
 */
@Service
public class CphTeacherServiceImpl implements ICphTeacherService
{
    @Autowired
    private CphTeacherMapper cphTeacherMapper;
    @Autowired
    private QgzxTeacherMapper qgzxTeacherMapper;

    @Autowired
    private Gxsdxy02JzgxxMapper teacherMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysPostService sysPostService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ClassCounMapper classCounMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<Map<String,Object>> getOwnUnTodoCount(String tno){
        return  cphTeacherMapper.getOwnUnTodoCount(tno);
    }

    @Override
    public List<CphTeacherLookScore> listIam(String tno){
        return cphTeacherMapper.listIam(tno);
    }


    @Override
    public List<CphTeacherLookScore> listClassTwo(String tno){
        return cphTeacherMapper.listClassTwo(tno);
    }

    @Override
    public List<CphTeacherLookScore> listCe(String tno){
        return cphTeacherMapper.listCe(tno);
    }

    @Override
    public CphTeacher searchTeacherByEmployeeId(String tno) {
        return cphTeacherMapper.searchTeacherByTno(tno);
    }

    /**
     * 查询辅导员信息
     *
     * @param teacherId 辅导员信息主键
     * @return 辅导员信息
     */
    @Override
    public CphTeacher selectCphTeacherByTeacherId(Long teacherId)
    {
        return cphTeacherMapper.selectCphTeacherByTeacherId(teacherId);
    }

    @Override
    public List<CphTeacherLookScore> listSport(String tno){
        return cphTeacherMapper.listSport(tno);
    }

    @Override
    public List<CphRecord> getIamRecordByStuNo(String stuNo){
        return cphTeacherMapper.getIamRecordByStuNo(stuNo);
    }

    @Override
    public List<CphTeacherLookScore> listCourse(String tno){
        return cphTeacherMapper.listCourse(tno);
    }

    @Override
    public List<CphTeacherOwnStu> listOwnStu(String tNo){
        return cphTeacherMapper.listOwnStu(tNo);
    }

    @Override
    public List<SrsMajors> listOwnMajor(String tNo){
        return cphTeacherMapper.listOwnMajor(tNo);
    }

    @Override
    public List<SrsGrade> listOwnGrade(String tNo){
        return cphTeacherMapper.listOwnGrade(tNo);
    }


    @Override
    public CountStu countOwnStu(CphSearch param){
        return cphTeacherMapper.countOwnStu(param);
    }

    @Override
    public CountStu countLiveStu(CphSearch param){
        return cphTeacherMapper.countLiveStu(param);
    }


    @Override
    public List<CphClassRankScore> countOwnHisClass(CphSearch param){
        return cphTeacherMapper.countOwnHisClass(param);
    }

    @Override
    public List<Map> countOwnHisAsClass(CphSearch param) {
        return cphTeacherMapper.countOwnHisAsClass(param);
    }


    /**
     * 查询辅导员信息列表
     *
     * @param cphTeacher 辅导员信息
     * @return 辅导员信息
     */
    @Override
    public List<CphTeacher> selectCphTeacherList(CphTeacher cphTeacher)
    {
        return cphTeacherMapper.selectCphTeacherList(cphTeacher);
    }

    /**
     * 查询辅导员名字列表
     *
     * @param
     * @return 辅导员信息
     */
    @Override
    public List<Object> selectCphTeacherNameList()
    {
        List<CphTeacher> cphTeachers = cphTeacherMapper.selectCphTeacherNameList();

        ArrayList<Object> objects = new ArrayList<>();
        for (CphTeacher cphTeacher : cphTeachers) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name",cphTeacher.getName());
            map.put("tno",cphTeacher.getEmployeeId());
            map.put("id",cphTeacher.getTeacherId());
            objects.add(map);
        }
        return objects;


    }
    /**
     * 新增辅导员信息
     *
     * @param cphTeacher 辅导员信息
     * @return 结果
     */
    @Override
    public int insertCphTeacher(CphTeacher cphTeacher)
    {
        cphTeacher.setCreateTime(DateUtils.getNowDate());
        return cphTeacherMapper.insertCphTeacher(cphTeacher);
    }

    /**
     * 修改辅导员信息
     *
     * @param cphTeacher 辅导员信息
     * @return 结果
     */
    @Override
    public int updateCphTeacher(CphTeacher cphTeacher)
    {
        cphTeacher.setUpdateTime(DateUtils.getNowDate());
        return cphTeacherMapper.updateCphTeacher(cphTeacher);
    }

    /**
     * 批量删除辅导员信息
     *
     * @param teacherIds 需要删除的辅导员信息主键
     * @return 结果
     */
    @Override
    public int deleteCphTeacherByTeacherIds(Long[] teacherIds)
    {
        return cphTeacherMapper.deleteCphTeacherByTeacherIds(teacherIds);
    }

    /**
     * 删除辅导员信息信息
     *
     * @param teacherId 辅导员信息主键
     * @return 结果
     */
    @Override
    public int deleteCphTeacherByTeacherId(Long teacherId)
    {
        return cphTeacherMapper.deleteCphTeacherByTeacherId(teacherId);
    }

    /**
     * 同步辅导员信息
     * @return 成功行数
     */
    @Override
    @Transactional
    public Map<String, Integer> teacherDataSync(){


        HashMap<String, Integer> map = new HashMap<>();
        int update =0;
        int insert =0;
        try {
            InfoTeacher infoTeacher = new InfoTeacher();
            infoTeacher.setChmodStatus("1");
            List<Gxsdxy02Jzgxx> teacherAll = teacherMapper.queryAll();
            List<CphTeacher> teacherList = cphTeacherMapper.selectCphTeacherList(null);
            List<ClassCoun> classCouns = classCounMapper.queryAll();
            SysDept sysDept = new SysDept();
            List<SysDept> deptList = sysDeptService.selectDeptList(sysDept);
            List<CphTeacher> insertTeacher = new ArrayList<>();
            List<CphTeacher> updateTeacher = new ArrayList<>();
            // 创建一个固定大小的线程池，最大线程数为 10
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            Object lock = new Object(); // 定义一个对象作为锁
            for (Gxsdxy02Jzgxx teacher : teacherAll) {
                executorService.submit(() -> {
                    CphTeacher cphTeacher = new CphTeacher();
                    cphTeacher.setName(teacher.getXm());
                    cphTeacher.setGender(teacher.getXbdmmc());
                    cphTeacher.setEmployeeId(teacher.getGh());
//                    Optional<SysDept> techerdept = deptList.stream()
//                            .filter(obj -> obj.getDeptCode().equals(teacher.getBmbh()))
//                            .findFirst();
//                    cphTeacher.setDeptId(techerdept.orElse(new SysDept()).getDeptId());
                    // 搜索元素 "banana"
//                    Optional<SysDept> result = deptList.stream().filter(item -> item.getDeptCode().equals(teacher.getBmbh())).findFirst();
//
//                    // 检查是否找到匹配的元素，并进行相应的处理
//                    if (result.isPresent()) {
//                        System.out.println("找到了匹配的元素: " + result.get());
//                    } else {
//                        System.out.println("未找到匹配的元素");
//                    }
//                    cphTeacher.setDeptId(result.orElse(new SysDept()).getDeptId());
                    Long deptId = sysDeptService.selectDeptByDeptCode(teacher.getBmbh()).getDeptId();
                    cphTeacher.setDeptId(deptId);
                    cphTeacher.setStatus(teacher.getZzztdm());

                    boolean t = teacherList.stream().anyMatch(obj -> obj.
                            getEmployeeId().equals(teacher.getGh()));

                    synchronized (lock) {
                        if (t) {
                            //cphTeacherMapper.updateCphTeacher(cphTeacher);
//                            updateTeacher.add(cphTeacher);
                            boolean t2 = classCouns.stream().anyMatch(obj -> obj.getCounCode().equals(teacher.getGh()));
                            if (t2) {
                                SysUser sysUser = new SysUser();
                                sysUser.setPassword(SecurityUtils.encryptPassword(teacher.getGh()));
                                sysUser.setUserName(teacher.getGh());
                                sysUser.setNickName(teacher.getXm());
                                sysUser.setDeptId(deptId);
                                Long[] role = {102L};
                                sysUser.setRoleIds(role);
                                // 创建并初始化 long 数组
                                Long[] post = {3L};
                                sysUser.setPostIds(post);
                                sysUserService.insertUser(sysUser);
                            }
                        }else {
                            cphTeacherMapper.insertCphTeacher(cphTeacher);

//                            insertTeacher.add(cphTeacher);

                        }
                    }
                });



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

        return map;
    }

    //同步辅导员
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sqlserverSynchronousMYSQL(List<Map> list) {
        //辅导员列表
        List<CphTeacher> cphTeachers = cphTeacherMapper.selectTeacherList();
        //查找重复值
        List<Map> updateMap = list.stream()
                .filter(obj1 -> cphTeachers
                        .stream().anyMatch(obj2 -> {
                            Object xhObj = obj1.get("zgh");
                            if (xhObj != null) {
                                String zgh = xhObj.toString();
                                return obj2.getEmployeeId().equals(zgh);
                            }
                            return false;
                        }))
                .collect(Collectors.toList());

        //添加需要
        List<String> kshList2 = cphTeachers.stream()
                .map(CphTeacher::getEmployeeId)
                .collect(Collectors.toList());

        List<Map> insertMap = list.stream()
                .filter(obj -> {
                    Object xhObj = obj.get("zgh");
                    return xhObj != null && !kshList2.contains(xhObj.toString());
                })
                .collect(Collectors.toList());
        //添加
        List<CphTeacher> insertStudentList = new ArrayList<>();
        for (Map map:insertMap){
            CphTeacher cphTeacher = new CphTeacher();
            Object xmObj = map.get("xm");
            if (xmObj != null) {
                cphTeacher.setName(xmObj.toString());
            }
            Object xbObj = map.get("xb");
            if (xbObj != null) {
                String s = xbObj.toString();
                if (!Objects.equals(s, "NULL") && !Objects.equals(s, "null")&&!Objects.equals(s," ")) {
                    cphTeacher.setGender(xbObj.toString());
                }
            }
            Object zghObj = map.get("zgh");
            if (zghObj != null) {
                cphTeacher.setEmployeeId(zghObj.toString());
            }
            //学院id
            Object yxdmObj = map.get("yxdm");
            if (yxdmObj!=null) {
                Long deptId = cphTeacherMapper.selectDeptCode(yxdmObj.toString());
                if (deptId != null) {
                    cphTeacher.setDeptId(deptId);
                }
            }
            cphTeacher.setStatus("1");
            cphTeacher.setCreateTime(DateUtils.getNowDate());
            insertStudentList.add(cphTeacher);
        }
        if (insertStudentList.size()!=0) {
            cphTeacherMapper.insertBatchSomeColumn(insertStudentList);
        }
        //修改
        List<CphTeacher> updateSrsStudent = new ArrayList<>();
        for (Map map:updateMap){
            CphTeacher cphTeacher = new CphTeacher();
            Object xmObj = map.get("xm");
            if (xmObj != null) {
                cphTeacher.setName(xmObj.toString());
            }
            Object xbObj = map.get("xb");
            if (xbObj != null) {
                String s = xbObj.toString();
                if (!Objects.equals(s, "NULL") && !Objects.equals(s, "null")&&!Objects.equals(s," ")) {
                    cphTeacher.setGender(xbObj.toString());
                }
            }
            Object zghObj = map.get("zgh");
            if (zghObj != null) {
                cphTeacher.setEmployeeId(zghObj.toString());
            }
            //学院id
            Object yxdmObj = map.get("yxdm");
            if (yxdmObj!=null) {
                Long ksh = cphTeacherMapper.selectDeptCode(yxdmObj.toString());
                if (ksh != null) {
                    cphTeacher.setDeptId(ksh);
                }
            }
            cphTeacher.setUpdateTime(DateUtils.getNowDate());
            updateSrsStudent.add(cphTeacher);
        }
        /*if (updateSrsStudent.size()!=0) {
            List<List<CphTeacher>> lists = ListSliceUtil.updateSlice(updateSrsStudent);
            if (lists != null) {
                for (List<CphTeacher> studentList : lists) {
                    cphTeacherMapper.updateSrsClassList(studentList);
                }
            }
        }*/



    }

    //同步教职工表
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synchronousMYSQL(List<Map> list) {
        List<QgzxTeacher> insertTeacherList = new ArrayList<>();//添加集合
        List<QgzxTeacher> updateTeacherList = new ArrayList<>();//修改集合
        for (Map<String, Object> map : list) {
            String zgh = (String) map.get("zgh");
            String xm=(String) map.get("xm");
            String xb=(String) map.get("xb");
            String ksh=(String) map.get("ksh");
            String zgzt=(String) map.get("zgzt");
            QgzxTeacher qgzxTeacher = qgzxTeacherMapper.selectQgzxTeacherByEmployeeId(zgh);
            Long deptId = qgzxTeacherMapper.selectDeptCode(ksh);
            QgzxTeacher entity=new QgzxTeacher();
            entity.setEmployeeId(zgh);
            entity.setName(xm);
            entity.setGender(xb);
            if(deptId!=null) {
                entity.setDeptId(deptId);
            }
            entity.setStatus(zgzt);
            entity.setCreateTime(DateUtils.getNowDate());
            if(qgzxTeacher==null){
                //qgzxTeacherMapper.insertQgzxTeacher(entity);
                insertTeacherList.add(entity);
            }else{
                entity.setEmployeeId(zgh);
                entity.setUpdateTime(DateUtils.getNowDate());
                //qgzxTeacherMapper.updateQgzxTeacherNew(entity);
                updateTeacherList.add(entity);
            }
        }
        if(insertTeacherList.size()!=0){
            qgzxTeacherMapper.insertBatchSomeColumn(insertTeacherList);
        }
        if(updateTeacherList.size()!=0){
            qgzxTeacherMapper.updateBatchSomeColumn(updateTeacherList);
        }
    }

    //同步到用户表
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void Usertb(){
        //同步到user表
        List<CphTeacher> cphTeachers = cphTeacherMapper.selectTeacherList();//所有职工
        List<SysUser> sysUserList = sysUserMapper.selectUserLisrS();//所以用户
        List<SysUser> insertUser = new ArrayList<>();//需要添加的集合
        List<SysUser> updateUser = new ArrayList<>();//需要修改的集合
        for (CphTeacher cphTeacher:cphTeachers){
            int i=0;//添加标记
            for (SysUser sysUser:sysUserList){
                //修改
                if (Objects.equals(cphTeacher.getEmployeeId(), sysUser.getUserName())){
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setUserName(cphTeacher.getEmployeeId());
                    sysUser1.setDeptId(cphTeacher.getDeptId());
                    updateUser.add(sysUser1);
                    i=0;
                    break;
                }
                i=1;
            }
            //添加
            if (i==1){
                SysUser sysUser = new SysUser();
                sysUser.setUserName(cphTeacher.getEmployeeId());
                if (cphTeacher.getDeptId()!=null){
                    sysUser.setDeptId(cphTeacher.getDeptId());
                }
                sysUser.setSex(Objects.equals(cphTeacher.getGender(), "男") ?"0":"1");
                sysUser.setNickName(cphTeacher.getName());
                sysUser.setPassword(SecurityUtils.encryptPassword("#A"+cphTeacher.getEmployeeId()+"A#"));
                insertUser.add(sysUser);

            }
            i=0;
        }
        if (insertUser.size()!=0){
            sysUserMapper.insertUserListInfo(insertUser);
            insertUserrole(insertUser);
        }
        if (updateUser.size()!=0) {
            List<List<SysUser>> listList1 = ListSliceUtil.updateSlice(updateUser);//切割修改集合
            if (listList1 != null) {
                for (List<SysUser> userList : listList1) {
                   // sysUserMapper.updateUserListInfo(userList);
                }
            }
        }
        System.out.println(insertUser.size());
        System.out.println(updateUser.size());
    }

    //同步到用户表
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UsertbNew(){
        //同步到user表
        List<QgzxTeacher> qgzxTeachers = qgzxTeacherMapper.selectTeacherList();//所有职工
        List<SysUser> sysUserList = sysUserMapper.selectUserLisrS();//所以用户
        List<SysUser> insertUser = new ArrayList<>();//需要添加的集合
        List<SysUser> updateUser = new ArrayList<>();//需要修改的集合
        for (QgzxTeacher qgzxTeacher:qgzxTeachers){
            int i=0;//添加标记
            for (SysUser sysUser:sysUserList){
                //修改
                if (Objects.equals(qgzxTeacher.getEmployeeId(), sysUser.getUserName())){
                    SysUser sysUser1 = new SysUser();
                    sysUser1.setUserName(qgzxTeacher.getEmployeeId());
                    sysUser1.setDeptId(qgzxTeacher.getDeptId());
                    if(qgzxTeacher.getStatus().equals("11")){
                        sysUser1.setStatus("0");
                    }
                    else if (qgzxTeacher.getStatus().equals("4")){
                        sysUser1.setStatus("0");
                    }else {
                        sysUser1.setStatus("1");
                    }
                    updateUser.add(sysUser1);
                    i=0;
                    break;
                }
                i=1;
            }
            //添加
            if (i==1){
                SysUser sysUser = new SysUser();
                sysUser.setUserName(qgzxTeacher.getEmployeeId());
                if (qgzxTeacher.getDeptId()!=null){
                    sysUser.setDeptId(qgzxTeacher.getDeptId());
                }
                sysUser.setSex(Objects.equals(qgzxTeacher.getGender(), "男") ?"0":"1");
                sysUser.setNickName(qgzxTeacher.getName());
                sysUser.setPassword(SecurityUtils.encryptPassword("#A"+qgzxTeacher.getEmployeeId()+"A#"));
                if(qgzxTeacher.getStatus().equals("11")){
                    sysUser.setStatus("0");
                }
                else if (qgzxTeacher.getStatus().equals("4")){
                    sysUser.setStatus("0");
                }else {
                    sysUser.setStatus("1");
                }
                insertUser.add(sysUser);

            }
            i=0;
        }
        if (insertUser.size()!=0){
            sysUserMapper.insertUserListInfo(insertUser);
            insertUserroleNew(insertUser);
        }
        if (updateUser.size()!=0) {
            List<List<SysUser>> listList1 = ListSliceUtil.updateSlice(updateUser);//切割修改集合
            if (listList1 != null) {
                for (List<SysUser> userList : listList1) {
                    sysUserMapper.updateUserListInfo(userList);
                }
            }
        }
        System.out.println(insertUser.size());
        System.out.println(updateUser.size());
    }


    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(102L);
            userRoleList.add(sysRole);
        }
        sysUserRoleMapper.batchUserRole(userRoleList);
    }
    public void insertUserroleNew(List<SysUser> insertUser){
        List<SysUserRole> userRoleList=new ArrayList<>();
        for (SysUser sysUser:insertUser){
            SysUserRole sysRole = new SysUserRole();
            sysRole.setUserId(sysUser.getUserId());
            sysRole.setRoleId(124L);//统一设为教职工角色
            userRoleList.add(sysRole);
        }
        sysUserRoleMapper.batchUserRole(userRoleList);
    }

    @Override
    public List<Map<String, Object>> exportSXZZ(CphExport param) {
        return cphTeacherMapper.selectSXZZ(param);
    }
    @Override
    public List<Map<String, Object>> exportZHPJ(CphExport param) {
        return cphTeacherMapper.selectZHPJ(param);
    }
}
