package com.srs.stureg.service.impl;

import java.lang.management.LockInfo;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.srs.common.annotation.DataSource;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysDictData;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.enums.DataSourceType;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.listFunc;
import com.srs.comprehensive.domain.SrsClass;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.domain.Vo.CphSearch;
import com.srs.comprehensive.domain.Vo.DataScreen;
import com.srs.comprehensive.mapper.SrsOrderMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.comprehensive.service.ISrsClassService;
import com.srs.stureg.domain.*;
import com.srs.stureg.mapper.SrsMsgQueueMapper;
import com.srs.stureg.mapper.SrsStuRegMapper;
import com.srs.stureg.mapper.SrsStuTodoMapper;
import com.srs.stureg.mapper.SrsTaskListMapper;
import com.srs.stureg.service.ISrsStuRegService;
import com.srs.stureg.service.ISrsStuTodoService;
import com.srs.stureg.util.TogglesDbf;
import com.srs.system.mapper.SysDictDataMapper;
import com.srs.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.el.lang.ELArithmetic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
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 org.springframework.web.multipart.MultipartFile;

import static com.srs.common.utils.SecurityUtils.getUsername;


/**
 * 新生报到学生注册信息Service业务层处理
 *
 * @author srs
 * @date 2023-07-24
 */
@Service
public class SrsStuRegServiceImpl extends ServiceImpl<SrsStuRegMapper, SrsStuReg> implements ISrsStuRegService {

    @Autowired
    private SrsStuRegMapper srsStuRegMapper;

    //用户
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SrsOrderMapper srsOrderMapper;

    //redis
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //短信队列
    @Autowired
    private SrsMsgQueueMapper srsMsgQueueMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    private List<SysUser> userList;//用户集合
    //待办
    @Autowired
    private SrsTaskListMapper srsTaskListMapper;
    //每个学生的待办
    @Autowired
    private SrsStuTodoMapper srsStuTodoMapper;


    @Autowired
    private ISrsStuTodoService srsStuTodoService;

    @Autowired
    public SrsStudentMapper _stuMapper;

