package com.template.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.SmartEvaluateTeacherControllerAPI;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.UUIDUtil;
import com.template.common.utils.paramUtils;
import com.template.model.evaluate.teacher.*;
import com.template.model.pojo.SmartScore;
import com.template.model.pojo.SmartSemester;
import com.template.model.request.addChildScoreManageRequest;
import com.template.model.request.addScoreManageRequest;
import com.template.model.request.updateScoreManageRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.EvaluateTeacherVo;
import com.template.model.vo.RankingVo;
import com.template.services.SmartEvaluateTdetailService;
import com.template.services.SmartEvaluateTeacherService;
import com.template.services.SmartScoreManageService;
import com.template.services.SmartSemesterService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
//返回参数加密注解
@DESRespondSecret
public class SmartEvaluateTeacherController implements SmartEvaluateTeacherControllerAPI {

    @Autowired
    public SmartEvaluateTdetailService smartEvaluateTdetailService;
    @Autowired
    public SmartEvaluateTeacherService smartEvaluateTeacherService;
    @Autowired
    public SmartScoreManageService smartScoreManageService;
    @Autowired
    SmartSemesterService smartSemesterService;


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult addScoreManage(addScoreManageRequest asmr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        SmartSemester semester = smartSemesterService.getSmartById(asmr.getTermId());
        if (semester == null) {
            return CommonResult.fail("学期数据为空，添加评分项失败");
        }

        List<SmartScoreManage> ssm = smartScoreManageService.queryDatasByTermId(asmr.getTermId());
        if (ssm != null && ssm.size() > 0) {
            long exist = ssm.stream().filter(e -> e.getParentId().intValue() == 0 && e.getScoreItem().equals(asmr.getScoreItem())).count();
            if (exist > 0) {
                return CommonResult.fail("存在重复主项");
            }
        }

        try {
            SmartScoreManage parentData = new SmartScoreManage();
            parentData.setTermId(asmr.getTermId());
            parentData.setTerm(semester.getName());
            parentData.setScoreItem(asmr.getScoreItem());
            parentData.setParentId(0);
            parentData.setScoreNum(asmr.getScoreNum());
            int insertResult = smartScoreManageService.insertSmartScoreManage(parentData);
            if (insertResult <= 0) {
                //return CommonResult.fail("添加项失败");
                throw new Exception("添加项失败！");
            }
            SmartScoreManage childData = new SmartScoreManage();
            childData.setTermId(asmr.getTermId());
            childData.setTerm(semester.getName());
            childData.setScoreItem(asmr.getScoreChildItem());
            childData.setParentId(insertResult);
            childData.setScoreNum(asmr.getScoreNum());
            int insertChildResult = smartScoreManageService.insertSmartScoreManage(childData);
            if (insertChildResult <= 0) {
                //return CommonResult.fail("添加子项失败");
                throw new Exception("添加子项失败！");
            }
        } catch (Exception e) {
            throw new Exception("添加失败！");
        }


        return CommonResult.ok("添加成功");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult addChildScoreManage(addChildScoreManageRequest acsmr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        SmartSemester semester = smartSemesterService.getSmartById(acsmr.getTermId());
        if (semester == null) {
            return CommonResult.fail("学期数据为空，添加评分项失败");
        }

        //根据父级ID获取父级下所有子级数据
        List<SmartScoreManage> childDatas = smartScoreManageService.queryAllDatasByParentId(acsmr.getId());
        if (childDatas != null && childDatas.size() > 0) {
            long exist = childDatas.stream().filter(e -> e.getScoreItem().equals(acsmr.getScoreItem())).count();
            if (exist > 0) {
                return CommonResult.fail("存在重复子项");
            }
        }

        try {
            SmartScoreManage parentData = new SmartScoreManage();
            parentData.setTermId(acsmr.getTermId());
            parentData.setTerm(semester.getName());
            parentData.setScoreItem(acsmr.getScoreItem());
            parentData.setParentId(acsmr.getId());
            parentData.setScoreNum(acsmr.getScoreNum());
            int insertResult = smartScoreManageService.insertSmartScoreManage(parentData);
            if (insertResult <= 0) {
                //return CommonResult.fail("添加子项失败");
                throw new Exception("添加子项失败！");
            }

            Optional<SmartScoreManage> oScoreManage = childDatas.stream().filter(e -> e.getParentId().intValue() == 0).findFirst();
            if (oScoreManage != null && oScoreManage.isPresent()) {
                BigDecimal totalNum = new BigDecimal(0.0);
                for (SmartScoreManage child : childDatas) {
                    if (child.getParentId().intValue() != 0) {
                        totalNum = totalNum.add(new BigDecimal(child.getScoreNum()));
                    }
                }
                totalNum = totalNum.add(new BigDecimal(acsmr.getScoreNum()));
                oScoreManage.get().setScoreNum(totalNum.doubleValue());

                int updateData = smartScoreManageService.updateSmartScoreManage(oScoreManage.get());
                if (updateData <= 0) {
                    //return CommonResult.ok("添加失败");
                    throw new Exception("添加失败！");
                }
            }
        } catch (Exception e) {
            throw new Exception("添加子项失败！");
        }

        return CommonResult.ok("添加成功");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult updateScoreManage(updateScoreManageRequest usmr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        SmartScoreManage data = smartScoreManageService.getSmartScoreManageById(usmr.getId());
        if (data == null) {
            return CommonResult.fail("数据已失效，编辑失败");
        }

        //根据父级ID获取父级下所有子级数据
        List<SmartScoreManage> childDatas = smartScoreManageService.queryAllDatasByParentId(data.getParentId());
        if (childDatas != null && childDatas.size() > 0) {
            long exist = childDatas.stream().filter(e -> e.getScoreItem().equals(usmr.getScoreItem()) && e.getId().intValue() != usmr.getId().intValue()).count();
            if (exist > 0) {
                return CommonResult.fail("存在重复子项");
            }
        }

        try {
            List<SmartScoreManage> updateDatas = new ArrayList<>();
            Optional<SmartScoreManage> oScoreManage = childDatas.stream().filter(e -> e.getParentId().intValue() == 0).findFirst();
            if (oScoreManage != null && oScoreManage.isPresent()) {
                BigDecimal totalNum = new BigDecimal(0.0);
                for (SmartScoreManage child : childDatas) {
                    if (child.getParentId().intValue() != 0 && child.getId().intValue() != usmr.getId().intValue()) {
                        totalNum = totalNum.add(new BigDecimal(child.getScoreNum()));
                    }
                }
                totalNum = totalNum.add(new BigDecimal(usmr.getScoreNum()));
                oScoreManage.get().setScoreNum(totalNum.doubleValue());

                updateDatas.add(oScoreManage.get());
            }


            data.setScoreItem(usmr.getScoreItem());
            data.setScoreNum(usmr.getScoreNum());
            updateDatas.add(data);

            boolean updateData = smartScoreManageService.updateBatchById(updateDatas);
            if (!updateData) {
                //return CommonResult.fail("编辑失败");
                throw new Exception("编辑失败！");
            }
        } catch (Exception e) {
            throw new Exception("编辑失败！");
        }

        return CommonResult.ok("编辑成功");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult deleteScoreManage(int id) throws Exception {

        SmartScoreManage data = smartScoreManageService.getSmartScoreManageById(id);
        if (data == null) {
            return CommonResult.fail("数据已失效，删除失败");
        }
        SmartScoreManage parent = smartScoreManageService.getSmartScoreManageById(data.getParentId());
        if (parent == null) {
            return CommonResult.fail("父级数据为空删除失败");
        }
        try {
            int result = smartScoreManageService.deleteSmartScoreManageById(id);
            if (result <= 0) {
                //return CommonResult.fail("删除失败");
                throw new Exception("删除失败！");
            }
            BigDecimal scoreNum = new BigDecimal(parent.getScoreNum()).subtract(new BigDecimal(data.getScoreNum()));
            parent.setScoreNum(scoreNum.doubleValue());

            int update = smartScoreManageService.updateSmartScoreManage(parent);
            if (update <= 0) {
                //return CommonResult.fail("删除失败");
                throw new Exception("删除失败！");
            }
        } catch (Exception e) {
            throw new Exception("删除失败！");
        }

        return CommonResult.ok("删除成功");
    }


    @PassToken
    public CommonResult operateSmartScoreManage(JSONObject jsonObject) {
        SimpleScore simpleScoreLists = null;
        try {
            simpleScoreLists = JSONObject.parseObject(jsonObject.toString(), SimpleScore.class);
        } catch (Exception e) {
            return CommonResult.errorMsg("参数格式错误");
        }
        List<SmartScoreManageList> allList = simpleScoreLists.getSimpleScoreList();
        List<String> mainScoreItems = allList.stream().filter(e -> e.getDeleted() == 0).map(m -> m.getTermId() + m.getScoreItem()).collect(Collectors.toList());
        Set<String> mainScoreSet = new HashSet<>(mainScoreItems);
        if (mainScoreItems.size() != mainScoreSet.size()) {
            return CommonResult.fail("存在重复主项");
        }
        Integer term = allList.get(0).getTermId();
        QueryWrapper<SmartEvaluateTdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term_id", term);
        List<SmartEvaluateTdetail> smartEvaluateTdetails = smartEvaluateTdetailService.getEvaluateTdetailByKey(queryWrapper1);
        if (smartEvaluateTdetails.size() > 0) {
            return CommonResult.fail("该学期已评分，不可再操作");
        }
        List<SmartScoreManage> smList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            SmartScoreManage mainScoreManage = new SmartScoreManage();
            double mainScoreNum = 0;
            if (allList.get(i).getId() == null) {
                allList.get(i).setId((int) UUIDUtil.generateID());
            }
            mainScoreManage.setId(allList.get(i).getId());
            mainScoreManage.setTermId(term);
            mainScoreManage.setScoreItem(allList.get(i).getScoreItem());
            mainScoreManage.setParentId(allList.get(i).getParentId());
            mainScoreManage.setDeleted(allList.get(i).getDeleted());
            List<SmartScoreManageList> childList = allList.get(i).getSmartScoreManageList();
            List<String> scoreItems = childList.stream().filter(e -> e.getDeleted() == 0).map(m -> term + m.getScoreItem()).collect(Collectors.toList());
            Set<String> ScoreSet = new HashSet<>(scoreItems);
            if (scoreItems.size() != ScoreSet.size()) {
                return CommonResult.fail("存在重复子项");
            }
            for (int j = 0; j < childList.size(); j++) {
                SmartScoreManage childScoreManage = new SmartScoreManage();
                if (childList.get(j).getId() == null) {
                    childList.get(j).setId((int) UUIDUtil.generateID());
                }
                childScoreManage.setId(childList.get(j).getId());
                childScoreManage.setTermId(term);
                childScoreManage.setScoreItem(childList.get(j).getScoreItem());
                childScoreManage.setParentId(allList.get(i).getId());
                childScoreManage.setScoreNum(childList.get(j).getScoreNum());
                childScoreManage.setDeleted(childList.get(j).getDeleted());
                smList.add(childScoreManage);
                if (childList.get(j).getDeleted() == 0) {
                    mainScoreNum += childList.get(j).getScoreNum();
                }
            }
            mainScoreManage.setScoreNum(mainScoreNum);
            smList.add(mainScoreManage);
        }
        for (int i = 0; i < smList.size(); i++) {
            // 相关判断
            SmartScoreManage scoreManage = smList.get(i);
            SmartScoreManage sc = smartScoreManageService.getSmartScoreManageById(scoreManage.getId());
            if (sc == null) {
                smartScoreManageService.insertSmartScoreManage(scoreManage);
            } else {
                smartScoreManageService.updateSmartScoreManage(scoreManage);
            }
        }
        return CommonResult.ok("操作成功");
    }

    @PassToken
    public CommonResult getScoreManage(String term) {
        if (term == null) {
            term = smartScoreManageService.getMaxTerm();
        }
        SimpleScore simpleScore = smartScoreManageService.queryScoreDetail(term);
        return CommonResult.ok(simpleScore);
    }

    @PassToken
    public CommonResult getTeacherScoreList(SmartEvaluateTeacher smartEvaluateTeacher, Integer currentPage, Integer pageCount) {
        QueryWrapper<SmartEvaluateTeacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        if (smartEvaluateTeacher.getName() != null && !smartEvaluateTeacher.getName().trim().equals("")) {
            queryWrapper.and(qw -> qw.like("name", smartEvaluateTeacher.getName()).or().like("card_no", smartEvaluateTeacher.getName()));
        }
        if (smartEvaluateTeacher.getTerm() != null && !smartEvaluateTeacher.getTerm().trim().equals("")) {
            queryWrapper.like("term", smartEvaluateTeacher.getTerm());
        }
        if (smartEvaluateTeacher.getSubject() != null && !smartEvaluateTeacher.getSubject().trim().equals("")) {
            queryWrapper.eq("subject", smartEvaluateTeacher.getSubject());
        }
        if (smartEvaluateTeacher.getClassName() != null && !smartEvaluateTeacher.getClassName().trim().equals("")) {
            queryWrapper.eq("class_name", smartEvaluateTeacher.getClassName());
        }
        if (smartEvaluateTeacher.getGradeName() != null && !smartEvaluateTeacher.getGradeName().trim().equals("")) {
            queryWrapper.eq("grade_name", smartEvaluateTeacher.getGradeName());
        }
        queryWrapper.orderByDesc("id");
        PageUtils<SmartEvaluateTeacher> list = smartEvaluateTeacherService.queryPageSmartEvaluateTeacher(currentPage, pageCount, queryWrapper);
        return CommonResult.ok(list);
    }

    @PassToken
    public void getTeacherScoreExcel(SmartEvaluateTeacher smartEvaluateTeacher, HttpServletResponse response) {
        String term = smartScoreManageService.getMaxTerm();
        QueryWrapper<SmartEvaluateTeacher> queryWrapper = new QueryWrapper<>();
        if (smartEvaluateTeacher.getName() != null && !smartEvaluateTeacher.getName().trim().equals("")) {
            queryWrapper.and(qw -> qw.like("name", smartEvaluateTeacher.getName()).or().like("card_no", smartEvaluateTeacher.getName()));
        }
        if (smartEvaluateTeacher.getTerm() != null && !smartEvaluateTeacher.getTerm().trim().equals("")) {
            queryWrapper.like("term", smartEvaluateTeacher.getTerm());
        } else {
            queryWrapper.like("term", term);
        }
        if (smartEvaluateTeacher.getSubject() != null && !smartEvaluateTeacher.getSubject().trim().equals("")) {
            queryWrapper.eq("subject", smartEvaluateTeacher.getSubject());
        }
        if (smartEvaluateTeacher.getClassName() != null && !smartEvaluateTeacher.getClassName().trim().equals("")) {
            queryWrapper.eq("class_name", smartEvaluateTeacher.getClassName());
        }
        List<SmartEvaluateTeacher> outlist = smartEvaluateTeacherService.getEvaluateTeacherByKey(queryWrapper);
        //导出
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("教师评分明细");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("工号");
        headerRow.createCell(2).setCellValue("姓名");
        headerRow.createCell(3).setCellValue("学期");
        headerRow.createCell(4).setCellValue("学科");
        headerRow.createCell(5).setCellValue("班级");
        QueryWrapper<SmartScoreManage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("parent_id", 0);
        queryWrapper1.eq("term", term);
        List<SmartScoreManage> scoreManageList = smartScoreManageService.getScoreManageByKey(queryWrapper1);
        for (int i = 0; i < scoreManageList.size(); i++) {
            headerRow.createCell(i + 6).setCellValue(scoreManageList.get(i).getScoreItem());
        }
        headerRow.createCell(scoreManageList.size() + 6).setCellValue("总分");
        for (int i = 0; i < outlist.size(); i++) {
            SmartEvaluateTeacher teacherScore = outlist.get(i);

            Row dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(i + 1);
            dataRow.createCell(1).setCellValue(teacherScore.getCardNo());
            dataRow.createCell(2).setCellValue(teacherScore.getName());
            dataRow.createCell(3).setCellValue(teacherScore.getTerm());
            dataRow.createCell(4).setCellValue(teacherScore.getSubject());
            dataRow.createCell(5).setCellValue(teacherScore.getClassName());
            // 分数详情
            JSONObject scoreDetail = JSON.parseObject(teacherScore.getEvaluateDetail());
            for (int j = 0; j < scoreManageList.size(); j++) {
                for (Map.Entry entry : scoreDetail.entrySet()) {
                    if (scoreManageList.get(j).getScoreItem().equals(entry.getKey())) {
                        dataRow.createCell(j + 6).setCellValue(entry.getValue().toString());
                    }
                }
            }
        }
        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "教师评测信息.xlsx", response);
    }

    @PassToken
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult evaluateScore(JSONObject jsonObject) throws Exception {
        SimpleEvaluateScore simpleEvaluateScore = null;
        try {
            simpleEvaluateScore = JSONObject.parseObject(jsonObject.toString(), SimpleEvaluateScore.class);
        } catch (Exception e) {
            //return CommonResult.errorMsg("参数格式错误");
            throw new Exception("参数格式错误！");
        }

        try {
            SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(simpleEvaluateScore.getId());
            if (teacher == null) {
                //return CommonResult.fail("教师评分数据为空");
                throw new Exception("教师评分数据为空！");
            }

            List<SmartEvaluateTdetail> newDetails = new ArrayList<>();
            List<SmartEvaluateTdetail> updateDetails = new ArrayList<>();
            //查找明细smart_evaluate_tdetail
            List<SmartEvaluateTdetail> tdetails = smartEvaluateTdetailService.queryTdetailsByTermUserId(teacher.getTermId(), teacher.getUserId());
            for (SmartEvaluateTdetailList ssl : simpleEvaluateScore.getSimpleScoreList()) {
                for (SmartEvaluateTdetailList sc : ssl.getEvaluateList()) {
                    Optional<SmartEvaluateTdetail> oStdetail = tdetails.stream().filter(e -> e.getScoreManageId().equals(sc.getId())).findFirst();
                    if (oStdetail != null && oStdetail.isPresent()) {
                        oStdetail.get().setOwnNum(sc.getOwnNum());
                        updateDetails.add(oStdetail.get());
                    } else {
                        SmartEvaluateTdetail nDetail = new SmartEvaluateTdetail();
                        nDetail.setScoreManageId(sc.getId());
                        nDetail.setTermId(teacher.getTermId());
                        nDetail.setUserId(teacher.getUserId());
                        nDetail.setOwnNum(sc.getOwnNum());
                        newDetails.add(nDetail);
                    }
                }
            }

            teacher.setTotalScore(simpleEvaluateScore.getTotalScore());
            teacher.setLowingScore(simpleEvaluateScore.getLowingScore());

            int updateEvaluate = smartEvaluateTeacherService.updateSmartEvaluateTeacher(teacher);
            if (updateEvaluate <= 0) {
                throw new Exception("教师评分数据更新失败！");
            }

            if (newDetails != null && newDetails.size() > 0) {
                boolean insertDetail = smartEvaluateTdetailService.saveBatch(newDetails);
                if (!insertDetail) {
                    return CommonResult.fail("评价明细数据添加失败");
                }
            }

            if (updateDetails != null && updateDetails.size() > 0) {
                boolean updateDetail = smartEvaluateTdetailService.updateBatchById(updateDetails);
                if (!updateDetail) {
                    return CommonResult.fail("评价明细数据更新失败");
                }
            }
        } catch (Exception e) {
            throw new Exception("评分失败！");
        }

        return CommonResult.ok("评分成功");
    }

    @PassToken
    public CommonResult getTeacherScoreDetail(Integer id) {
        SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(id);
        if (teacher == null) {
            return CommonResult.fail("该条记录已删除");
        }

        SimpleScoreDetailList simpleScoreDetailList = new SimpleScoreDetailList();
        List<SmartEvaluateTdetailList> ls = new ArrayList<>();
        //根据学期ID找到smart_score_manage表中的评分项
        List<SmartScoreManage> ssms = smartScoreManageService.queryDatasByTermId(teacher.getTermId());
        List<SmartEvaluateTdetail> sets = smartEvaluateTdetailService.queryTdetailsByTermUserId(teacher.getTermId(), teacher.getUserId());
        BigDecimal totalScore = new BigDecimal(0.0);//总分值
        BigDecimal ownerTotal = new BigDecimal(0.0);
        if (ssms != null && ssms.size() > 0) {
            List<SmartScoreManage> parentDatas = ssms.stream().filter(e -> e.getParentId() == 0).collect(Collectors.toList());
            for (SmartScoreManage pd : parentDatas) {
                SmartEvaluateTdetailList data = new SmartEvaluateTdetailList();
                data.setId(pd.getId());
                data.setCardNo(teacher.getCardNo());
                data.setTerm(teacher.getTerm());
                data.setTermId(teacher.getTermId());
                data.setParentId(0);
                data.setScoreItem(pd.getScoreItem());
                data.setScoreNum(pd.getScoreNum());
                data.setOwnNum(0.0);//评分数据
                totalScore = totalScore.add(new BigDecimal(pd.getScoreNum()));
                List<SmartEvaluateTdetailList> childs = new ArrayList<>();
                List<SmartScoreManage> detailDatas = ssms.stream().filter(e -> e.getParentId().equals(pd.getId())).collect(Collectors.toList());
                for (SmartScoreManage detail : detailDatas) {
                    SmartEvaluateTdetailList child = new SmartEvaluateTdetailList();
                    child.setId(detail.getId());
                    child.setCardNo(teacher.getCardNo());
                    child.setTerm(teacher.getTerm());
                    child.setTermId(teacher.getTermId());
                    child.setParentId(pd.getId());
                    child.setScoreItem(detail.getScoreItem());
                    child.setScoreNum(detail.getScoreNum());
                    Optional<SmartEvaluateTdetail> oset = sets.stream().filter(e -> e.getScoreManageId().equals(detail.getId())).findFirst();
                    if (oset != null && oset.isPresent()) {
                        child.setOwnNum(oset.get().getOwnNum());
                        ownerTotal = ownerTotal.add(new BigDecimal(oset.get().getOwnNum()));
                    }
                    childs.add(child);
                }
                data.setEvaluateList(childs);
                ls.add(data);
            }
            simpleScoreDetailList.setSimpleScoreDetailList(ls);
        }
        BigDecimal lowingScore = totalScore.subtract(ownerTotal);

        JSONObject resultJson = new JSONObject();
        resultJson.put("id", teacher.getId());
        resultJson.put("totalScore", ownerTotal);
        resultJson.put("lowingScore", lowingScore);
        resultJson.put("simpleScoreList", simpleScoreDetailList);
        return CommonResult.ok(resultJson);
    }

    @PassToken
    public CommonResult getScoreComparison(Integer id) {
        SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(id);
        QueryWrapper<SmartEvaluateTdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term_id", teacher.getTermId());
        List<SmartEvaluateTdetail> detailList = smartEvaluateTdetailService.getEvaluateTdetailByKey(queryWrapper1);
        int teacherCount = smartEvaluateTeacherService.queryTeacherCount(teacher.getTermId());
        List<SmartScoreManage> scoreManages = smartScoreManageService.queryDatasByTermId(teacher.getTermId());
        List<SmartScoreManage> parentScoreManages = scoreManages.stream().filter(e -> e.getParentId().intValue() == 0).collect(Collectors.toList());
        List<JSONObject> resultJson = new ArrayList<>();
        for (SmartScoreManage parentData : parentScoreManages) {
            JSONObject jsonObject = new JSONObject();
            BigDecimal ownScore = new BigDecimal(0.0);
            BigDecimal avgScore = new BigDecimal(0.0);
            List<SmartScoreManage> childs = scoreManages.stream().filter(e -> e.getParentId().equals(parentData.getId())).collect(Collectors.toList());
            for (SmartScoreManage child : childs) {
                List<SmartEvaluateTdetail> childDatas =detailList.stream().filter(e -> e.getScoreManageId().equals(child.getId())).collect(Collectors.toList());
                for (SmartEvaluateTdetail childData:childDatas) {
                    if (childData.getUserId().equals(teacher.getUserId())) {
                        ownScore = ownScore.add(new BigDecimal(childData.getOwnNum()));
                    }
                    avgScore = avgScore.add(new BigDecimal(childData.getOwnNum()));
                }
            }

            Double avg = teacherCount == 0 ? 0 : (new BigDecimal(avgScore.doubleValue() / teacherCount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            jsonObject.put("name", parentData.getScoreItem());
            jsonObject.put("ownScore", ownScore);
            jsonObject.put("avgScore", avg);
            resultJson.add(jsonObject);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "扣");
        jsonObject.put("ownScore", teacher.getLowingScore());
        jsonObject.put("avgScore", smartEvaluateTeacherService.getAvgLowingScore(teacher.getTerm()));
        resultJson.add(jsonObject);
        return CommonResult.ok(resultJson);
    }

    @PassToken
    public CommonResult getScoreRank(int currentPage, int pageCount, String subject) {
        QueryWrapper<SmartEvaluateTeacher> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("term", smartScoreManageService.getMaxTerm());
        queryWrapper1.eq("deleted", 0);
        if (subject != null) {
            queryWrapper1.eq("subject", subject);
        }
        queryWrapper1.orderByDesc("total_score");
        PageUtils<SmartEvaluateTeacher> list = smartEvaluateTeacherService.queryPageSmartEvaluateTeacher(currentPage, pageCount, queryWrapper1);
        return CommonResult.ok(list);
    }

    @PassToken
    public CommonResult queryTopSixTeacher() {
        List<EvaluateTeacherVo> teachers = smartEvaluateTeacherService.smartTopTeacherList();

        return CommonResult.ok(teachers);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult rankingList(String cardNo) {
        LocalDateTime now = LocalDateTime.now();
        SmartSemester smartSemester = smartSemesterService.getSemester(now);
        if (ObjectUtils.isEmpty(smartSemester)) {
            return CommonResult.ok("当前时间不属于任何学期");
        }
        String term = smartSemester.getName();

        List<RankingVo> rankingList = smartEvaluateTeacherService.getRankingList(term);
        RankingVo vo = smartEvaluateTeacherService.getRanking(term, cardNo);

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", rankingList);
        map.put("single", vo);

        return CommonResult.ok(map);
    }
}
