package com.template.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.template.annotation.PassToken;
import com.template.api.SmartEvaluateStudentControllerAPI;
import com.template.common.jh.ReqRespResearchProductQuestionnaireItem;
import com.template.common.jh.SectionUtil;
import com.template.common.utils.UUIDUtil;
import com.template.model.evaluate.student.*;
import com.template.model.evaluate.teacher.SimpleScore;
import com.template.model.evaluate.teacher.SmartEvaluateTdetail;
import com.template.model.evaluate.teacher.SmartEvaluateTeacher;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.services.SmartEvaluateSdetailService;
import com.template.services.SmartEvaluateStudentService;
import com.template.services.SmartSubjectManageService;
import com.template.services.SmartSubjectRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class SmartEvaluateStudentController implements SmartEvaluateStudentControllerAPI {

    @Autowired
    public SmartSubjectManageService smartSubjectManageService;
    @Autowired
    public SmartSubjectRuleService smartSubjectRuleService;
    @Autowired
    public SmartEvaluateStudentService smartEvaluateStudentService;
    @Autowired
    public SmartEvaluateSdetailService smartEvaluateSdetailService;

    @PassToken
    public CommonResult operateSmartSubjectManage(JSONObject jsonObject){
        SubjectManageList subjectManageList = null;
        try {
            subjectManageList = JSONObject.parseObject(jsonObject.toString(), SubjectManageList.class);
        } catch (Exception e){
            return CommonResult.errorMsg("参数格式错误");
        }
        List<SmartSubjectManage> allList = subjectManageList.getSubjectList();
        System.out.println("==="+allList);
        List<String> subjectLists = allList.stream().filter(e->e.getDeleted()==0).map(m->m.getTerm()+m.getName()).collect(Collectors.toList());
        Set<String> mainScoreSet = new HashSet<>(subjectLists);
        if (subjectLists.size()!=mainScoreSet.size()){
            return CommonResult.fail("存在重复学科");
        }
        QueryWrapper<SmartEvaluateSdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term",allList.get(0).getTerm());
        List<SmartEvaluateSdetail> smartEvaluateTdetails = smartEvaluateSdetailService.getSmartEvaluateSdetailByKey(queryWrapper1);
        if (smartEvaluateTdetails.size()>0){
            return CommonResult.fail("该学期已有评测数据，不可再更改");
        }
        for (int i = 0; i < allList.size(); i++) {
            SmartSubjectManage smartSubjectManage = allList.get(i);
            if (smartSubjectManage.getId()==null){
                smartSubjectManage.setId((int) UUIDUtil.generateID());
            }
            SmartSubjectManage listc = smartSubjectManageService.getSmartSubjectManageById(smartSubjectManage.getId());
            if (listc==null){
                smartSubjectManageService.insertSmartSubjectManage(smartSubjectManage);
            } else {
                smartSubjectManageService.updateSmartSubjectManage(smartSubjectManage);
            }
        }
        return CommonResult.ok("操作成功");
    }

    @PassToken
    public CommonResult querySubjectManage(String term){
        if (term==null){
            term=smartSubjectManageService.getMaxTerm();
        }
        QueryWrapper<SmartSubjectManage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term",term);
        List<SmartSubjectManage> list = smartSubjectManageService.getSmartSubjectManageByKey(queryWrapper1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("subjectList", list);
        return CommonResult.ok(jsonObject);
    }

    @PassToken
    public CommonResult operateSmartSubjectRule(JSONObject jsonObject){
        SmartSubjectRuleOutList smartSubjectRuleOutList = null;
        try {
            smartSubjectRuleOutList = JSONObject.parseObject(jsonObject.toString(), SmartSubjectRuleOutList.class);
        } catch (Exception e){
            return CommonResult.errorMsg("参数格式错误");
        }
        List<SmartSubjectRuleInList> outList = smartSubjectRuleOutList.getSmartSubjectRuleInLists();
        List<SmartSubjectRule> data = new ArrayList<>();
        for (int i = 0; i < outList.size(); i++) {
            String subjectName = outList.get(i).getSubjectName();
            String term = outList.get(i).getTerm();
            List<SmartSubjectRule> smartSubjectRules = outList.get(i).getSubjectRuleList();
            List<String> ruleList = smartSubjectRules.stream().filter(e->e.getDeleted()==0).map(SmartSubjectRule::getLevel).collect(Collectors.toList());
            Set<String> ruleSet = new HashSet<>(ruleList);
            if (ruleList.size()!=ruleSet.size()){
                return CommonResult.fail("存在重复等级");
            }
            List<String> rangeList = smartSubjectRules.stream().filter(e->e.getDeleted()==0).map(SmartSubjectRule::getScoreRange).collect(Collectors.toList());
            List<ReqRespResearchProductQuestionnaireItem> all = new ArrayList<>();
            for (int j = 0; j < rangeList.size(); j++) {
                String[] ls = rangeList.get(j).split("-");
                ReqRespResearchProductQuestionnaireItem re = new ReqRespResearchProductQuestionnaireItem(ls[0],ls[1], (byte) 7);
                all.add(re);
            }
            if (SectionUtil.compareSection(all)){
                return CommonResult.fail("存在重复区间");
            }
            for (int j = 0; j < smartSubjectRules.size(); j++) {
                SmartSubjectRule smartSubjectRule = smartSubjectRules.get(j);
                if (smartSubjectRule.getId()==null){
                    smartSubjectRule.setId((int) UUIDUtil.generateID());
                }
                smartSubjectRule.setSubjectName(subjectName);
                smartSubjectRule.setTerm(term);
                data.add(smartSubjectRule);
            }
        }
        for (int i = 0; i < data.size(); i++) {
            SmartSubjectRule smartSubjectRule = data.get(i);
            SmartSubjectRule rule = smartSubjectRuleService.getSmartSubjectRuleById(smartSubjectRule.getId());
            if (rule==null) {
                smartSubjectRuleService.insertSmartSubjectRule(smartSubjectRule);
            } else {
                smartSubjectRuleService.updateSmartSubjectRule(smartSubjectRule);
            }
        }
        return CommonResult.ok("操作成功");
    }

    @PassToken
    public CommonResult querySubjectRule(String term){
        if (term==null){
            term=smartSubjectManageService.getMaxTerm();
        }
        QueryWrapper<SmartSubjectManage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term",term);
        queryWrapper1.eq("shows", 1);
        List<SmartSubjectManage> list = smartSubjectManageService.getSmartSubjectManageByKey(queryWrapper1);
        JSONObject jsonObject1 = new JSONObject();
        List<JSONObject> lj = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            QueryWrapper<SmartSubjectRule> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("deleted", 0);
            queryWrapper2.eq("term",term);
            queryWrapper2.eq("subject_name", list.get(i).getName());
            List<SmartSubjectRule> list2 = smartSubjectRuleService.getSmartSubjectRuleByKey(queryWrapper2);
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("subjectName",list.get(i).getName());
            jsonObject2.put("term", term);
            jsonObject2.put("subjectRuleList",list2);
            lj.add(jsonObject2);
            jsonObject1.put("smartSubjectRuleInLists",lj);
        }
        return CommonResult.ok(jsonObject1);
    }

    @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);
    }

    @PassToken
    public CommonResult evaluateScore(JSONObject jsonObject){
        SmartEvaluateSdetailList smartEvaluateSdetailList = null;
        try {
            smartEvaluateSdetailList = JSONObject.parseObject(jsonObject.toString(), SmartEvaluateSdetailList.class);
        } catch (Exception e){
            return CommonResult.errorMsg("参数格式错误");
        }
        Integer id = smartEvaluateSdetailList.getId();
        List<SmartEvaluateSdetail> scoreList = smartEvaluateSdetailList.getScoreList();
        SmartEvaluateStudent student = smartEvaluateStudentService.getSmartEvaluateStudentById(id);
        double total = 0;
        for (int i = 0; i < scoreList.size(); i++) {
            SmartEvaluateSdetail smartEvaluateSdetail = scoreList.get(i);
            if (smartEvaluateSdetail.getId()==null){
                smartEvaluateSdetail.setId((int) UUIDUtil.generateID());
            }
            if (smartEvaluateSdetail.getDeleted()==0){
                total+=smartEvaluateSdetail.getScoreNum();
            }
            smartEvaluateSdetail.setTerm(student.getTerm());
            smartEvaluateSdetail.setCardNo(student.getCardNo());
            QueryWrapper<SmartSubjectRule> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("deleted", 0);
            queryWrapper1.eq("subject_name", smartEvaluateSdetail.getSubjectName());
            List<SmartSubjectRule> rule = smartSubjectRuleService.getSmartSubjectRuleByKey(queryWrapper1);
            String scoreLevel = "";
            for (int j = 0; j < rule.size(); j++) {
                String[] range = rule.get(j).getScoreRange().split("-");
                double min = Double.parseDouble(range[0]);
                double max = Double.parseDouble(range[1]);
                if (smartEvaluateSdetail.getScoreNum()>=min && smartEvaluateSdetail.getScoreNum()<=max){
                    scoreLevel = rule.get(i).getLevel();
                    break;
                }
            }
            smartEvaluateSdetail.setScoreLevel(scoreLevel);
            SmartEvaluateSdetail listc = smartEvaluateSdetailService.getSmartEvaluateSdetailById(smartEvaluateSdetail.getId());
            if (listc==null){
                smartEvaluateSdetailService.insertSmartEvaluateSdetail(smartEvaluateSdetail);
            } else {
                smartEvaluateSdetailService.updateSmartEvaluateSdetail(smartEvaluateSdetail);
            }
        }
        student.setScoreComment(smartEvaluateSdetailList.getScoreComment());
        student.setScoreNum(total);
        String scoreLevel = "";
        QueryWrapper<SmartSubjectRule> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("deleted", 0);
        queryWrapper2.eq("subject_name", "平均成绩");
        List<SmartSubjectRule> rule = smartSubjectRuleService.getSmartSubjectRuleByKey(queryWrapper2);
        for (int i = 0; i < rule.size(); i++) {
            String[] range = rule.get(i).getScoreRange().split("-");
            double min = Double.parseDouble(range[0]);
            double max = Double.parseDouble(range[1]);
            if (total>=min && total<=max){
                scoreLevel = rule.get(i).getLevel();
                break;
            }
        }
        student.setScoreLevel(scoreLevel);
        smartEvaluateStudentService.updateSmartEvaluateStudent(student);
        return CommonResult.ok();
    }
}