    @Autowired
    private ISrsClassService srsClassService;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Override
    public AjaxResult syncClassCode() {
        // 初始化两个线程池，根据CPU核心数配置合理线程数
        ThreadPoolExecutor pool1 = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() / 2,
                Runtime.getRuntime().availableProcessors(),
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                new ThreadFactory() {
                    private final AtomicInteger counter = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "update-pool-1-" + counter.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy() // 任务满时让提交线程执行，避免丢失
        );

        ThreadPoolExecutor pool2 = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() / 2,
                Runtime.getRuntime().availableProcessors(),
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                new ThreadFactory() {
                    private final AtomicInteger counter = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "update-pool-2-" + counter.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        try {
            List<SrsStuReg> stuList = this.list();
            List<GxsdxySjzx009Temp2024xsxx> tempList = srsStuRegMapper.listXsxxTemp(new GxsdxySjzx009Temp2024xsxx());

            tempList.forEach(x -> {
                x.临时学号报到后给新的 = x.临时学号报到后给新的.replace("LS", "");
            });

            List<SrsStuReg> needUpdateList = new ArrayList<>();
            for (SrsStuReg srsStuReg : stuList) {
                GxsdxySjzx009Temp2024xsxx temp = tempList.stream()
                        .filter(x -> x.临时学号报到后给新的.equals(srsStuReg.getKSH()))
                        .findFirst()
                        .orElse(null);
                if (temp != null) {
                    SrsStuReg stu = new SrsStuReg();
                    stu.setId(srsStuReg.getId());
                    stu.setBJDM(temp.教务系统班级编号);
                    stu.setBJ(temp.班级名称);
                    needUpdateList.add(stu);
                }
            }

            if (needUpdateList.isEmpty()) {
                return AjaxResult.success("没有需要更新的数据");
            }

            // 将更新列表拆分为两部分，分配给两个线程池
            int mid = needUpdateList.size() / 2;
            List<SrsStuReg> part1 = needUpdateList.subList(0, mid);
            List<SrsStuReg> part2 = needUpdateList.subList(mid, needUpdateList.size());

            // 用于等待所有线程完成
            CountDownLatch countDownLatch = new CountDownLatch(2);
            // 用于捕获线程中的异常
            AtomicReference<Exception> exceptionRef = new AtomicReference<>();

            // 提交第一个任务到线程池1
            pool1.submit(() -> {
                try {
                    if (!part1.isEmpty()) {
                        boolean res = this.updateBatchById(part1);
                        if (!res) {
                            throw new Exception("线程池1批量更新失败");
                        }
                    }
                } catch (Exception e) {
                    exceptionRef.set(e);
                } finally {
                    countDownLatch.countDown();
                }
            });

            // 提交第二个任务到线程池2
            pool2.submit(() -> {
                try {
                    if (!part2.isEmpty()) {
                        boolean res = this.updateBatchById(part2);
                        if (!res) {
                            throw new Exception("线程池2批量更新失败");
                        }
                    }
                } catch (Exception e) {
                    exceptionRef.set(e);
                } finally {
                    countDownLatch.countDown();
                }
            });

            // 等待所有任务完成（最多等待30秒）
            boolean await = countDownLatch.await(30, TimeUnit.SECONDS);
            if (!await) {
                throw new Exception("批量更新超时");
            }

            // 检查是否有异常
            if (exceptionRef.get() != null) {
                throw exceptionRef.get();
            }

            return AjaxResult.success("同步班级代码成功，共更新" + needUpdateList.size() + "条数据");
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        } finally {
            // 关闭线程池
            pool1.shutdown();
            pool2.shutdown();
            try {
                // 等待线程池关闭（最多等5秒）
                if (!pool1.awaitTermination(5, TimeUnit.SECONDS)) {
                    pool1.shutdownNow();
                }
                if (!pool2.awaitTermination(5, TimeUnit.SECONDS)) {
                    pool2.shutdownNow();
                }
            } catch (InterruptedException e) {
                pool1.shutdownNow();
                pool2.shutdownNow();
            }
        }
    }


    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<GxsdxySjzx009Temp2024xsxx> listXsxxTemp(GxsdxySjzx009Temp2024xsxx param){
        return srsStuRegMapper.listXsxxTemp(param);
    }


    public SrsStuRegServiceImpl(List<SysUser> userList) {
        this.userList = userList;
    }

   @Override
    public  int addSrsStuRegs(List<SrsStuReg> srsStuRegs){
        int count=0;
        if(srsStuRegs.size()==0){
            return count;
        }
        for(SrsStuReg srsStuReg:srsStuRegs) {
            SrsStuReg entity= srsStuRegMapper.getOwnInfoByKsh(srsStuReg.getKSH());
                    if(entity==null) {
                        int insertResult= srsStuRegMapper.insert(srsStuReg);//批量插入新生注册表
                        count+=insertResult;
                        SysUser sysUser1 = new SysUser();
                        sysUser1.setUserName(srsStuReg.getKSH());
                        sysUser1.setNickName(srsStuReg.getXSXM());
                        sysUser1.setPhonenumber(srsStuReg.getSJH());
                        sysUser1.setSex(srsStuReg.getXB());
                        sysUser1.setPassword(SecurityUtils.encryptPassword(srsStuReg.getKSH().substring(srsStuReg.getKSH().length()-4)+srsStuReg.getSFZH().substring(srsStuReg.getSFZH().length()-4)));
                        sysUser1.setCreateBy(getUsername());
                        sysUser1.setDelFlag("0");
                        SysUser entityDTO=sysUserMapper.selectUserByUserName(srsStuReg.getKSH());
                        if(entityDTO==null){
                            int  insertUsertResult=sysUserMapper.insertUser(sysUser1);
                            count+=insertUsertResult;
                        }else{
                            sysUser1.setUserId(entityDTO.getUserId());
                            int  updateResultCount=sysUserMapper.updateUser(sysUser1);
                            count+=updateResultCount;
                        }
                    }else {
                        srsStuReg.setId(entity.getId());
                        srsStuReg.setUpdateTime(DateUtils.getNowDate());
                        srsStuReg.setUpdateBy(getUsername());
                        srsStuReg.setBJ(srsStuReg.getBJ());
                        srsStuReg.setBJDM(srsStuReg.getBJDM());
                        srsStuReg.setRegStatus(entity.getRegStatus());
                        int updateResult= srsStuRegMapper.updateSrsStuReg(srsStuReg);//更新新生注册表
                        count+=updateResult;
                        SysUser sysUser1 = new SysUser();
                        sysUser1.setUserName(srsStuReg.getKSH());
                        sysUser1.setNickName(srsStuReg.getXSXM());
                        sysUser1.setPhonenumber(srsStuReg.getSJH());
                        sysUser1.setSex(srsStuReg.getXB());
                        sysUser1.setPassword(SecurityUtils.encryptPassword(srsStuReg.getKSH().substring(srsStuReg.getKSH().length()-4)+srsStuReg.getSFZH().substring(srsStuReg.getSFZH().length()-4)));
                        sysUser1.setCreateBy(getUsername());
                        sysUser1.setDelFlag("0");
                        SysUser entityDTO=sysUserMapper.selectUserByUserName(srsStuReg.getKSH());
                        if(entityDTO==null){
                           int  insertResult=sysUserMapper.insertUser(sysUser1);
                           count+=insertResult;
                        }else{
                            sysUser1.setUserId(entityDTO.getUserId());
                            int  updateResultCount=sysUserMapper.updateUser(sysUser1);
                            count+=updateResultCount;
                        }

                    }

            }
        return  count;
    }

//    @Override
//    public  int addSrsStuRegs(List<SrsStuReg> srsStuRegs){
//        List<SrsStuReg> srsStuRegList=new ArrayList<>();
//        List<SrsStuReg> srsStuRegList2=new ArrayList<>();
//        List<SysUser> SysUserList=new ArrayList<>();
//        List<SysUser> SysUserList2=new ArrayList<>();
//        List<SysUser> SysUserList3=new ArrayList<>();
//        List<SysUser> SysUserList4=new ArrayList<>();
//        int count=0;
//        if(srsStuRegs.size()==0){
//            return count;
//        }
//        for(SrsStuReg srsStuReg:srsStuRegs) {
//            SrsStuReg entity= srsStuRegMapper.getOwnInfoByKsh(srsStuReg.getKSH());
//            if(entity==null) {
//                srsStuRegList.add(srsStuReg);
//                SysUser sysUser1 = new SysUser();
//                sysUser1.setUserName(srsStuReg.getKSH());
//                sysUser1.setNickName(srsStuReg.getXSXM());
//                sysUser1.setPhonenumber(srsStuReg.getSJH());
//                sysUser1.setSex(srsStuReg.getXB());
//                sysUser1.setPassword(SecurityUtils.encryptPassword(srsStuReg.getKSH().substring(srsStuReg.getKSH().length()-4)+srsStuReg.getSFZH().substring(srsStuReg.getSFZH().length()-4)));
//                sysUser1.setCreateBy(getUsername());
//                sysUser1.setDelFlag("0");
//                SysUser entityDTO=sysUserMapper.selectUserByUserName(srsStuReg.getKSH());
//                if(entityDTO==null){
//                    SysUserList.add(sysUser1);
//                }else{
//                    sysUser1.setUserId(entityDTO.getUserId());
//                    SysUserList2.add(sysUser1);
//                }
//            }else {
//                srsStuReg.setId(entity.getId());
//                srsStuReg.setUpdateTime(DateUtils.getNowDate());
//                srsStuReg.setUpdateBy(getUsername());
//                srsStuReg.setBJ(srsStuReg.getBJ());
//                srsStuReg.setBJDM(srsStuReg.getBJDM());
//                srsStuRegList2.add(srsStuReg);
//                SysUser sysUser1 = new SysUser();
//                sysUser1.setUserName(srsStuReg.getKSH());
//                sysUser1.setNickName(srsStuReg.getXSXM());
//                sysUser1.setPhonenumber(srsStuReg.getSJH());
//                sysUser1.setSex(srsStuReg.getXB());
//                sysUser1.setPassword(SecurityUtils.encryptPassword(srsStuReg.getKSH().substring(srsStuReg.getKSH().length()-4)+srsStuReg.getSFZH().substring(srsStuReg.getSFZH().length()-4)));
//                sysUser1.setCreateBy(getUsername());
//                sysUser1.setDelFlag("0");
//                SysUser entityDTO=sysUserMapper.selectUserByUserName(srsStuReg.getKSH());
//                if(entityDTO==null){
//                    SysUserList3.add(sysUser1);
//                }else{
//                    sysUser1.setUserId(entityDTO.getUserId());
//                    SysUserList4.add(sysUser1);
//                }
//            }
//
//        }
//        if(srsStuRegList.size()>0){
//            int insertResult=srsStuRegMapper.insertBathStuRegs(srsStuRegList);
//            count+=insertResult;
//        }
//        if(srsStuRegList2.size()>0){
//            int updateResult=srsStuRegMapper.updateBathSrsStuRegs(srsStuRegList2);
//            count+=updateResult;
//        }
//        if(SysUserList.size()>0){
//            int insertResult=sysUserMapper.insertBathUsers(SysUserList);
//            count+=insertResult;
//        }
//        if(SysUserList2.size()>0){
//            int updateResult=sysUserMapper.updateBathUsers(SysUserList2);
//            count+=updateResult;
//        }
//        if(SysUserList3.size()>0){
//            int insertResult=sysUserMapper.insertBathUsers(SysUserList3);
//            count+=insertResult;
//        }
//        if(SysUserList4.size()>0){
//            int updateResult=sysUserMapper.updateBathUsers(SysUserList4);
//            count+=updateResult;
//        }
//        return  count;
//    }

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

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

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

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


    @Override
    public List<DataScreen> countBaodao(){
        return srsStuRegMapper.countBaodao();
    }


    @Override
    public List<SrsStuReg> listView(CphSearch param) {
        return srsStuRegMapper.listView(param);
    }

    @Override
    public List<DataScreen> countGender() {
        return srsStuRegMapper.countGender();
    }

    @Override
    public List<DataScreen> countMajorTop10() {
        return srsStuRegMapper.countMajorTop10();
    }

    @Override
    public Map<String, Object> countNowAt() {
        return srsStuRegMapper.countNowAt();
    }

    @Override
    public List<DataScreen> countArea() {
        return srsStuRegMapper.countArea();
    }


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

    @Override
    public List<DataScreen> countDeptStuMoney(){
        return srsStuRegMapper.countDeptStuMoney();
    }


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


    @Override
    public int changePwdIs(SrsStuReg stu) {
        QueryWrapper<SrsStuReg> regQueryWrapper = new QueryWrapper<>();
        regQueryWrapper.eq("KSH", stu.getKSH());
        SrsStuReg find = srsStuRegMapper.selectOne(regQueryWrapper);
        if (find == null) {
            return 0;
        }
        find.setIsChangePwd("1");
        int res = srsStuRegMapper.updateById(find);
        return res;
    }

    @Override
    public SrsStuReg getOwnInfoByKsh(String ksh) {
        return srsStuRegMapper.getOwnInfoByKsh(ksh);
    }

    @Override
    public Map<String, Integer> selectCountByRegStatus() {
        HashMap<String, Integer> map = new HashMap<>();
        List<SysDictData> srs_stu_reg_status = sysDictDataMapper.selectDictDataByType("srs_stu_reg_status");
        for (SysDictData srsStuRegStatus : srs_stu_reg_status) {
            Integer count = srsStuRegMapper.selectCountByRegStatus(srsStuRegStatus.getDictValue());
            map.put(srsStuRegStatus.getDictValue(), count);
        }
        return map;

    }

    /**
     * 查询新生报到学生注册信息
     *
     * @param id 新生报到学生注册信息主键
     * @return 新生报到学生注册信息
     */
    @Override
    public SrsStuReg selectSrsStuRegById(Long id) {
        SrsStuReg info=srsStuRegMapper.selectSrsStuRegById(id);
        return info;
    }

    /**
     * 通过学号查询注册信息
     *
     * @param stuNo
     * @return
     */
    @Override
    public SrsStuReg selectSrsStuRegByStuNo(String stuNo) {
        return srsStuRegMapper.selectSrsStuRegByStuNo(stuNo);
    }


    /**
     * 查询新生报到学生注册信息列表
     *
     * @param srsStuReg 新生报到学生注册信息
     * @return 新生报到学生注册信息
     */
    @Override
    public List<SrsStuReg> selectSrsStuRegList(SrsStuReg srsStuReg) {
        srsStuReg.setDelFlag("0");
        return srsStuRegMapper.selectSrsStuRegList(srsStuReg);
    }

    /**
     * 新增新生报到学生注册信息
     *
     * @param srsStuReg 新生报到学生注册信息
     * @return 结果
     */
    @Override
    public int insertSrsStuReg(SrsStuReg srsStuReg) {
        SrsClass sc=srsClassService.selectSrsClassByClassId(srsStuReg.getClassId());
        srsStuReg.setClassName(sc.getClassName());
        srsStuReg.setBJ(sc.getClassName());
        srsStuReg.setBJDM(sc.getClassCode());
        srsStuReg.setCreateTime(DateUtils.getNowDate());
        return srsStuRegMapper.insertSrsStuReg(srsStuReg);
    }

    /**
     * 修改新生报到学生注册信息
     *
     * @param srsStuReg 新生报到学生注册信息
     * @return 结果
     */
    @Override
    public int updateSrsStuReg(SrsStuReg srsStuReg) {

//        SrsClass sc=srsClassService.selectSrsClassByClassId(srsStuReg.getClassId());
        if(srsStuReg.getBJDM()!=null||srsStuReg.getBJDM()!=""){
            SrsClass sc=srsClassService.selectSrsClassByClassCode(srsStuReg.getBJDM());
            if(sc!=null){
                srsStuReg.setClassName(sc.getClassName());
                srsStuReg.setBJ(sc.getClassName());
                srsStuReg.setBJDM(sc.getClassCode());
            }
        }
        srsStuReg.setUpdateTime(DateUtils.getNowDate());
        return srsStuRegMapper.updateSrsStuReg(srsStuReg);
    }

    /**
     * 批量删除新生报到学生注册信息
     *
     * @param ids 需要删除的新生报到学生注册信息主键
     * @return 结果
     */
    @Override
    public int deleteSrsStuRegByIds(List<Long> ids) {
        return srsStuRegMapper.deleteBatchIds(ids);
    }

    /**
     * 删除新生报到学生注册信息信息
     *
     * @param id 新生报到学生注册信息主键
     * @return 结果
     */
    @Override
    public int deleteSrsStuRegById(Long id) {
        return srsStuRegMapper.deleteSrsStuRegById(id);
    }


    //批量导入学生注册信息
    @Override
    @Transactional(rollbackFor = Exception.class)
//    public Future<String> addSrsStuRegList(List<Map<String, Object>> srsStuRegs, String fileName) {
    public List<SrsStuReg> addSrsStuRegList(List<Map<String, Object>> srsStuRegs, String fileName) {
//        long start = System.currentTimeMillis();
        String[] kshArr = new String[srsStuRegs.size()];
        Set<String> set1 = new HashSet<>();
        List<String> allKsh = new ArrayList<>();
        int j = 0;
        for (Map map : srsStuRegs) {
            kshArr[j] = map.get("KSH")+"";
            set1.add(map.get("KSH")+"");
            allKsh.add(map.get("KSH")+"");
            j++;
        }
        List<SrsStuReg> isExistKsh = srsStuRegMapper.selectIsExistKsh(kshArr);
        Set<String> set2 = new HashSet<>();
        List<String> listIsExistKsh = new ArrayList<>();
        for (SrsStuReg i : isExistKsh) {
            set2.add(i.getKSH());
            listIsExistKsh.add(i.getKSH());
        }
        Set<String> difference = new HashSet<>(set1);
        difference.removeAll(set2);
        Set<Map<String, Object>> needQueryTemp = new HashSet<>(srsStuRegs);
        Set<Map<String, Object>> needQuery = needQueryTemp.stream()
                .filter(s -> difference.contains(s.get("KSH")+"")).collect(Collectors.toSet());

        List<String> needUpdateKsh = listFunc.intersectList(allKsh, listIsExistKsh);
        List<Map<String, Object>> needUpdateListTemp = needQueryTemp.stream()
                .filter(x -> needUpdateKsh.contains(x.get("KSH")+"")).collect(Collectors.toList());

        List<SrsStuReg> needUpdate = new ArrayList<>();
        for (Map i : needUpdateListTemp) {
            String ksh = i.get("KSH")+"";
            SrsStuReg srstemp = isExistKsh.stream().filter(x -> Objects.equals(x.getKSH(), ksh)).findAny().orElse(null);
            if (srstemp != null) {
                SrsStuReg srsStuReg = new SrsStuReg();
                Long id = srstemp.getId();
                srsStuReg.setId(id);

                //set你想set的
                if (Objects.equals(fileName, "t_jhk.dbf")) {
                    srsStuReg.setZY(i.get("zymc2")+"");
                    srsStuReg.setZYDM(i.get("zydm3")+"");
                }
                needUpdate.add(srsStuReg);
            }
        }


        List<SrsStuReg> srsStuRegArrayList = new ArrayList<>();
        List<SrsMsgQueue> srsMsgQueueList = new ArrayList<>();
        for (Map i : needQuery) {
            SrsStuReg srsStuReg = new SrsStuReg();
            if (Objects.equals(fileName, "T_TDD.dbf")) {
                srsStuReg.setKSH(i.get("KSH")+"");
                srsStuReg.setXSXM(i.get("XM")+"");
                srsStuReg.setSFZH(i.get("SFZH")+"");
                srsStuReg.setSJH(i.get("LXDH")+"");
                if (Objects.equals(i.get("XBDM")+"", "1")) {
                    srsStuReg.setXB("男");
                } else {
                    srsStuReg.setXB("女");
                }
                srsStuReg.setLQZY(i.get("LQZY")+"");
                srsStuReg.setKLDM(i.get("KLDM")+"");
                srsStuReg.setPCDM(i.get("PCDM")+"");
                srsStuReg.setTDDW(i.get("TDDW")+"");
//                srsStuReg.setZYDH(i.get("ZYDH")+"");
                srsStuReg.setTDCJ((Double) i.get("TDCJ"));
                srsStuReg.setLastSchool(i.get("ZXMC")+"");
                srsStuReg.setFamNowAddr(i.get("JTDZ")+"");
            }
//            if(i.containsKey("XH")) {
//                srsStuReg.setXH(i.get("XH")+"");
//            }

//            srsStuReg.setZZMM(i.get("ZZMM")+"");
//            srsStuReg.setMZ(i.get("MZ")+"");
//            if (i.containsKey("XY")) {
//                srsStuReg.setXY(i.get("XY")+"");
//            }
//            srsStuReg.setXYDM(i.get("XYDM")+"");
//            if (i.containsKey("zymc")) {
//                srsStuReg.setZY(i.get("zymc")+"");
//            }
//            srsStuReg.setZYDM(i.get("zydm")+"");
////            if (i.containsKey("BJ")) {
////                srsStuReg.setBJ(i.get("BJ")+"");
////            }
////            srsStuReg.setBJDM(i.get("BJDM")+"");
//            srsStuReg.setLastSchool(i.get("ZXMC")+"");
//            srsStuReg.setFamNowAddr(i.get("JTDZ")+"");
            srsStuReg.setRegStatus("0");
            srsStuReg.setCreateTime(DateUtils.getNowDate());
            //srsStuReg.setCreateBy(getUsername());
            srsStuReg.setDelFlag("0");
            srsStuRegArrayList.add(srsStuReg);
            // 插入短信队列
//            SrsMsgQueue srsMsgQueue = new SrsMsgQueue();
//            if(i.containsKey("KSH")) {
//                srsMsgQueue.setXH(srsStuReg.getKSH());
//            }
//            srsMsgQueue.setPhone(srsStuReg.getSJH());
//            srsMsgQueue.setStatus("0");
//            srsMsgQueue.setCreateBy(getUsername());
//            srsMsgQueue.setCreateTime(DateUtils.getNowDate());
//            srsMsgQueueList.add(srsMsgQueue);
        }

        List<Map<String, Object>> needList = new ArrayList<>(needQuery);
        ExecutorService executor = Executors.newFixedThreadPool(200);//创建一个线程池，数量100
        userList = new Vector<>();
        for (Map map : needList) {
            executor.submit(() -> {
                addDefault(map);
            });
        }
        executor.shutdown();//关闭线程池
        try {
            executor.awaitTermination(6, TimeUnit.MINUTES);//等待6分钟
        } catch (InterruptedException e) {
            executor.shutdownNow();//强制关闭线程池
            e.printStackTrace();
            throw new ServiceException("系统异常，请重试");
        }

        Integer integer = srsStuRegMapper.insertBatchSomeColumn(srsStuRegArrayList);//批量插入新生注册表
        srsStuRegMapper.updateSrsStuRegList(needUpdate);//更新新生注册表
        srsMsgQueueMapper.insertBatchSomeColumn(srsMsgQueueList);//批量插入短信队列
        sysUserMapper.insertUserList(userList);//用户
        System.out.println("开始========================================");
        System.out.println(userList.size());
        long end = System.currentTimeMillis();
//        System.out.println("耗时:"+(end-start));
//        return new AsyncResult(String.valueOf(3));
        return needUpdate;
    }

    //批量修改
    private int updateSrsStuRegList(List<Map<String, Object>> srsStuRegList) {
        List<SrsStuReg> srsStuRegs1 = srsStuRegMapper.selectList(null);
        List<SrsStuReg> srsStuRegRepeatList = new ArrayList<>();
        for (Map srsStuRegMap : srsStuRegList) {
            String stuRegValue = srsStuRegMap.get("KSH")+"";
            for (SrsStuReg srsStuReg : srsStuRegs1) {
                if (srsStuReg.getKSH().equals(stuRegValue)) {
                    SrsStuReg srsStuReg1 = new SrsStuReg();
                    srsStuReg1.setId(srsStuReg.getId());
                    srsStuReg1.setXH(srsStuReg.getXH());
                    srsStuRegRepeatList.add(srsStuReg1);
                }
            }
        }
        return srsStuRegMapper.updateSrsStuRegList(srsStuRegRepeatList);
    }

    //导入用户注册信息
    private void addDefault(Map<String, Object> map) {
        //导入学生用户
        SysUser sysUser1 = new SysUser();
        sysUser1.setUserName(map.get("KSH")+"");
        sysUser1.setNickName(map.get("XM")+"");
        sysUser1.setPhonenumber(map.get("LXDH")+"");
        sysUser1.setSex(map.get("XBDM")+"");
        sysUser1.setPassword(SecurityUtils.encryptPassword(map.get("KSH")+""
                .substring((map.get("KSH")+"").length() - 4) + map
                .get("SFZH")+""
                .substring((map.get("SFZH")+"").length() - 6)));
        sysUser1.setCreateBy(getUsername());
        userList.add(sysUser1);
    }

    //完善注册信息
    @Override
    public Map insertStuRegList(Map<String, Object> jsonMap) {
        HashMap<String, String> returnMap = new HashMap<>();
        try {
            SrsStuReg srsStuReg = new SrsStuReg();
            srsStuReg.setKSH(getUsername());
            //查询学生
            List<SrsStuReg> srsStuRegs = srsStuRegMapper.selectSrsStuRegList(srsStuReg);
//            String redis = redisTemplate.opsForValue().get("VERIFY_XXXX"+ jsonMap.get("SJH"));//获取redis中的注册信息
//            ObjectMapper objectMapper = new ObjectMapper();
//            SrsStuReg srsStuReg1 = objectMapper.readValue(redis, SrsStuReg.class);//将string转成srsstureg对象
            srsStuReg = srsStuRegs.get(0);
            if (jsonMap.containsKey("lastSchool")) {//存在
                srsStuReg.setLastSchool(jsonMap.get("lastSchool")+"");
            }
            if (jsonMap.containsKey("lastSchoolAddr")) {
                srsStuReg.setLastSchoolAddr(jsonMap.get("lastSchoolAddr")+"");
            }
            if (jsonMap.containsKey("famName")) {
                srsStuReg.setFamName(jsonMap.get("famName")+"");
            }
            if (jsonMap.containsKey("famRelation")) {
                srsStuReg.setFamRelation(jsonMap.get("famRelation")+"");
            }
            if (jsonMap.containsKey("famPhone")) {
                srsStuReg.setFamPhone(jsonMap.get("famPhone")+"");
            }
            if (jsonMap.containsKey("famNowAddr")) {
                srsStuReg.setFamNowAddr(jsonMap.get("famNowAddr")+"");
            }
            if (jsonMap.containsKey("sfzAddr")) {
                srsStuReg.setSfzAddr(jsonMap.get("sfzAddr")+"");
            }
            srsStuReg.setUpdateTime(DateUtils.getNowDate());
            srsStuReg.setUpdateBy(getUsername());
            int i = srsStuRegMapper.updateSrsStuReg(srsStuReg);//完善学生注册信息
            if (i > 0) {
                returnMap.put("state", "1");
                returnMap.put("msg", "修改成功");
            }

        } catch (Exception e) {
            returnMap.put("state", "0");
            returnMap.put("msg", "未知错误");
            return returnMap;
        }
        return returnMap;
    }

    //验证学生注册信息
    @Override
    public Map verifyXX(Map<String, Object> jsonMap) {
        HashMap<String, String> returnMap = new HashMap<>();
        //从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + jsonMap.get("SJH"));
        //对验证码进行校验（验证码是否存在，是否和输入的验证码一支）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(jsonMap.get("code"))) {
            //验证码无效
            returnMap.put("state", "0");
            returnMap.put("msg", "验证码无效");
            return returnMap;
        }
        SrsStuReg srsStuReg = new SrsStuReg();
        srsStuReg.setKSH(jsonMap.get("KSH")+"");
        srsStuReg.setSFZH(jsonMap.get("SFZH")+"");
        srsStuReg.setSJH(jsonMap.get("SJH")+"");
        //查询学生
        List<SrsStuReg> srsStuRegs = srsStuRegMapper.selectSrsStuRegList(srsStuReg);
        if (srsStuRegs.size() == 0) {
            returnMap.put("state", "0");
            returnMap.put("msg", "输入信息错误，请确定输入的信息是否正确");
            return returnMap;
        }
        //有则激活
        SrsStuReg updateSrsStuReg = srsStuRegs.get(0);
        updateSrsStuReg.setRegStatus("2");
        updateSrsStuReg.setUpdateBy(updateSrsStuReg.getKSH());
        updateSrsStuReg.setUpdateTime(DateUtils.getNowDate());
        srsStuRegMapper.updateSrsStuReg(updateSrsStuReg);
        returnMap.put("state", "1");
        returnMap.put("msg", "200");
        //所有验证通过删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + jsonMap.get("SJH")+"");
        //查询所有待办
        SrsTaskList srsTaskList = new SrsTaskList();
        srsTaskList.setStatus("1");
        srsTaskList.setDelFlag("0");
        List<SrsTaskList> srsTaskLists = srsTaskListMapper.selectSrsTaskListList(srsTaskList);
        for (SrsTaskList srsTaskList1 : srsTaskLists) {
            SrsStuTodo srsStuTodo = new SrsStuTodo();
            srsStuTodo.setStuNo(srsStuRegs.get(0).getXH());//学号
            srsStuTodo.setKsh(srsStuRegs.get(0).getKSH());//考生号
            srsStuTodo.setTaskId(srsTaskList1.getId());
            srsStuTodo.setTaskCode(srsTaskList1.getTaskCode());
            srsStuTodo.setStatus("0");
            srsStuTodo.setCreateTime(DateUtils.getNowDate());
            srsStuTodoMapper.insertSrsStuTodo(srsStuTodo);//添加到待办事项
        }
        return returnMap;
    }

