package com.srs.comprehensive.service.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.exception.ServiceException;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.CphExport;
import com.srs.comprehensive.domain.Vo.*;
import com.srs.comprehensive.mapper.*;
import com.srs.comprehensive.service.ISrsCqScoreService;
import com.srs.system.mapper.SysDeptMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 学生综合素质评分表Service业务层处理
 *
 * @author srs
 * @date 2023-06-29
 */
@Service
@AllArgsConstructor
public class SrsCqScoreServiceImpl extends ServiceImpl<SrsCqScoreMapper, SrsCqScore> implements ISrsCqScoreService {

    private final SrsCqScoreMapper srsCqScoreMapper;


    private final SrsStudentMapper srsStudentMapper;
    //学年表
    private final SrsStuYearMapper srsStuYearMapper;

    private final SrsClassMapper srsClassMapper;

    private final SysDeptMapper sysDeptMapper;

    private final SrsMajorsMapper srsMajorsMapper;

    private final SrsGradeMapper srsGradeMapper;

    /**
     * 查询学生综合素质评分表
     *
     * @param id 学生综合素质评分表主键
     * @return 学生综合素质评分表
     */
    @Override
    public SrsCqScore selectSrsCqScoreById(Long id) {
        return srsCqScoreMapper.selectSrsCqScoreById(id);
    }

    @Override
    public List<DataScreen> countScoreDis(Long stuYearId){
        return srsCqScoreMapper.countScoreDis(stuYearId);
    }

    @Override
    public List<DataScreen> rankDis(CphSearch search){
        return srsCqScoreMapper.rankDis(search);
    }


    @Override
    public List<DataScreen> countScoreDetailDis(Long stuYearId){
        return srsCqScoreMapper.countScoreDetailDis(stuYearId);
    }

    @Override
    public List<Map<String,Object>> exportScore(CphExport param){
        return srsCqScoreMapper.exportScore(param);
    }

    @Override
    public List<CphStuScoreType> listOwnFive(String stuNo){
        return srsCqScoreMapper.listOwnFive(stuNo);
    }

    @Override
    public List<CphOwnScore> getOwn(String stuNo){
        return srsCqScoreMapper.getOwn(stuNo);
    }

    @Override
    public List<CphOwnScore> getOwn2(String stuNo){
        return srsCqScoreMapper.getOwn2(stuNo);
    }

    @Override
    public List<CphTotalScoreInfo> listCphScore(CphSearch search){
        return srsCqScoreMapper.listCphScore(search);
    }

    @Override
    public List<CphCollegeLook> listOwnCollegeScore(CphSearch param){
        return srsCqScoreMapper.listOwnCollegeScore(param);
    }

    @Override
    public List<CphCollegeLook> listOwnCollegeStu(CphSearch param){
        return srsCqScoreMapper.listOwnCollegeStu(param);
    }

    @Override
    public List<CphCollegeLook> listOwnCollegeAudit(CphSearch param){
        return srsCqScoreMapper.listOwnCollegeAudit(param);

    }


    @Override
    public List<SrsMajors> listOwnMajor(Long id){
        return srsCqScoreMapper.listOwnMajor(id);
    }

    @Override
    public List<SrsMajors> listOwnClass(CphSearch param){
        return srsCqScoreMapper.listOwnClass(param);
    }






