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.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.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
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("deleted", 0);
        queryWrapper1.eq("grade", smartSubjectTemplate.getGrade());
        queryWrapper1.eq("term", smartSubjectTemplate.getTerm());
        // 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("存在重复等级");
        }
        smartSubjectTemplate.setDeleted(0);
        smartSubjectTemplateService.insertSmartSubjectTemplate(smartSubjectTemplate);
        for (int i = 0; i < ruleList.size(); i++) {
            SmartTemplateRule rule = ruleList.get(i);
            rule.setTemplateId(smartSubjectTemplate.getId());
            rule.setDeleted(0);
            smartTemplateRuleService.insertSmartTemplateRule(rule);
        }
        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("deleted", 0);
        queryWrapper1.eq("grade", smartSubjectTemplate.getGrade());
        queryWrapper1.eq("term", smartSubjectTemplate.getTerm());
        // 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("deleted", 0);
        queryWrapper2.eq("grade_name", smartSubjectTemplate.getGrade());
        queryWrapper2.eq("term", smartSubjectTemplate.getTerm());
        // 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().filter(e->e.getDeleted().equals(0)).map(SmartTemplateRule::getLevel).collect(Collectors.toList());
        Set<String> levelSet = new HashSet<>(levels);
        if (levels.size() != levelSet.size()) {
            return CommonResult.fail("存在重复等级");
        }
        for (int i = 0; i < ruleList.size(); i++) {
            SmartTemplateRule rule = ruleList.get(i);
            if (rule.getId()==null){
                rule.setId((int) UUIDUtil.generateID());
            }
            rule.setTemplateId(smartSubjectTemplate.getId());
            SmartTemplateRule ruleListc = smartTemplateRuleService.getSmartTemplateRuleById(rule.getId());
            if (ruleListc==null){
                smartTemplateRuleService.insertSmartTemplateRule(rule);
            } else {
                smartTemplateRuleService.updateSmartTemplateRule(rule);
            }
        }
        smartSubjectTemplate.setDeleted(0);
        smartSubjectTemplateService.updateSmartSubjectTemplate(smartSubjectTemplate);
        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("deleted", 0);
        queryWrapper1.eq("grade_name", smartSubjectTemplate.getGrade());
        queryWrapper1.eq("term", smartSubjectTemplate.getTerm());
        // queryWrapper1.eq("exam_type", smartSubjectTemplate.getExamType());
        queryWrapper1.isNotNull("score_level");
        List<SmartEvaluateStudent> evaluateData = smartEvaluateStudentService.getSmartEvaluateStudentByKey(queryWrapper1);
        if (!evaluateData.isEmpty()){
            return CommonResult.fail("该评分项已评测，不可删除");
        }
        QueryWrapper<SmartTemplateRule> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("deleted", 0);
        queryWrapper2.eq("template_id", smartSubjectTemplate.getId());
        List<SmartTemplateRule> listc = smartTemplateRuleService.getSmartTemplateRuleByKey(queryWrapper2);
        if (!listc.isEmpty()){
            SmartTemplateRule sr = new SmartTemplateRule();
            sr.setDeleted(1);
            smartTemplateRuleService.update(sr, queryWrapper2);
        }
        smartSubjectTemplateService.deleteSmartSubjectTemplateById(id);
        return CommonResult.ok("操作成功");
    }

    @PassToken
    @DESRespondSecret(validated = false)
    public CommonResult queryTemplatePage(Integer currentPage, Integer pageCount) {
        QueryWrapper<SmartSubjectTemplate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.orderByDesc("id");
        PageUtils<SmartSubjectTemplate> list = smartSubjectTemplateService.queryPageSmartSubjectTemplate(currentPage, pageCount, queryWrapper1);
        return CommonResult.ok(list);
    }

    @PassToken
    @DESRespondSecret(validated = false)
    public CommonResult queryTemplateRulePage(Integer id) {
        QueryWrapper<SmartTemplateRule> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        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("该条记录已删除");
        }
        QueryWrapper<SmartSubjectTemplate> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("grade", evaluateStudent.getGradeName());
        queryWrapper1.eq("term", evaluateStudent.getTerm());
        List<SmartSubjectTemplate> templateList = smartSubjectTemplateService.getSmartSubjectTemplateByKey(queryWrapper1);
        if (templateList.isEmpty()){
            return CommonResult.fail("未查询到相关评价模板");
        }
        SmartSubjectTemplate template = templateList.get(0);
        String[] examType = template.getExamType().split(",");
        QueryWrapper<SmartGrade> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("deleted", 0);
        queryWrapper2.eq("name", template.getGrade());
        SmartGrade smartGrade = smartGradeService.getOne(queryWrapper2);
        Double totalScore = 0.00;
        int k = 0;
        for (int i = 0; i < examType.length; i++) {
            QueryWrapper<SmartExamtype> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("deleted", 0);
            queryWrapper3.eq("grade_id",smartGrade.getId());
            queryWrapper3.eq("name", examType[i]);
            SmartExamtype smartExamtype = smartExamtypeService.getOne(queryWrapper3);
            if (smartExamtype.getIsExam()==0){
                return CommonResult.fail(smartGrade.getName()+"-"+smartExamtype.getName()+"不支持综评！");
            }
            QueryWrapper<SmartScore> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("deleted", 0);
            queryWrapper4.eq("semester", template.getTerm());
            queryWrapper4.eq("grade", template.getGrade());
            queryWrapper4.eq("exam_type", smartExamtype.getId());
            queryWrapper4.eq("card_no", evaluateStudent.getCardNo());
            List<SmartScore> scoreList = smartScoreService.list(queryWrapper4);
            if (scoreList.isEmpty()){
                return CommonResult.fail("未查询到"+evaluateStudent.getName()+"-"+template.getTerm()+"-"+smartExamtype.getName()+"考试成绩");
            }
            for (int j = 0; j < scoreList.size(); j++) {
                totalScore+=scoreList.get(j).getScore();
                k++;
            }
        }
        Double avgScore = totalScore/k;
        QueryWrapper<SmartTemplateRule> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("deleted", 0);
        queryWrapper5.eq("template_id", template.getId());
        List<SmartTemplateRule> ruleList = smartTemplateRuleService.getSmartTemplateRuleByKey(queryWrapper5);
        if (ruleList.isEmpty()){
            return CommonResult.fail("未配置评分规则");
        }
        String scoreLevel = "";
        for (int j = 0; j < ruleList.size(); j++) {
            String[] range = ruleList.get(j).getScoreRange().split("-");
            double min = Double.parseDouble(range[0]);
            double max = Double.parseDouble(range[1]);
            if (avgScore >= min && avgScore <= max) {
                scoreLevel = ruleList.get(j).getLevel();
                break;
            }
        }
        evaluateStudent.setScoreNum(avgScore);
        evaluateStudent.setScoreLevel(scoreLevel);
        evaluateStudent.setScoreComment(scoreComment);
        smartEvaluateStudentService.updateSmartEvaluateStudent(evaluateStudent);
        return CommonResult.ok();
    }

    @PassToken
    public CommonResult queryEvaluateStudent(SmartEvaluateStudent smartEvaluateStudent, Integer currentPage, Integer pageCount) {
        QueryWrapper<SmartEvaluateStudent> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        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);
    }

}