    //验证手机号，并修改手机号
    @Override
    public Map verifyPhone(Map<String, Object> jsonMap) {
        HashMap<String, String> returnMap = new HashMap<>();
        try {
            String chstr = "CHECK_CODE_" + jsonMap.get("SJH");
            //从redis中获取下发的验证码
            String redisCode = redisTemplate.opsForValue().get(chstr);
            //对验证码进行校验（验证码是否存在，是否和输入的验证码一支）
            if (StringUtils.isEmpty(redisCode) || !redisCode.equals(jsonMap.get("code"))) {
                //验证码无效
                returnMap.put("state", "0");
                returnMap.put("msg", "验证码无效");
                return returnMap;
            }
            SrsStuReg srsStuReg = new SrsStuReg();
            srsStuReg.setKSH(jsonMap.get("KSH")+"");
            //srsStuReg.setSJH();
            SrsStuReg srss = srsStuRegMapper.getOwnInfoByKsh(jsonMap.get("KSH")+"");

            if (!Objects.equals(srss.getSFZH(), jsonMap.get("SFZH")+"")) {
                throw new Exception("身份证号错误");
            }

            srss.setSJH(jsonMap.get("SJH")+"");
            srss.setRegStatus("2");
            int res = updateSrsStuReg(srss);
            returnMap.put("state", "1");
            returnMap.put("msg", "修改成功");
        } catch (Exception e) {
            returnMap.put("state", "0");
            returnMap.put("msg", e.getMessage());
        }
        return returnMap;
    }