    @Override
    @Transactional
    public Map<String, Integer> generateComprehensiveSummary(int id) {
        List<Map<String, Object>> comprehensiveSummary = srsCqScoreMapper.getComprehensiveSummary(id);
        List<SrsCqScore> srsCqScores = srsCqScoreMapper.selectAll(id);
        List<SrsCqScore> insertCqScoreList = new ArrayList<>();
        List<SrsCqScore> updateCqScoreList = new ArrayList<>();
        Long stuYearId = Long.valueOf(id);
        // 创建一个固定大小的线程池，最大线程数为 10
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        Object lock = new Object(); // 定义一个对象作为锁
        for (Map<String, Object> stringObjectMap : comprehensiveSummary) {
            executorService.submit(() -> {
                    String stuNo = (String) stringObjectMap.get("stu_no");
                    BigDecimal  cqScore = (BigDecimal) stringObjectMap.get("total_score");

                    SrsCqScore srsCqScore = new SrsCqScore();
                    srsCqScore.setCqScore(cqScore);
                    srsCqScore.setStuYearId(stuYearId);
                    srsCqScore.setStuNo(stuNo);
//                boolean cq = srsCqScores.stream()
//                        .anyMatch(obj -> obj.getStuNo().equals(stuNo) && obj.getStuYearId().equals(stuYearId));
                Optional<SrsCqScore> cq = srsCqScores.stream().filter(obj -> obj.getStuYearId().equals(stuYearId) && obj.getStuNo().equals(stuNo)).findFirst();

                synchronized (lock) {
                    if (!cq.isPresent()){
                        insertCqScoreList.add(srsCqScore);
//                        srsCqScoreMapper.insertSrsCqScore(srsCqScore);


                    }else {
                        srsCqScore.setId(cq.get().getId());
                        updateCqScoreList.add(srsCqScore);
//                        srsCqScoreMapper.updateSrsCqScore(srsCqScore);
                    }
                }

            });

        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(10, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            executorService.shutdownNow();//强制关闭线程池
            System.out.println(e);
            throw new ServiceException("错误");
        }
        int updateNum = 0;
        int insertNum = 0;
        if (!insertCqScoreList.isEmpty()){
            insertNum = srsCqScoreMapper.batchInsertCqScore(insertCqScoreList);
            int batchSize = 5000; // 每批次插入的数据量
            int totalSize = insertCqScoreList.size();
            for (int i = 0; i < totalSize; i += batchSize) {
                int endIndex = Math.min(i + batchSize, totalSize);
                List<SrsCqScore> batchList = insertCqScoreList.subList(i, endIndex);
                // 将 batchList 中的数据插入到数据库中
                srsCqScoreMapper.batchUpdateCqScore(batchList); // 这里的 insertBatchData 是自定义的方法，负责批量插入数据库
                insertNum = insertNum+batchList.size();
                System.out.println("成功数量:"+insertNum);
            }
        }


        if (!updateCqScoreList.isEmpty()){
            int batchSize = 5000; // 每批次插入的数据量
            int totalSize = updateCqScoreList.size();

            for (int i = 0; i < totalSize; i += batchSize) {
                int endIndex = Math.min(i + batchSize, totalSize);
                List<SrsCqScore> batchList = updateCqScoreList.subList(i, endIndex);
                // 将 batchList 中的数据插入到数据库中
                srsCqScoreMapper.batchUpdateCqScore(batchList);
                updateNum = updateNum+batchList.size();
                System.out.println("更新数量:"+updateNum);
            }

        }
        HashMap<String, Integer> map = new HashMap<>();
        map.put("insert",insertNum);
        map.put("update",updateNum);
        return map;

    }

//    @Override
//    public void generateComprehensiveSummary(int id) {
//        srsCqScoreMapper.generateComprehensiveSummary(id);
//    }

    /**
     * 根据学生id查询综合成绩评分
     *
     * @param
     * @return
     */
    @Override
    public List<SrsUserCqScore> selectSrsCqStuId() {
        SrsStudent srsStudent = srsStudentMapper.selectSrsStudentByStuNo(getUsername());//根据当前用户查询学生id
        CphSearch search = new CphSearch();//综合评分表对象
//        srsCqScore.setStuId(srsStudent.getStuId());

        List<SrsCqScore> srsCqScores = srsCqScoreMapper.selectSrsCqScoreList(search);//根据用户id查询综合评分列表
        List<SrsUserCqScore> srsUserCqScores = new ArrayList<>();//传给前端的参数
        int i = 0;//记录执行的数组
        for (SrsCqScore srsCqScore1 : srsCqScores) {
            //查询差数的学年名称
            SrsStuYear srsStuYear = srsStuYearMapper.selectSrsStuYearById(srsCqScores.get(i).getStuYearId());
            srsUserCqScores.add(new SrsUserCqScore(srsCqScore1.getCqScore(), srsStuYear.getStuYearName()));
            i++;
        }

        return srsUserCqScores;//根据stuId查询
    }

    /**
     * 查询学生综合素质评分表列表
     *
     * @param search 搜索实体类
     * @return 学生综合素质评分表
     */
    @Override
    public List<SrsCqScore> selectSrsCqScoreList(CphSearch search) {
        return srsCqScoreMapper.selectSrsCqScoreList(search);
    }

    /**
     * 新增学生综合素质评分表
     *
     * @param srsCqScore 学生综合素质评分表
     * @return 结果
     */
    @Override
    public int insertSrsCqScore(SrsCqScore srsCqScore) {
        srsCqScore.setCreateTime(DateUtils.getNowDate());
        return srsCqScoreMapper.insertSrsCqScore(srsCqScore);
    }

    /**
     * 修改学生综合素质评分表
     *
     * @param srsCqScore 学生综合素质评分表
     * @return 结果
     */
    @Override
    public int updateSrsCqScore(SrsCqScore srsCqScore) {
        srsCqScore.setUpdateTime(DateUtils.getNowDate());
        return srsCqScoreMapper.updateSrsCqScore(srsCqScore);
    }

    /**
     * 批量删除学生综合素质评分表
     *
     * @param ids 需要删除的学生综合素质评分表主键
     * @return 结果
     */
    @Override
    public int deleteSrsCqScoreByIds(Long[] ids) {
        return srsCqScoreMapper.deleteSrsCqScoreByIds(ids);
    }

    /**
     * 删除学生综合素质评分表信息
     *
     * @param id 学生综合素质评分表主键
     * @return 结果
     */
    @Override
    public int deleteSrsCqScoreById(Long id) {
        return srsCqScoreMapper.deleteSrsCqScoreById(id);
    }

    @Override
    public AjaxResult getScoreDistribution(SrsCqScore srsCqScore) {
        Map<String, Object> params = srsCqScore.getParams();
        List<Map<String, Object>> list = srsCqScoreMapper.getScoreDistribution(params);
        Map<String, Integer> scoreDistribution = new HashMap<>();
        int count60 = 0;
        int count70 = 0;
        int count80 = 0;
        int count90 = 0;
        int count100 = 0;

        for (Map<String, Object> result : list) {
            BigDecimal totalScore = (BigDecimal) result.get("total_score");
            if (totalScore.compareTo(BigDecimal.ZERO) >= 0 && totalScore.compareTo(new BigDecimal(60)) < 0) {
                count60++;
            } else if (totalScore.compareTo(new BigDecimal(60)) >= 0 && totalScore.compareTo(new BigDecimal(70)) < 0) {
                count70++;
            } else if (totalScore.compareTo(new BigDecimal(70)) >= 0 && totalScore.compareTo(new BigDecimal(80)) < 0) {
                count80++;
            } else if (totalScore.compareTo(new BigDecimal(80)) >= 0 && totalScore.compareTo(new BigDecimal(90)) < 0) {
                count90++;
            } else if (totalScore.compareTo(new BigDecimal(90)) >= 0 && totalScore.compareTo(new BigDecimal(100)) <= 0) {
                count100++;
            }
        }
        scoreDistribution.put("0-60", count60);
        scoreDistribution.put("60-70", count70);
        scoreDistribution.put("70-80", count80);
        scoreDistribution.put("80-90", count90);
        scoreDistribution.put("90-100", count100);
        scoreDistribution.put("total", list.size());
        return AjaxResult.success(scoreDistribution);
    }

    public List<SrsCeScoreClassDeptGradeMajorsStudentStuYear> comprehensiveRanking(SrsCqScore srsCqScore) {
        // 获取参数和数据
        Map<String, Object> params = srsCqScore.getParams();
        return baseMapper.selectPerson(params);
    }

    //查询个人思想品得加分申请
    public List<CphAuditDetails> getcphiamByOne(String stuNo){
        return  srsCqScoreMapper.getcphiamByOne(stuNo);
    }
    //查询个人素质综合信息
    public  List<SrsCqScore> getStuData(String stuNo){
        return  srsCqScoreMapper.getStuData(stuNo);
    }
}
