package com.template.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.SmartEvaluateStudentControlle2API;
import com.template.common.utils.UUIDUtil;
import com.template.common.utils.paramUtils;
import com.template.model.evaluate.student.*;
import com.template.model.pojo.SmartExamtype;
import com.template.model.pojo.SmartGrade;
import com.template.model.pojo.SmartScore;
import com.template.model.request.addTemplateRuleRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.services.*;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    public SmartSubjectManageService smartSubjectManageService;
    @Autowired
    public SmartSubjectRuleService smartSubjectRuleService;
    @Autowired
    public SmartEvaluateStudentService smartEvaluateStudentService;
    @Autowired
    public SmartEvaluateSdetailService smartEvaluateSdetailService;
    @Autowired
    public SmartSubjectTemplateService smartSubjectTemplateService;
    @Autowired
    public SmartTemplateRuleService smartTemplateRuleService;
    @Autowired
    public SmartExamtypeService smartExamtypeService;
    @Autowired
    public SmartScoreService smartScoreService;
    @Autowired
    public SmartGradeService smartGradeService;

    /**
     * ==============================第二版============================
     **/
    @PassToken
    public CommonResult addSmartSubjectTemplate(JSONObject jsonObject) {
        SmartTemplateRuleList smartTemplateRuleList = null;
        try {
            smartTemplateRuleList = JSONObject.parseObject(jsonObject.toString(), SmartTemplateRuleList.class);
        } catch (Exception e) {
            return CommonResult.errorMsg("参数格式错误");
        }
        SmartSubjectTemplate smartSubjectTemplate = smartTemplateRuleList.getSmartSubjectTemplate();
        QueryWrapper<SmartSubjectTemplate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("grade_id", smartSubjectTemplate.getGradeId());
        queryWrapper1.eq("term_id", smartSubjectTemplate.getTermId());
        // queryWrapper1.eq("exam_type", smartSubjectTemplate.getExamType());
        List<SmartSubjectTemplate> listc = smartSubjectTemplateService.list(queryWrapper1);
        if (!listc.isEmpty()) {
            return CommonResult.fail("该评分项已存在");
        }
        List<SmartTemplateRule> ruleList = smartTemplateRuleList.getRuleList();
        List<String> levels = ruleList.stream().map(SmartTemplateRule::getLevel).collect(Collectors.toList());
        Set<String> levelSet = new HashSet<>(levels);
        if (levels.size() != levelSet.size()) {
            return CommonResult.fail("存在重复等级");
        }
        int insertTemplate = smartSubjectTemplateService.insertSmartSubjectTemplate(smartSubjectTemplate);
        if (insertTemplate <= 0) {
            return CommonResult.fail("操作失败");
        }

        List<SmartTemplateRule> rules = new ArrayList<>();
        for (int i = 0; i < ruleList.size(); i++) {
            SmartTemplateRule rule = ruleList.get(i);
            rule.setTemplateId(insertTemplate);
            rules.add(rule);
        }
        boolean insertRuleBatch = smartTemplateRuleService.saveBatch(rules);
        if (!insertRuleBatch) {
            return CommonResult.fail("操作失败");
        }

        List<Integer> examTypes = new ArrayList<>();
        for (SmartTermTemplate stt : smartSubjectTemplate.getExamTypes()) {
            examTypes.add(stt.getId());
        }
        List<SmartScore> scores = smartScoreService.querySmartScoresByex(smartSubjectTemplate.getTermId(), smartSubjectTemplate.getGradeId(), examTypes);
        List<Integer> userIds = scores.stream().map(SmartScore::getUserId).distinct().collect(Collectors.toList());
        List<SmartEvaluateStudent> insertStudents = new ArrayList<>();
        for (Integer userId : userIds) {
            SmartEvaluateStudent ses = new SmartEvaluateStudent();
            ses.setTermId(smartSubjectTemplate.getTermId());
            ses.setTerm(smartSubjectTemplate.getTerm());
            ses.setUserId(userId);

            List<SmartScore> userScores = scores.stream().filter(e -> e.getUserId().equals(userId)).collect(Collectors.toList());
            if (userScores != null && userScores.size() > 0) {
                ses.setGradeName(userScores.get(0).getGrade());
                ses.setGradeId(userScores.get(0).getGradeId());
                ses.setClassId(userScores.get(0).getSchoolClassId());
                ses.setClassName(userScores.get(0).getSchoolClass());
                ses.setCardNo(userScores.get(0).getCardNo());
                ses.setName(userScores.get(0).getName());
                BigDecimal totalScoreNum = new BigDecimal(0.0);
                Integer scoreNum = 0;
                for (SmartScore us : userScores) {
                    totalScoreNum = totalScoreNum.add(new BigDecimal(us.getScore()));
                    scoreNum++;

                }
                ses.setScoreNum(totalScoreNum.doubleValue());
                ses.setSubjectNum(scoreNum);
            }
            insertStudents.add(ses);
        }
        if (insertStudents != null && insertStudents.size() > 0) {
            boolean insertBatch = smartEvaluateStudentService.saveBatch(insertStudents);
            if (!insertBatch) {
                return CommonResult.fail("操作失败");
            }
        }

        return CommonResult.ok("操作成功");
    }

    @PassToken
    public CommonResult updateSmartSubjectTemplate(JSONObject jsonObject) {
        SmartTemplateRuleList smartTemplateRuleList = null;
        try {
            smartTemplateRuleList = JSONObject.parseObject(jsonObject.toString(), SmartTemplateRuleList.class);
        } catch (Exception e) {
            return CommonResult.errorMsg("参数格式错误");
        }
        SmartSubjectTemplate smartSubjectTemplate = smartTemplateRuleList.getSmartSubjectTemplate();
        QueryWrapper<SmartSubjectTemplate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("grade_id", smartSubjectTemplate.getGradeId());
        queryWrapper1.eq("term_id", smartSubjectTemplate.getTermId());
        // queryWrapper1.eq("exam_type", smartSubjectTemplate.getExamType());
        List<SmartSubjectTemplate> listc = smartSubjectTemplateService.list(queryWrapper1);
        if (!listc.isEmpty() && !Objects.equals(listc.get(0).getId(), smartSubjectTemplate.getId())) {
            return CommonResult.fail("该评分项已存在");
        }
        SmartSubjectTemplate st = smartSubjectTemplateService.getSmartSubjectTemplateById(smartSubjectTemplate.getId());
        if (st == null) {
            return CommonResult.fail("未找到该评分项");
        }
        QueryWrapper<SmartEvaluateStudent> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("grade_id", smartSubjectTemplate.getGradeId());
        queryWrapper2.eq("term_id", smartSubjectTemplate.getTermId());
        // queryWrapper2.eq("exam_type", smartSubjectTemplate.getExamType());
        queryWrapper2.isNotNull("score_level");
        List<SmartEvaluateStudent> evaluateData = smartEvaluateStudentService.getSmartEvaluateStudentByKey(queryWrapper2);
        if (!evaluateData.isEmpty()) {
            return CommonResult.fail("该评分项已评测，不可修改");
        }
        List<SmartTemplateRule> ruleList = smartTemplateRuleList.getRuleList();
        List<String> levels = ruleList.stream().map(SmartTemplateRule::getLevel).collect(Collectors.toList());
        Set<String> levelSet = new HashSet<>(levels);
        if (levels.size() != levelSet.size()) {
            return CommonResult.fail("存在重复等级");
        }
        smartTemplateRuleService.deleteSmartTemplateRuleBytId(smartSubjectTemplate.getId());

        List<SmartTemplateRule> rules = new ArrayList<>();
        for (int i = 0; i < ruleList.size(); i++) {
            SmartTemplateRule rule = ruleList.get(i);
            rule.setTemplateId(smartSubjectTemplate.getId());
            rules.add(rule);
        }
        if (rules != null && rules.size() > 0) {
            boolean insertBatch = smartTemplateRuleService.saveBatch(rules);
            if (!insertBatch) {
                return CommonResult.fail("修改失败");
            }
        }

        int insert = smartSubjectTemplateService.updateSmartSubjectTemplate(smartSubjectTemplate);
        if (insert <= 0) {
            return CommonResult.fail("修改失败");
        }

        //region 学生综合评价
        List<Integer> examTypes = new ArrayList<>();
        List<String> allExamTypes = new ArrayList<>();
        List<String> oldExamTypes = st.getExamType() == null ? new ArrayList<>() : Arrays.asList(st.getExamType().split(","));
        for (int i = 0; i < oldExamTypes.size(); i++) {
            allExamTypes.add(oldExamTypes.get(i));
        }
        for (SmartTermTemplate stt : smartSubjectTemplate.getExamTypes()) {
            examTypes.add(stt.getId());
            String idstr = String.valueOf(stt.getId());
            allExamTypes.add(idstr);
        }

        allExamTypes = allExamTypes.stream().distinct().collect(Collectors.toList());

        List<SmartScore> scores = smartScoreService.querySmartScoresByexs(smartSubjectTemplate.getTermId(), smartSubjectTemplate.getGradeId(), allExamTypes);
        List<Integer> userIds = scores.stream().map(SmartScore::getUserId).distinct().collect(Collectors.toList());
        List<SmartEvaluateStudent> students = smartEvaluateStudentService.getEvaluateStudents(userIds, smartSubjectTemplate.getTermId());
        List<SmartEvaluateStudent> updateStudents = new ArrayList<>();
        List<SmartEvaluateStudent> insertStudents = new ArrayList<>();
        for (Integer userId : userIds) {
            List<SmartScore> userScores = scores.stream().filter(e -> e.getUserId().equals(userId)).collect(Collectors.toList());
            BigDecimal totalScoreNum = new BigDecimal(0.0);
            Integer scoreNum = 0;
            if (userScores != null && userScores.size() > 0) {
                Optional<SmartEvaluateStudent> oStudent = students.stream().filter(e -> e.getTermId().equals(smartSubjectTemplate.getTermId()) && e.getUserId().equals(userId)).findFirst();
                for (SmartScore us : userScores) {
                    if (examTypes.contains(us.getExamType())) {
                        totalScoreNum = totalScoreNum.add(new BigDecimal(us.getScore()));
                        scoreNum++;
                    }
                }
                if (oStudent != null && oStudent.isPresent()) {
                    oStudent.get().setScoreNum(totalScoreNum.doubleValue());
                    oStudent.get().setSubjectNum(scoreNum);
                    updateStudents.add(oStudent.get());
                } else {
                    Optional<SmartScore> oSmartScore = scores.stream().filter(e -> e.getSemesterId().equals(smartSubjectTemplate.getTermId()) && e.getUserId().equals(userId)).findFirst();
                    SmartEvaluateStudent ses = new SmartEvaluateStudent();
                    ses.setTermId(smartSubjectTemplate.getTermId());
                    ses.setUserId(userId);
                    if (oSmartScore != null && oSmartScore.isPresent()) {
                        ses.setTerm(oSmartScore.get().getSemester());
                        ses.setGradeName(oSmartScore.get().getGrade());
                        ses.setGradeId(oSmartScore.get().getGradeId());
                        ses.setClassId(oSmartScore.get().getSchoolClassId());
                        ses.setClassName(oSmartScore.get().getSchoolClass());
                        ses.setCardNo(oSmartScore.get().getCardNo());
                        ses.setName(oSmartScore.get().getName());
                    }
                    ses.setScoreNum(totalScoreNum.doubleValue());
                    ses.setSubjectNum(scoreNum);
                    insertStudents.add(ses);
                }
            }
        }
        if (insertStudents != null && insertStudents.size() > 0) {
            boolean insertBatch = smartEvaluateStudentService.saveBatch(insertStudents);
            if (!insertBatch) {
                return CommonResult.fail("修改失败");
            }
        }

        if (updateStudents != null && updateStudents.size() > 0) {
            boolean updateBatch = smartEvaluateStudentService.updateBatchById(updateStudents);
            if (!updateBatch) {
                return CommonResult.fail("修改失败");
            }
        }
        //endregion

        return CommonResult.ok("修改成功");
    }

    @PassToken
    public CommonResult delSmartSubjectTemplate(Integer id) {
        if (id == null) {
            return CommonResult.fail("请传入ID");
        }
        SmartSubjectTemplate smartSubjectTemplate = smartSubjectTemplateService.getSmartSubjectTemplateById(id);
        if (smartSubjectTemplate == null) {
            return CommonResult.fail("该评分项不存在");
        }
        QueryWrapper<SmartEvaluateStudent> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("grade_id", smartSubjectTemplate.getGradeId());
        queryWrapper1.eq("term_id", smartSubjectTemplate.getTermId());
        // queryWrapper1.eq("exam_type", smartSubjectTemplate.getExamType());
        queryWrapper1.isNotNull("score_level");
        List<SmartEvaluateStudent> evaluateData = smartEvaluateStudentService.getSmartEvaluateStudentByKey(queryWrapper1);
        if (!evaluateData.isEmpty()) {
            return CommonResult.fail("该评分项已评测，不可删除");
        }

        int listc = smartTemplateRuleService.deleteSmartTemplateRuleBytId(smartSubjectTemplate.getId());

        smartSubjectTemplateService.deleteSmartSubjectTemplateById(id);
        return CommonResult.ok("操作成功");
    }

    @PassToken
    @DESRespondSecret(validated = false)
    public CommonResult queryTemplatePage(Integer currentPage, Integer pageCount) {
        QueryWrapper<SmartSubjectTemplate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.orderByDesc("id");
        PageUtils<SmartSubjectTemplate> list = smartSubjectTemplateService.queryPageSmartSubjectTemplate(currentPage, pageCount, queryWrapper1);
        List<SmartExamtype> examtypes = smartExamtypeService.list(null);
        if (list.getList() != null && list.getList().size() > 0) {
            List<Integer> gradeIds = list.getList().stream().map(SmartSubjectTemplate::getGradeId).distinct().collect(Collectors.toList());
            List<Integer> termIds =list.getList().stream().map(SmartSubjectTemplate::getTermId).distinct().collect(Collectors.toList());
            List<SmartEvaluateStudent> eStudents = smartEvaluateStudentService.queryUseEvaluateStudents(gradeIds, termIds);
            for (SmartSubjectTemplate data : list.getList()) {
                List<SmartTermTemplate> examTypeDatas = new ArrayList<>();
                List<String> names = new ArrayList<>();
                List<String> examTypes = Arrays.asList(data.getExamType().split(","));
                if (examtypes != null && examtypes.size() > 0) {
                    for (String examType : examTypes) {
                        Optional<SmartExamtype> oExamtype = examtypes.stream().filter(e -> String.valueOf(e.getId()).equals(examType)).findFirst();
                        if (oExamtype != null && oExamtype.isPresent()) {
                            names.add(oExamtype.get().getName());
                            SmartTermTemplate examTypeData = new SmartTermTemplate();
                            examTypeData.setId(oExamtype.get().getId());
                            examTypeData.setName(oExamtype.get().getName());
                            examTypeDatas.add(examTypeData);
                        }
                    }
                }
                if (names != null && names.size() > 0) {
                    data.setExamType(StringUtils.join(names, ","));
                }
                data.setExamTypes(examTypeDatas);

                data.setIsUse(0);
                if(eStudents != null && eStudents.size() > 0){
                    long existCount =  eStudents.stream().filter(e -> e.getTermId().intValue() == data.getTermId().intValue()
                            && e.getGradeId().intValue() == data.getGradeId().intValue()).count();
                    if(existCount > 0){
                        data.setIsUse(1);
                    }
                }
            }

        }
        return CommonResult.ok(list);
    }

    @PassToken
    @DESRespondSecret(validated = false)
    public CommonResult queryTemplateRulePage(Integer id) {
        QueryWrapper<SmartTemplateRule> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("template_id", id);
        queryWrapper1.orderByDesc("id");
        List<SmartTemplateRule> list = smartTemplateRuleService.getSmartTemplateRuleByKey(queryWrapper1);
        return CommonResult.ok(list);
    }

    @PassToken
    public CommonResult evaluateScore(Integer id, String scoreComment) {
        if (id == null) {
            return CommonResult.fail("请传入ID");
        }
        SmartEvaluateStudent evaluateStudent = smartEvaluateStudentService.getSmartEvaluateStudentById(id);
        if (evaluateStudent == null) {
            return CommonResult.fail("该条记录已删除");
        }

        evaluateStudent.setScoreComment(scoreComment);
        smartEvaluateStudentService.updateSmartEvaluateStudent(evaluateStudent);
        return CommonResult.ok("评价成功");
    }

    @PassToken
    public CommonResult queryEvaluateStudent(SmartEvaluateStudent smartEvaluateStudent, Integer currentPage, Integer pageCount) {
        QueryWrapper<SmartEvaluateStudent> queryWrapper1 = new QueryWrapper<>();
        if (smartEvaluateStudent.getName() != null && !smartEvaluateStudent.getName().trim().equals("")) {
            queryWrapper1.and(qw -> qw.like("name", smartEvaluateStudent.getName()).or().like("card_no", smartEvaluateStudent.getName()));
        }
        if (smartEvaluateStudent.getTerm() != null && !smartEvaluateStudent.getTerm().trim().equals("")) {
            queryWrapper1.like("term", smartEvaluateStudent.getTerm());
        }
        if (smartEvaluateStudent.getGradeName() != null && !smartEvaluateStudent.getGradeName().trim().equals("")) {
            queryWrapper1.eq("grade_name", smartEvaluateStudent.getGradeName());
        }
        if (smartEvaluateStudent.getClassName() != null && !smartEvaluateStudent.getClassName().trim().equals("")) {
            queryWrapper1.eq("class_name", smartEvaluateStudent.getClassName());
        }
        if (smartEvaluateStudent.getScoreLevel() != null && !smartEvaluateStudent.getScoreLevel().trim().equals("")) {
            queryWrapper1.eq("score_level", smartEvaluateStudent.getClassName());
        }
        queryWrapper1.orderByDesc("id");
        PageUtils<SmartEvaluateStudent> list = smartEvaluateStudentService.queryPageSmartEvaluateStudent(currentPage, pageCount, queryWrapper1);
        return CommonResult.ok(list);
    }

    @Override
    public CommonResult addSmartTemplateRule(addTemplateRuleRequest atrr, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        if(atrr.getMinScore() >= atrr.getMaxScore()){
            return CommonResult.fail("最小分不能大于等于最大分");
        }

        List<SmartTemplateRule> rules = smartTemplateRuleService.querySmartTemplateRuleBytId(atrr.getTemplateId());
        if (rules != null && rules.size() > 0) {
            for (SmartTemplateRule rule : rules) {
                if (rule.getLevel().equals(atrr.getLevel())) {
                    return CommonResult.fail("评分子项中已包含评分等级：" + atrr.getLevel());
                }

                Integer minValue = 0;
                Integer maxValue = 0;
                String[] levels = rule.getScoreRange().split("-");
                if (Integer.valueOf(levels[0]).intValue() > Integer.valueOf(levels[1]).intValue()) {
                    minValue = Integer.valueOf(levels[1]).intValue();
                    maxValue = Integer.valueOf(levels[0]).intValue();
                } else {
                    minValue = Integer.valueOf(levels[0]).intValue();
                    maxValue = Integer.valueOf(levels[1]).intValue();
                }

                if ((atrr.getMinScore() >= minValue && atrr.getMinScore() <= maxValue)
                        || (atrr.getMinScore() <= minValue && atrr.getMaxScore() >= maxValue)
                        || (atrr.getMaxScore() >= minValue && atrr.getMinScore() <= maxValue)) {
                    return CommonResult.fail("评分区间和评分等级：" + rule.getLevel() + "重合");
                }

            }
        }
        SmartTemplateRule rule = new SmartTemplateRule();
        rule.setTemplateId(atrr.getTemplateId());
        rule.setLevel(atrr.getLevel());
        rule.setScoreRange(atrr.getMinScore() + "-" + atrr.getMaxScore());

        int result = smartTemplateRuleService.insertSmartTemplateRule(rule);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

}