    //验证手机号
    @Override
    public Map verifyPwd(Map<String, Object> jsonMap) {
        HashMap<String, String> returnMap = new HashMap<>();
        try {
            String chstr = "CHECK_CODE_" + jsonMap.get("SJH");
            //从redis中获取下发的验证码
            String redisCode = redisTemplate.opsForValue().get(chstr);
            //对验证码进行校验（验证码是否存在，是否和输入的验证码一支）
            if (StringUtils.isEmpty(redisCode) || !redisCode.equals(jsonMap.get("code"))) {
                //验证码无效
                returnMap.put("state", "0");
                returnMap.put("msg", "验证码无效");
                return returnMap;
            }
            QueryWrapper<SrsStuReg> stuRegQueryWrapper = new QueryWrapper<>();
            stuRegQueryWrapper.eq("XH",jsonMap.get("XH")+"");
            SrsStuReg srss = srsStuRegMapper.selectOne(stuRegQueryWrapper);

            if (!Objects.equals(srss.getSFZH(), jsonMap.get("SFZH")+"")) {
                throw new Exception("身份证号错误");
            }

            returnMap.put("state", "1");
            returnMap.put("msg", "修改成功");
        } catch (Exception e) {
            returnMap.put("state", "0");
            returnMap.put("msg", e.getMessage());
        }
        return returnMap;
    }

