package com.xjrsoft.module.student.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.ScoreTypeEnum;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.common.utils.excel.ExcelMergeUtil;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.mapper.BaseClassMapper;
import com.xjrsoft.module.student.dto.BaseStudentAssessmentInspectionMobilePageDto;
import com.xjrsoft.module.student.dto.BaseStudentAssessmentInspectionPageDto;
import com.xjrsoft.module.student.dto.CalssQuantitativeAssessmentPageDto;
import com.xjrsoft.module.student.dto.QuantitativeAssessmentExcelDto;
import com.xjrsoft.module.student.dto.QuantitativeAssessmentSingleScoreDto;
import com.xjrsoft.module.student.entity.BaseClassMajorSet;
import com.xjrsoft.module.student.entity.BaseStudentAssessmentCategory;
import com.xjrsoft.module.student.entity.BaseStudentAssessmentClassRelation;
import com.xjrsoft.module.student.entity.BaseStudentAssessmentInspection;
import com.xjrsoft.module.student.entity.BaseStudentAssessmentStudentRelation;
import com.xjrsoft.module.student.entity.BaseStudentSchoolRoll;
import com.xjrsoft.module.student.mapper.BaseStudentAssessmentCategoryMapper;
import com.xjrsoft.module.student.mapper.BaseStudentAssessmentClassRelationMapper;
import com.xjrsoft.module.student.mapper.BaseStudentAssessmentInspectionMapper;
import com.xjrsoft.module.student.mapper.BaseStudentAssessmentStudentRelationMapper;
import com.xjrsoft.module.student.mapper.BaseStudentSchoolRollMapper;
import com.xjrsoft.module.student.service.IBaseStudentAssessmentInspectionService;
import com.xjrsoft.module.student.vo.BaseStudentAssessmentClassListVo;
import com.xjrsoft.module.student.vo.BaseStudentAssessmentInspectionMobilePageVo;
import com.xjrsoft.module.student.vo.BaseStudentAssessmentInspectionMobileVo;
import com.xjrsoft.module.student.vo.BaseStudentAssessmentInspectionPageVo;
import com.xjrsoft.module.student.vo.BaseStudentAssessmentInspectionVo;
import com.xjrsoft.module.student.vo.CalssQuantitativeAssessmentPageVo;
import com.xjrsoft.module.student.vo.QuantitativeAssessmentSingleScoreVo;
import com.xjrsoft.module.student.vo.QuantitativeAssessmentSubTableExcelVo;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import com.xjrsoft.module.teacher.entity.XjrUser;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @title: 学生班级巡查考核
 * @Author dzx
 * @Date: 2023-11-16
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class BaseStudentAssessmentInspectionServiceImpl extends MPJBaseServiceImpl<BaseStudentAssessmentInspectionMapper, BaseStudentAssessmentInspection> implements IBaseStudentAssessmentInspectionService {

    private final BaseStudentAssessmentInspectionMapper assessmentInspectionMapper;

    private final BaseStudentAssessmentCategoryMapper baseStudentAssessmentCategoryMapper;

    private final BaseStudentAssessmentStudentRelationMapper assessmentStudentRelationMapper;

    private final BaseStudentAssessmentClassRelationMapper assessmentClassRelationMapper;

    private final BaseClassMapper baseClassMapper;

    private final BaseStudentSchoolRollMapper baseStudentSchoolRollMapper;

    private final IFileService fileService;

    @Override
    public Page<BaseStudentAssessmentInspectionPageVo> getPage(Page<BaseStudentAssessmentInspectionPageDto> page, BaseStudentAssessmentInspectionPageDto dto) {
        Page<BaseStudentAssessmentInspectionPageVo> result = assessmentInspectionMapper.getPage(page, dto);
        // 处理加减分
        result.getRecords().forEach((node) -> {
            if (node.getScoreType().equals(ScoreTypeEnum.ScoreMinus.getCode())) {
                node.setScore(node.getScore() * -1);
            }
        });
        return result;
    }

    @Override
    public BaseStudentAssessmentInspectionVo getInfo(Long id) {
        BaseStudentAssessmentInspectionVo result = assessmentInspectionMapper.getInfo(id);
        // 处理加减分
        if (result.getScoreType().equals(ScoreTypeEnum.ScoreMinus.getCode())) {
            result.setScore(result.getScore() * -1);
        }

        // 获取班级信息
        List<BaseStudentAssessmentClassListVo> baseStudentAssessmentClassListVos = assessmentClassRelationMapper.selectJoinList(BaseStudentAssessmentClassListVo.class,
                MPJWrappers.<BaseStudentAssessmentClassRelation>lambdaJoin()
                        .leftJoin(BaseClass.class, BaseClass::getId, BaseStudentAssessmentClassRelation::getClassId)
                        .leftJoin(XjrUser.class, XjrUser::getId, BaseClass::getTeacherId)
                        .eq(BaseStudentAssessmentClassRelation::getBaseStudentAssessmentInspectionId, id)
                        .select(BaseStudentAssessmentClassRelation::getId)
                        .selectAs(BaseClass::getName, BaseStudentAssessmentClassListVo::getClassName)
                        .selectAs(XjrUser::getName, BaseStudentAssessmentClassListVo::getTeacherName)
                        .selectAs(XjrUser::getMobile, BaseStudentAssessmentClassListVo::getMobile)
                        .select(BaseStudentAssessmentClassRelation.class, x -> VoToColumnUtil.fieldsToColumns(BaseStudentAssessmentClassRelation.class).contains(x.getProperty()))
        );
        result.setClassList(baseStudentAssessmentClassListVos);

        // 获取学生信息
        List<BaseStudentAssessmentStudentRelation> baseStudentAssessmentStudentRelations = assessmentStudentRelationMapper.selectList(
                Wrappers.<BaseStudentAssessmentStudentRelation>query().lambda()
                        .eq(BaseStudentAssessmentStudentRelation::getBaseStudentAssessmentInspectionId, result.getId())
        );
        result.setStudentList(baseStudentAssessmentStudentRelations);

        // 获取文件列表
        result.setFileInfos(fileService.list(Wrappers.<File>query().lambda().eq(File::getFolderId, result.getFileId())));

        return result;
    }

    @Override
    public Page<BaseStudentAssessmentInspectionMobilePageVo> getMobilePage(Page<BaseStudentAssessmentInspectionMobilePageDto> page, BaseStudentAssessmentInspectionMobilePageDto dto) {
        if (dto.getClassIds() == null || dto.getClassIds().size() == 0) {
            // 获取当前用户所管班级
            List<Long> classIds = baseClassMapper.selectList(
                    Wrappers.<BaseClass>query().lambda()
                            .eq(BaseClass::getTeacherId, StpUtil.getLoginIdAsLong())
                            .select(BaseClass::getId)
            ).stream().map(BaseClass::getId).collect(Collectors.toList());
            dto.setClassIds(classIds);
        }
        if (dto.getClassIds() == null || dto.getClassIds().size() == 0) {
            return null;
        }
        Page<BaseStudentAssessmentInspectionMobilePageVo> result = assessmentInspectionMapper.getMobilePage(page, dto);
        // 处理加减分
        result.getRecords().forEach((node) -> {
            if (node.getScoreType().equals(ScoreTypeEnum.ScoreMinus.getCode())) {
                node.setScore(node.getScore() * -1);
            }
        });
        return result;
    }

    @Override
    public BaseStudentAssessmentInspectionMobileVo getMobileInfo(Long id) {
        BaseStudentAssessmentInspectionMobileVo result = assessmentInspectionMapper.getMobileInfo(id);
        // 处理加减分
        if (result.getScoreType().equals(ScoreTypeEnum.ScoreMinus.getCode())) {
            result.setScore(result.getScore() * -1);
        }

        // 获取学生信息
        List<BaseStudentAssessmentStudentRelation> baseStudentAssessmentStudentRelations = assessmentStudentRelationMapper.selectList(
                Wrappers.<BaseStudentAssessmentStudentRelation>query().lambda()
                        .eq(BaseStudentAssessmentStudentRelation::getBaseStudentAssessmentInspectionId, result.getBaseStudentAssessmentInspectionId())
                        .eq(BaseStudentAssessmentStudentRelation::getClassId, result.getClassId())
        );
        result.setStudentList(baseStudentAssessmentStudentRelations);
        result.setStudentCount(baseStudentAssessmentStudentRelations.size());

        // 获取文件列表
        result.setFileInfos(fileService.list(Wrappers.<File>query().lambda().eq(File::getFolderId, result.getFileId())));

        return result;
    }

    @Override
    public ResponseEntity<byte[]> getQuantitativeAssessmentExcelByte(QuantitativeAssessmentExcelDto dto) {
        //导出的文件名，字节流
        String fileName = "StudentAssessmentInspection" + ExcelTypeEnum.XLSX.getValue();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();

        //获取需要导出的子表
        List<Long> baseStudentAssessmentCategoryIdList = new ArrayList<>();
        baseStudentAssessmentCategoryIdList.add(1768178717588197377L);
        baseStudentAssessmentCategoryIdList.add(1768179375900987394L);
        baseStudentAssessmentCategoryIdList.add(1769927649167151105L);

        LambdaQueryWrapper<BaseStudentAssessmentCategory> baseStudentAssessmentCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseStudentAssessmentCategoryLambdaQueryWrapper
                .in(BaseStudentAssessmentCategory::getId, baseStudentAssessmentCategoryIdList);
        List<BaseStudentAssessmentCategory> baseStudentAssessmentCategorieList = baseStudentAssessmentCategoryMapper.selectList(baseStudentAssessmentCategoryLambdaQueryWrapper);

        //导出子表
        if(baseStudentAssessmentCategorieList.size() > 0){
            //需要合并的列
            int[] mergeColumeIndex = {0, 1, 2, 3, 4};
            ExcelMergeUtil excelFillCellMergeStrategy = new ExcelMergeUtil(1, mergeColumeIndex);

            //开始处理写入
            try (ExcelWriter excelWriter = EasyExcel.write(bot, QuantitativeAssessmentSubTableExcelVo.class).registerWriteHandler(excelFillCellMergeStrategy).build()) {
                int no = 1;
                for (BaseStudentAssessmentCategory bsac : baseStudentAssessmentCategorieList) {
                    dto.setBaseStudentAssessmentCategoryId(bsac.getId());
                    //sheet名
                    String sheetName = bsac.getName();

                    WriteSheet writeSheet = EasyExcel.writerSheet(no++, sheetName ).build();

                    //求所有的个人行为集合
                    List<QuantitativeAssessmentSubTableExcelVo> quantitativeAssessmentSubTableExcelVoList = assessmentInspectionMapper.getQuantitativeAssessmentSubTableExcelVoList(dto);

                    excelWriter.write(quantitativeAssessmentSubTableExcelVoList, writeSheet);
                }
                //TODO 班级量化考核统计表总
                //以班级为数据的基础进行数据的填充
                MPJLambdaWrapper<BaseClass> baseClassMPJLambdaWrapper = new MPJLambdaWrapper<>();
                baseClassMPJLambdaWrapper
                        .selectAs(BaseClass::getTeacherId, CalssQuantitativeAssessmentPageVo::getHeadTeacherId)
                        .selectAs(XjrUser::getUserName, CalssQuantitativeAssessmentPageVo::getOa)
                        .selectAs(XjrUser::getName, CalssQuantitativeAssessmentPageVo::getHeadTeacherName)
                        .selectAs(BaseClass::getId, CalssQuantitativeAssessmentPageVo::getClassId)
                        .selectAs(BaseClass::getName, CalssQuantitativeAssessmentPageVo::getClassName)
                        .selectAs(BaseClassMajorSet::getTotalStudent, CalssQuantitativeAssessmentPageVo::getStudentNum)
                        .selectAs(BaseClass::getIsGraduate, CalssQuantitativeAssessmentPageVo::getClassStatus)
                        .leftJoin(XjrUser.class, XjrUser::getId, BaseClass::getTeacherId)
                        .leftJoin(BaseClassMajorSet.class, BaseClassMajorSet::getClassId, BaseClass::getId)
                        .eq(dto.getGradeId() != null, BaseClass::getGradeId, dto.getGradeId())
                        .eq(dto.getClassId() != null, BaseClass::getId, dto.getClassId())
                        .eq(dto.getClassStatus() != null, BaseClass::getIsGraduate, dto.getClassStatus())
                        .like(dto.getName() != null && !dto.getName().equals(""), XjrUser::getName, dto.getName())
                        .disableSubLogicDel();

                List<CalssQuantitativeAssessmentPageVo> resultList = baseClassMapper.selectJoinList(CalssQuantitativeAssessmentPageVo.class, baseClassMPJLambdaWrapper);

                //当前数据记录班级id
                List<Long> classIdList = new ArrayList<>();
                for(CalssQuantitativeAssessmentPageVo c: resultList){
                    classIdList.add(Long.parseLong(c.getClassId()));
                }
                dto.setClassIdList(classIdList);

                if(dto.getStartTime() != null){
                    // 获取上个月的最后一秒
                    LocalDateTime lastMonthEnd = dto.getStartTime().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);

                    // 获取下个月的第一秒
                    LocalDateTime nextMonthStart = dto.getStartTime().plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
                    dto.setStartTime(lastMonthEnd);
                    dto.setEndTime(nextMonthStart);
                }

                if(!classIdList.isEmpty()){
                    CalssQuantitativeAssessmentPageDto calssQuantitativeAssessmentPageDto = new CalssQuantitativeAssessmentPageDto();
                    BeanUtils.copyProperties(dto, calssQuantitativeAssessmentPageDto);


                    //学生个人行为
                    dto.setBaseStudentAssessmentCategoryId(1768178717588197377L);
                    Map<Long , QuantitativeAssessmentSingleScoreVo> individualBehaviorMap = getQuantitativeAssessmentSingleScoreMap(calssQuantitativeAssessmentPageDto);

                    //常规管理
                    dto.setBaseStudentAssessmentCategoryId(1769927649167151105L);
                    Map<Long , QuantitativeAssessmentSingleScoreVo> conventionalManagementMap = getQuantitativeAssessmentSingleScoreMap(calssQuantitativeAssessmentPageDto);

                    //获奖及荣誉奖彰
                    dto.setBaseStudentAssessmentCategoryId(1768179375900987394L);
                    Map<Long , QuantitativeAssessmentSingleScoreVo> awardsAndHonorableMap = getQuantitativeAssessmentSingleScoreMap(calssQuantitativeAssessmentPageDto);

                    //准军事化考核
                    List<QuantitativeAssessmentSingleScoreVo> paramilitaryList = assessmentInspectionMapper.getParamilitaryList(new QuantitativeAssessmentSingleScoreDto(){{
                        setClassIdList(classIdList);
                    }});
                    Map<Long , QuantitativeAssessmentSingleScoreVo> paramilitaryMap = new HashMap<>();
                    for (QuantitativeAssessmentSingleScoreVo q : paramilitaryList) {
                        awardsAndHonorableMap.put(q.getClassId(), q);
                    }

                    //将结果写进对应的班级里
                    for(CalssQuantitativeAssessmentPageVo c: resultList){
                        Long classId = Long.parseLong(c.getClassId());
                        if(individualBehaviorMap.get(classId) != null){
                            c.setStuPersonalBehaviorSubScore(individualBehaviorMap.get(classId).getSumScore());
                            c.setStuPersonalBehaviorScore((100 + individualBehaviorMap.get(classId).getSumScore())/100*25);
                        }

                        if(conventionalManagementMap.get(classId) != null){
                            c.setClassConventionalManageSubScore(conventionalManagementMap.get(classId).getSumScore());
                            c.setClassConventionalManageScore((100 + conventionalManagementMap.get(classId).getSumScore())/100*25);
                        }

                        if(awardsAndHonorableMap.get(classId) != null){
                            c.setHonorSumScore(awardsAndHonorableMap.get(classId).getSumScore());
                            if(awardsAndHonorableMap.get(classId).getSumScore() < 10){
                                c.setHonorScore(awardsAndHonorableMap.get(classId).getSumScore());
                            }else {
                                c.setHonorScore(10D);
                            }
                        }

                        if(c.getClassStatus() != null){
                            if(c.getClassStatus() == 1){
                                c.setClassStatusCn("在读");
                            }
                            if(c.getClassStatus() == 2){
                                c.setClassStatusCn("毕业");
                            }
                        }
                    }
                }
                //sheet名
                String sheetName = "量化考核总表";

//                WriteSheet writeSheet = EasyExcel.writerSheet(0, sheetName ).build();
//
//                excelWriter.write(resultList, writeSheet);
            }
            /*for (BaseStudentAssessmentCategory bsac : baseStudentAssessmentCategorieList) {
                dto.setBaseStudentAssessmentCategoryId(bsac.getId());
                //sheet名
                String sheetName = bsac.getName();

                //求所有的个人行为集合
                List<QuantitativeAssessmentSubTableExcelVo> quantitativeAssessmentSubTableExcelVoList = assessmentInspectionMapper.getQuantitativeAssessmentSubTableExcelVoList(dto);

                //需要合并的列
                int[] mergeColumeIndex = {0, 1, 2, 3, 4};

                //写字节流
                ExcelMergeUtil excelFillCellMergeStrategy = new ExcelMergeUtil(1, mergeColumeIndex);
                EasyExcel.write(bot, QuantitativeAssessmentSubTableExcelVo.class)
                        .registerWriteHandler(excelFillCellMergeStrategy)
                        .sheet(sheetName)
                        .doWrite(quantitativeAssessmentSubTableExcelVoList);
            }*/
        }

        return RT.fileStream(bot.toByteArray(), fileName);
    }

    @Override
    public IPage<CalssQuantitativeAssessmentPageVo> getCalssQuantitativeAssessmentPage(Page<CalssQuantitativeAssessmentPageDto> page, CalssQuantitativeAssessmentPageDto dto) {
        //以班级为数据的基础进行数据的填充
        MPJLambdaWrapper<BaseClass> baseClassMPJLambdaWrapper = new MPJLambdaWrapper<>();
        baseClassMPJLambdaWrapper
                .selectAs(BaseClass::getTeacherId, CalssQuantitativeAssessmentPageVo::getHeadTeacherId)
                .selectAs(XjrUser::getUserName, CalssQuantitativeAssessmentPageVo::getOa)
                .selectAs(XjrUser::getName, CalssQuantitativeAssessmentPageVo::getHeadTeacherName)
                .selectAs(BaseClass::getId, CalssQuantitativeAssessmentPageVo::getClassId)
                .selectAs(BaseClass::getName, CalssQuantitativeAssessmentPageVo::getClassName)
                .selectAs(BaseClassMajorSet::getTotalStudent, CalssQuantitativeAssessmentPageVo::getStudentNum)
                .selectAs(BaseClass::getIsGraduate, CalssQuantitativeAssessmentPageVo::getClassStatus)
                .leftJoin(XjrUser.class, XjrUser::getId, BaseClass::getTeacherId)
                .leftJoin(BaseClassMajorSet.class, BaseClassMajorSet::getClassId, BaseClass::getId)
                .eq(dto.getGradeId() != null, BaseClass::getGradeId, dto.getGradeId())
                .eq(dto.getClassId() != null, BaseClass::getId, dto.getClassId())
                .eq(dto.getClassStatus() != null, BaseClass::getIsGraduate, dto.getClassStatus())
                .like(dto.getName() != null && !dto.getName().equals(""), XjrUser::getName, dto.getName())
                .disableSubLogicDel();

        IPage<CalssQuantitativeAssessmentPageVo> resultPage = baseClassMapper.selectJoinPage(page, CalssQuantitativeAssessmentPageVo.class, baseClassMPJLambdaWrapper);

        //当前数据记录班级id
        List<Long> classIdList = new ArrayList<>();
        for(CalssQuantitativeAssessmentPageVo c: resultPage.getRecords()){
            classIdList.add(Long.parseLong(c.getClassId()));
        }
        dto.setClassIdList(classIdList);

        if(dto.getStartTime() != null){
            // 获取上个月的最后一秒
            LocalDateTime lastMonthEnd = dto.getStartTime().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);

            // 获取下个月的第一秒
            LocalDateTime nextMonthStart = dto.getStartTime().plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
            dto.setStartTime(lastMonthEnd);
            dto.setEndTime(nextMonthStart);
        }

        if(!classIdList.isEmpty()){
            //学生个人行为
            dto.setBaseStudentAssessmentCategoryId(1768178717588197377L);
            Map<Long , QuantitativeAssessmentSingleScoreVo> individualBehaviorMap = getQuantitativeAssessmentSingleScoreMap(dto);

            //常规管理
            dto.setBaseStudentAssessmentCategoryId(1769927649167151105L);
            Map<Long , QuantitativeAssessmentSingleScoreVo> conventionalManagementMap = getQuantitativeAssessmentSingleScoreMap(dto);

            //获奖及荣誉奖彰
            dto.setBaseStudentAssessmentCategoryId(1768179375900987394L);
            Map<Long , QuantitativeAssessmentSingleScoreVo> awardsAndHonorableMap = getQuantitativeAssessmentSingleScoreMap(dto);

            //准军事化考核
            List<QuantitativeAssessmentSingleScoreVo> paramilitaryList = assessmentInspectionMapper.getParamilitaryList(new QuantitativeAssessmentSingleScoreDto(){{
                setClassIdList(classIdList);
            }});
            Map<Long , QuantitativeAssessmentSingleScoreVo> paramilitaryMap = new HashMap<>();
            for (QuantitativeAssessmentSingleScoreVo q : paramilitaryList) {
                awardsAndHonorableMap.put(q.getClassId(), q);
            }

            //将结果写进对应的班级里
            for(CalssQuantitativeAssessmentPageVo c: resultPage.getRecords()){
                Long classId = Long.parseLong(c.getClassId());
                if(individualBehaviorMap.get(classId) != null){
                    c.setStuPersonalBehaviorSubScore(individualBehaviorMap.get(classId).getSumScore());
                    c.setStuPersonalBehaviorScore((100 + individualBehaviorMap.get(classId).getSumScore())/100*25);
                    /* ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
                    String geRenXingWeiGongShi = "sumSubScore/itemCount";
                    int totalScore = scoreBySubmitRecordId.get(mobileResultPageVo.getEvaluateSubmitRecordId()).getTotalScore();
                    int itemCount = scoreBySubmitRecordId.get(mobileResultPageVo.getEvaluateSubmitRecordId()).getItemCount();
                    double res = 0;
                    String newStr1 = zonghezhishu.replace("totalScore", ""+totalScore);
                    String newStr2 = newStr1.replace("itemCount", ""+itemCount);
                    try{
                        res = Double.parseDouble(engine.eval(newStr2).toString());
                    }catch (ScriptException s){

                    }
                    // 创建一个DecimalFormat对象，指定小数位数为两位
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    // 格式化double值为字符串
                    String formattedNumber = decimalFormat.format(res);*/
                }

                if(conventionalManagementMap.get(classId) != null){
                    c.setClassConventionalManageSubScore(conventionalManagementMap.get(classId).getSumScore());
                    c.setClassConventionalManageScore((100 + conventionalManagementMap.get(classId).getSumScore())/100*25);
                }

                if(awardsAndHonorableMap.get(classId) != null){
                    c.setHonorSumScore(awardsAndHonorableMap.get(classId).getSumScore());
                    if(awardsAndHonorableMap.get(classId).getSumScore() < 10){
                        c.setHonorScore(awardsAndHonorableMap.get(classId).getSumScore());
                    }else {
                        c.setHonorScore(10D);
                    }
                }
            }
        }

        return resultPage;
    }

    private Map<Long, QuantitativeAssessmentSingleScoreVo> getQuantitativeAssessmentSingleScoreMap(CalssQuantitativeAssessmentPageDto dto){
        List<QuantitativeAssessmentSingleScoreVo> individualBehaviorList = assessmentInspectionMapper.getAssessmentInspectionByClassIdList(new QuantitativeAssessmentSingleScoreDto(){{
            setClassIdList(dto.getClassIdList());
            setBaseStudentAssessmentCategoryId(dto.getBaseStudentAssessmentCategoryId());
            if(dto.getBaseSemesterId() != null){
                setBaseSemesterId(dto.getBaseSemesterId());
            }
            if(dto.getStartTime() != null){
                setStartTime(dto.getStartTime());
            }
            if(dto.getEndTime() != null){
                setStartTime(dto.getEndTime());
            }
        }});
        Map<Long , QuantitativeAssessmentSingleScoreVo> individualBehaviorMap = new HashMap<>();
        for (QuantitativeAssessmentSingleScoreVo q : individualBehaviorList) {
            if(q.getClassId() != null){
                individualBehaviorMap.put(q.getClassId(), q);
            }
        }
       return individualBehaviorMap;
    }

    @Override
    @Transactional
    public Boolean dataHandle(Long id) {
        //获取考核记录
        BaseStudentAssessmentInspection baseStudentAssessmentInspection = this.getById(id);
        if(baseStudentAssessmentInspection != null){
            //同步数据到考核关联班级表
            if(baseStudentAssessmentInspection.getAssessmentType() != null
                    && baseStudentAssessmentInspection.getAssessmentType().equals("class")
                    && baseStudentAssessmentInspection.getClassIds() != null
                    && !baseStudentAssessmentInspection.getClassIds().equals("")){
                String[] classIds = baseStudentAssessmentInspection.getClassIds().split(",");
                for (String classId: classIds) {
                    assessmentClassRelationMapper.insert(new BaseStudentAssessmentClassRelation(){{
                        setClassId(Long.parseLong(classId));
                        setBaseStudentAssessmentInspectionId(baseStudentAssessmentInspection.getId());
                        QueryWrapper<BaseStudentAssessmentClassRelation> queryWrapperSortcode = new QueryWrapper<>();
                        queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
                        BaseStudentAssessmentClassRelation b = assessmentClassRelationMapper.selectOne(queryWrapperSortcode);
                        setSortCode(b.getSortCode() + 1);
                    }});
                }
            }
            //同步数据到考核关联学生表
            if(baseStudentAssessmentInspection.getAssessmentType() != null
                    && baseStudentAssessmentInspection.getAssessmentType().equals("personal")
                    && baseStudentAssessmentInspection.getStudentUserIds() != null
                    && !baseStudentAssessmentInspection.getStudentUserIds().equals("")){
                String[] studentIds = baseStudentAssessmentInspection.getStudentUserIds().split(",");
                for (String studentId: studentIds) {
                    assessmentStudentRelationMapper.insert(new BaseStudentAssessmentStudentRelation(){{
                        MPJLambdaWrapper<BaseStudentSchoolRoll> baseStudentSchoolRollMPJLambdaWrapper = new MPJLambdaWrapper<>();
                        baseStudentSchoolRollMPJLambdaWrapper
                                .select(BaseStudentSchoolRoll::getId)
                                .select(BaseStudentSchoolRoll.class, x -> VoToColumnUtil.fieldsToColumns(BaseStudentSchoolRoll.class).contains(x.getProperty()))
                                .eq(BaseStudentSchoolRoll::getUserId, studentId);
                        BaseStudentSchoolRoll baseStudentSchoolRoll = baseStudentSchoolRollMapper.selectOne(baseStudentSchoolRollMPJLambdaWrapper);
                        if(baseStudentSchoolRoll != null){
                            setClassId(baseStudentSchoolRoll.getClassId());
                        }
                        setUserId(Long.parseLong(studentId));
                        setBaseStudentAssessmentInspectionId(baseStudentAssessmentInspection.getId());
                        QueryWrapper<BaseStudentAssessmentStudentRelation> queryWrapperSortcode = new QueryWrapper<>();
                        queryWrapperSortcode.select("IFNULL(MAX(sort_code),0) as sortCode");
                        BaseStudentAssessmentStudentRelation b = assessmentStudentRelationMapper.selectOne(queryWrapperSortcode);
                        setSortCode(b.getSortCode() + 1);
                    }});
                }
            }
        }
        return true;
    }
}