    @Override
    public Map checkPwd(Map<String, Object> jsonMap) {
        HashMap<String, String> returnMap = new HashMap<>();
        try {
            String ksh= (String) jsonMap.get("KSH");
            String sfzh=(String) jsonMap.get("SFZH");
            QueryWrapper<SrsStuReg> regQueryWrapper = new QueryWrapper<>();
            regQueryWrapper.eq("KSH",ksh);
            SrsStuReg srss=srsStuRegMapper.selectOne(regQueryWrapper);
            SysUser users = sysUserMapper.selectUserByUserName(ksh);
            if (users==null){
                throw new Exception("考生号错误");
            }

            if (!Objects.equals(srss.getSFZH(), sfzh)) {
                throw new Exception("身份证号错误");
            }
            users.setPassword(SecurityUtils.encryptPassword(jsonMap.get("pwd")+""));
            users.setUpdateBy(ksh);
            int res = sysUserMapper.updateUser(users);
            if (res!=0){
                returnMap.put("state", "1");
                returnMap.put("msg", "修改成功");
            }
        } catch (Exception e) {
            returnMap.put("state", "0");
            returnMap.put("msg", e.getMessage());
        }
        return returnMap;
    }

    //dbf导入数据
    @Override
    @Transactional
    public int addDbf(MultipartFile file, String tableName) {
        //将dbf文件转成map对象
        List<Map<String, Object>> maps = TogglesDbf.uploadDBFFile(file);
        if (maps != null) {
            for (Map<String, Object> map : maps) { // 遍历列表中的每个映射
                for (Map.Entry<String, Object> entry : map.entrySet()) { // 遍历映射中的每个条目
                    if (entry.getValue() instanceof String) { // 检查条目的值是否为字符串类型
                        String value = (String) entry.getValue(); // 强制转换为字符串类型
                        String trimmedValue = value.trim(); // 清除空格
                        entry.setValue(trimmedValue); // 更新映射中的值
                    }
                }
            }
        } else {
            throw new ServiceException("文件转换出错！");
        }
        //判断数据库是否存在该表
        try {
            if (srsStuRegMapper.isTableExist(tableName) <= 0) {
                //没有表存在，则创建表
                Map<String, Object> stringObjectMap = new HashMap<>(maps.get(0));
                for (Map.Entry<String, Object> map : stringObjectMap.entrySet()) {
                    if (map.getValue() instanceof Integer) {
                        // 处理int类型的value
                        map.setValue("int(10)");
                    } else if (map.getValue() instanceof Double) {
                        // 处理double类型的value
                        map.setValue("double(17,9)");
                    } else if (map.getValue() instanceof Date) {
                        // 处理Date类型的value
                        map.setValue("datetime");
                    } else {
                        map.setValue("varchar(100)");
                    }
                }
                srsStuRegMapper.createTable(tableName, stringObjectMap);
                // 添加延迟，等待表结构生效
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("创建表出错！请手动创建");
        }
        try {
            //查询数据库数据类型
            Map<String, Object> stringStringMap = srsStuRegMapper.selectDatabaseType(tableName);
            Map<String, Object> replaceContainerMap = new HashMap<>();
            for (Map.Entry<String, Object> key : stringStringMap.entrySet()) {
                Map<String, Object> nestedMap = new Gson().fromJson(new Gson().toJson(key.getValue()),
                        new TypeToken<Map<String, Object>>() {
                        }.getType());//(Map<String, Object>) key.getValue();
                String KEY_NAME = (String) nestedMap.get("COLUMN_NAME");//KSH
                String KEY_TYPE = (String) nestedMap.get("COLUMN_TYPE");//varchar(255)
                if (Objects.equals(KEY_TYPE, "date") || Objects.equals(KEY_TYPE, "datetime")) {
                    replaceContainerMap.put(KEY_NAME, KEY_TYPE);
                }
            }
            for (int i = 0; i < maps.size(); i++) {
                Map<String, Object> map = maps.get(i);
                Set<String> keys = replaceContainerMap.keySet();
                for (String k : keys) {
                    String v = map.get(k)+"";//map的value
                    long timestamp = Long.parseLong(v); // 将字符串转换为长整型时间戳
                    Date date = new Date(timestamp); // 使用长整型时间戳创建Date对象
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = sdf.format(date);//时间格式化后的date
                    Date parse = sdf.parse(format);
                    map.replace(k, parse);//替换key里面的value值
                }
                maps.set(i, map);//替换原来的maps
            }
            //修改
            /*
            if (srsStuRegMapper.selectTableCount(tableName)>0) {//判断表是否有数据
                if (Objects.equals(tableName, "t_jhk2012")) {//2012,t_jhk.dbf
                    List<Map<String,Object>> tJhkMapList=srsStuRegMapper.selectTable(tableName);//查询表数据
                    List<Map<String, Object>> updateListMap = new ArrayList<>();//修改
                    for (Map<String, Object> tJhkMap: tJhkMapList){
                        for (Map<String,Object> map:maps){
                            if (Objects.equals(tJhkMap.get("vehicle_id")+"", map.get("vehicle_id")+"")){
                                updateListMap.add(map);
                            }
                        }
                    }
                    srsStuRegMapper.updateMapList(updateListMap, tableName);//更新
                    for (Map<String, Object> map: maps) {
                        for (Map<String,Object> updateMap: updateListMap){
                            map.remove(updateMap);//x
                            break;
                        }
                    }
                } else if (Objects.equals(tableName, "td_kldm2012")) {//2012,td_kldm.dbf

                } else if (Objects.equals(tableName, "t_tddw2012")) {//2012,t_tddw.dbf

                } else if (Objects.equals(tableName, "t_tdd2012")) {//2012,t_tdd.dbf

                } else if (Objects.equals(tableName, "t_tdd2020")) {//2020,t_tdd.dbf
                } else if (Objects.equals(tableName, "td_zydh2020")) {//2020,td_zydh.dbf

                } else if (Objects.equals(tableName, "td_kldm2020")) {//2020,td_kldm.dbf

                } else if (Objects.equals(tableName, "t_tddw2020")) {//2020,t_tddw.dbf

                } else if (Objects.equals(tableName, "t_bmk2020")) {//2020,t_bmk.dbf

                } else if (Objects.equals(tableName, "t_zykmx2020")) { //2020,t_zykmx.dbf
                } else if (Objects.equals(tableName, "t_jhk2020")) {//2020,t_jhk.dbf

                }
            }

             */
            //添加
            srsStuRegMapper.insertData(tableName, maps);
//            List<Map<String, Object>> mapList = srsStuRegMapper.selectAll();
//            addSrsStuRegList(mapList,"");

        } catch (DataAccessException ex) {
            throw new ServiceException("字段类型不匹配");
        } catch (Exception e) {
            System.out.println(e);
            throw new ServiceException("导入数据出错，请联系管理员检查表字段是否正确！");
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSrsStuRegByKSH(SrsStuReg srsStuReg) {
        SrsStuReg stuReg = srsStuRegMapper.getOwnInfoByKsh(getUsername());
        stuReg.setSJH(srsStuReg.getSJH());
        stuReg.setFamNowAddr(srsStuReg.getFamNowAddr());
        stuReg.setFamName(srsStuReg.getFamName());
        stuReg.setFamRelation(srsStuReg.getFamRelation());
        stuReg.setFamPhone(srsStuReg.getFamPhone());
        stuReg.setIsDisability(srsStuReg.getIsDisability());
        stuReg.setIsRetired(srsStuReg.getIsRetired());
        stuReg.setIsFiling(srsStuReg.getIsFiling());
        stuReg.setDisableDescript(srsStuReg.getDisableDescript());
        stuReg.setIsSmoke(srsStuReg.getIsSmoke());
        stuReg.setIsEarly(srsStuReg.getIsEarly());
        stuReg.setHobby(srsStuReg.getHobby());

        SrsStuTodo srsStuTodo = new SrsStuTodo();
        if (StringUtils.isNotEmpty(srsStuReg.getLoanNo())) {
            stuReg.setLoanNo(srsStuReg.getLoanNo());
            srsStuTodo.setStatus("1");
            srsStuTodo.setKsh(getUsername());
            srsStuTodo.setTaskCode("ZXJF");
            srsStuTodoService.updateSrsStuTodoStastus(srsStuTodo);
        }
        if (StringUtils.isNotEmpty(srsStuReg.getRegStatus())) {
            stuReg.setRegStatus(srsStuReg.getRegStatus());
        }
        if (StringUtils.isNotEmpty(srsStuReg.getIsLoan())) {  // 贷款编号不为空，就修改
            stuReg.setIsLoan(srsStuReg.getIsLoan());
        }
        //SrsStuTodo srsStuTodo = new SrsStuTodo();
        srsStuTodo.setStatus("1");
        srsStuTodo.setKsh(getUsername());
        srsStuTodo.setTaskCode("XXCJ");
        srsStuTodoService.updateSrsStuTodoStastus(srsStuTodo);
        return srsStuRegMapper.updateSrsStuReg(stuReg);
    }

    //转换dbf导入新生数据
    @Override
    public List<Map<String, Object>> insertDBF(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//文件名
        List<Map<String, Object>> maps = TogglesDbf.uploadDBFFile(file);
        if (maps != null) {
            for (Map<String, Object> map : maps) { // 遍历列表中的每个映射
                for (Map.Entry<String, Object> entry : map.entrySet()) { // 遍历映射中的每个条目
                    if (entry.getValue() instanceof String) { // 检查条目的值是否为字符串类型
                        String value = (String) entry.getValue(); // 强制转换为字符串类型
                        String trimmedValue = value.trim(); // 清除空格
                        entry.setValue(trimmedValue); // 更新映射中的值
                    }
                }
            }
        } else {
            throw new ServiceException("文件转换出错！");
        }
//        List<Map<String, Object>> mapList = srsStuRegMapper.selectAll();
        if (Objects.equals(originalFilename, "T_TDD.dbf")) {
            List<Map<String, Object>> mapList = addSrsStuRegDbfList(maps, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "t_jhk.dbf")) {//连表
            List<Map<String, Object>> mapList = srsStuRegMapper.getStuRegWithList(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "t_tddw.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTTDDW(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "TD_KLDM.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTDKLDI(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "T_BMK2020.dbf")) {
            List<Map<String, Object>> mapList = addSrsStuRegDbfList(maps, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "T_TDD2020.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTTDD2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "t_zykmx2020.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTzykmx2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "t_jhk2020.dbf")) {//============
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTjhk2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "t_tddw2020.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTTDDW2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "td_zydh2020.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTdzydh2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        } else if (Objects.equals(originalFilename, "TD_KLDM2020.dbf")) {
            List<Map<String, Object>> mapList = srsStuRegMapper.selectTDKLDM2020(maps);
            addSrsStuRegDbfList(mapList, originalFilename);
            return mapList;
        }
        return null;
    }

    //新生数据
    @Transactional(rollbackFor = Exception.class)
    public List<Map<String, Object>> addSrsStuRegDbfList(List<Map<String, Object>> srsStuRegs, String fileName) {
        try {
            SrsStuReg ssr = new SrsStuReg();
            List<SrsStuReg> srsStuRegs1 = srsStuRegMapper.selectSrsStuRegList(ssr);//新生集合
            if (Objects.equals(fileName, "T_TDD.dbf") || Objects.equals(fileName, "T_BMK2020.dbf")) {
                //查找重复值
                List<Map<String, Object>> updateMap = srsStuRegs.stream()
                        .filter(obj1 -> srsStuRegs1
                                .stream().anyMatch(obj2 -> obj2.getKSH().equals(obj1.get("KSH")+"")))
                        .collect(Collectors.toList());

                //添加需要
                List<String> kshList2 = srsStuRegs1.stream()
                        .map(SrsStuReg::getKSH)
                        .collect(Collectors.toList());

                List<Map<String, Object>> insertMap = srsStuRegs.stream()
                        .filter(obj -> !kshList2.contains(obj.get("KSH")+""))
                        .collect(Collectors.toList());
                //更新
                if (Objects.equals(fileName, "T_TDD.dbf") && updateMap.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : updateMap) {
                        Map<String, Object> objectObjectHashMap = new HashMap<>();
//                    objectObjectHashMap.put("id",map.get("id")+"");
                        objectObjectHashMap.put("XSXM", map.get("XM")+"");
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("SFZH", map.get("SFZH")+"");
                        objectObjectHashMap.put("SJH", map.get("LXDH")+"");
                        objectObjectHashMap.put("XB",
                                Objects.equals(map.get("XBDM")+"", "1") ? "男" : "女");
                        objectObjectHashMap.put("LQZY", map.get("LQZY")+"");
                        objectObjectHashMap.put("KLDM", map.get("KLDM")+"");
                        objectObjectHashMap.put("PCDM", map.get("PCDM")+"");
                        objectObjectHashMap.put("TDDW", map.get("TDDW")+"");
                        objectObjectHashMap.put("TDCJ", map.get("TDCJ"));
                        objectObjectHashMap.put("last_school", map.get("ZXMC")+"");
                        objectObjectHashMap.put("fam_now_addr", map.get("JTDZ")+"");
                        objectObjectHashMap.put("update_time", DateUtils.getNowDate());
//                    objectObjectHashMap.put("update_by",getUsername());
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                }
                //添加
                if (Objects.equals(fileName, "T_TDD.dbf") && insertMap.size() != 0) {
                    List<SrsStuReg> srsStuRegArrayList = new ArrayList<>();
                    for (Map i : insertMap) {
                        SrsStuReg srsStuReg = new SrsStuReg();
                        srsStuReg.setKSH(i.get("KSH") + "");
                        if (StringUtils.isEmpty(i.get("XM") + "")) {
                            continue;
                        }
                        srsStuReg.setXSXM(i.get("XM") + "");
                        srsStuReg.setSFZH(i.get("SFZH") + "");
                        srsStuReg.setSJH(i.get("LXDH") + "");
                        if (Objects.equals(i.get("XBDM") + "", "1")) {
                            srsStuReg.setXB("男");
                        } else {
                            srsStuReg.setXB("女");
                        }
                        srsStuReg.setLQZY(i.get("LQZY") + "");
                        srsStuReg.setKLDM(i.get("KLDM") + "");
                        srsStuReg.setPCDM(i.get("PCDM") + "");
                        srsStuReg.setTDDW(i.get("TDDW") + "");
                        srsStuReg.setTDCJ((Double) i.get("TDCJ"));
                        srsStuReg.setLastSchool(i.get("ZXMC") + "");
                        srsStuReg.setFamNowAddr(i.get("JTDZ") + "");
                        srsStuReg.setRegStatus("0");
                        srsStuReg.setCreateTime(DateUtils.getNowDate());
                        //srsStuReg.setCreateBy(getUsername());
                        srsStuReg.setDelFlag("0");
                        srsStuRegArrayList.add(srsStuReg);
                    }
                    // 批量插入screenStuReg
                    if (srsStuRegArrayList.size() > 0)
                        srsStuRegMapper.insertBatchSomeColumn(srsStuRegArrayList);//批量插入新生注册表
                }
                //更新2020
                if (Objects.equals(fileName, "T_BMK2020.dbf") && updateMap.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : updateMap) {
                        Map<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("XSXM", map.get("XM")+"");
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("SFZH", map.get("ZJHM")+"");
                        objectObjectHashMap.put("SJH", map.get("LXDH")+"");
                        objectObjectHashMap.put("XB",
                                Objects.equals(map.get("XBDM")+"", "1") ? "男" : "女");
                        objectObjectHashMap.put("last_school", map.get("BYXXMC")+"");
                        objectObjectHashMap.put("fam_now_addr", map.get("TXDZ")+"");
                        objectObjectHashMap.put("update_time", DateUtils.getNowDate());
//                    objectObjectHashMap.put("update_by",getUsername());
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                }
                //添加2020
                if (Objects.equals(fileName, "T_BMK2020.dbf") && insertMap.size() != 0) {
                    List<SrsStuReg> srsStuRegArrayList = new ArrayList<>();
                    for (Map i : insertMap) {
                        SrsStuReg srsStuReg = new SrsStuReg();
                        srsStuReg.setKSH(i.get("KSH")+"");//考生号
                        srsStuReg.setXSXM(i.get("XM")+"");//姓名
                        srsStuReg.setSFZH(i.get("ZJHM")+"");//证件号码
                        srsStuReg.setSJH(i.get("LXDH")+"");//联系电话
                        srsStuReg.setLastSchool(i.get("BYXXMC")+"");//毕业学校
                        srsStuReg.setFamNowAddr(i.get("TXDZ")+"");//通讯地址
                        srsStuReg.setXB(Objects.equals(i.get("XBDM")+"", "1") ? "男" : "女");//性别
                        srsStuReg.setCreateTime(DateUtils.getNowDate());
                        //srsStuReg.setCreateBy(getUsername());
                        srsStuReg.setRegStatus("0");
                        srsStuReg.setDelFlag("0");
                        srsStuRegArrayList.add(srsStuReg);
                    }
                    // 批量插入screenStuReg
                    srsStuRegMapper.insertBatchSomeColumn(srsStuRegArrayList);//批量插入新生注册表
                }
            } else if (Objects.equals(fileName, "t_jhk.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("ZY", map.get("zymc2")+"");
                        objectObjectHashMap.put("ZYDM", map.get("zydm3")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "t_tddw.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("TDDWMC", map.get("tddwmc1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "TD_KLDM.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("KLMC", map.get("klmc1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "T_TDD2020.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("LQZY2020", map.get("lqzy1")+"");
                        objectObjectHashMap.put("PCDM2020", map.get("pcdm1")+"");
                        objectObjectHashMap.put("KLDM2020", map.get("kldm1")+"");
                        objectObjectHashMap.put("TDCJ", map.get("tdcj1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "t_zykmx2020.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("ZYDH2020", map.get("zydh1")+"");
                        objectObjectHashMap.put("TDDWDM2020", map.get("tddwdm1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "t_jhk2020.dbf")) {//===============
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        //objectObjectHashMap.put("KSH",map.get("KSH")+"");
                        //objectObjectHashMap.put("KLMC",map.get("klmc1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    //srsStuRegMapper.updateMapListAll(updateMapList,"srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "t_tddw2020.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("TDDWMC", map.get("tddwmc1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "td_zydh2020.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("ZY", map.get("zymc1")+"");
                        //objectObjectHashMap.put("KLMC",map.get("klmc1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            } else if (Objects.equals(fileName, "TD_KLDM2020.dbf")) {
                if (srsStuRegs.size() != 0) {
                    List<Map<String, Object>> updateMapList = new ArrayList<>();
                    for (Map map : srsStuRegs) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("KSH", map.get("KSH")+"");
                        objectObjectHashMap.put("KLMC", map.get("lqzy1")+"");
                        updateMapList.add(objectObjectHashMap);
                    }
                    srsStuRegMapper.updateMapListAll(updateMapList, "srs_stu_reg");
                } else {
                    throw new ServiceException("初始文件未导入！");
                }
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            return null;
        }
        return null;
    }

}
