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.SmartEvaluateStudentControllerAPI;
import com.template.common.jh.ReqRespResearchProductQuestionnaireItem;
import com.template.common.jh.SectionUtil;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.UUIDUtil;
import com.template.common.utils.paramUtils;
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.model.vo.HistoricalEvaluationVo;
import com.template.model.vo.TemplateRuleVo;
import com.template.services.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

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

    private static Logger logger = LoggerFactory.getLogger(SmartEvaluateStudentController.class);

    @Autowired
    private SmartSubjectManageService smartSubjectManageService;
    @Autowired
    private SmartSubjectRuleService smartSubjectRuleService;
    @Autowired
    private SmartEvaluateStudentService smartEvaluateStudentService;
    @Autowired
    private SmartEvaluateSdetailService smartEvaluateSdetailService;
    @Autowired
    private SmartTemplateRuleService smartTemplateRuleService;

    @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();
        logger.info("===" + 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("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("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("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("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<>();
        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.eq("term_id", 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);
        if (list.getList() != null && list.getList().size() > 0) {
            List<Integer> gradeIds = list.getList().stream().map(SmartEvaluateStudent::getGradeId).distinct().collect(Collectors.toList());
            List<Integer> termIds = list.getList().stream().map(SmartEvaluateStudent::getTermId).distinct().collect(Collectors.toList());
            List<TemplateRuleVo> templateRules = smartTemplateRuleService.queryTemplateRuleByIds(gradeIds, termIds);
            for (SmartEvaluateStudent student : list.getList()) {
                List<TemplateRuleVo> ownerRules = templateRules.stream().filter(e -> e.getGradeId().equals(student.getGradeId())
                        && e.getTermId().equals(student.getTermId())).collect(Collectors.toList());
                if (ownerRules != null && ownerRules.size() > 0) {
                    for (TemplateRuleVo ownerRule : ownerRules) {
                        Integer minValue = 0;
                        Integer maxValue = 0;
                        String[] levels = ownerRule.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();
                        }

                        Double scoreNum = (double) student.getScoreNum() / student.getSubjectNum();
                        if(scoreNum >= minValue && scoreNum <= maxValue){
                            student.setScoreLevel(ownerRule.getLevel());
                        }
                    }
                }
            }
        }

        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("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(j).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 / scoreList.size());
        String scoreLevel = "";
        QueryWrapper<SmartSubjectRule> queryWrapper2 = new QueryWrapper<>();
        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 (student.getScoreNum() >= min && student.getScoreNum() <= max) {
                scoreLevel = rule.get(i).getLevel();
                break;
            }
        }
        student.setScoreLevel(scoreLevel);
        smartEvaluateStudentService.updateSmartEvaluateStudent(student);
        return CommonResult.ok();
    }

    @PassToken
    public CommonResult queryDetailScore(Integer id) {
        if (id == null) {
            return CommonResult.fail("请传入id");
        }
        SmartEvaluateStudent smartEvaluateStudent = smartEvaluateStudentService.getSmartEvaluateStudentById(id);
        if (smartEvaluateStudent == null) {
            return CommonResult.fail("未查询到相关信息");
        }
        QueryWrapper<SmartEvaluateSdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("term", smartEvaluateStudent.getTerm());
        queryWrapper1.eq("card_no", smartEvaluateStudent.getCardNo());
        List<SmartEvaluateSdetail> list = smartEvaluateSdetailService.getSmartEvaluateSdetailByKey(queryWrapper1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", smartEvaluateStudent.getId());
        jsonObject.put("scoreComment", smartEvaluateStudent.getScoreComment());
        jsonObject.put("scoreList", list);
        return CommonResult.ok(jsonObject);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult historicalEvaluation(String cardNo) {
        List<HistoricalEvaluationVo> vos = smartEvaluateStudentService.getHistoricalEvaluation(cardNo);

//        获取评级
        for (int i = 0; i < vos.size(); i++) {
            HistoricalEvaluationVo vo = vos.get(i);
            String term = vo.getTerm();
            String scoreNum = vo.getScoreNum();
            QueryWrapper<SmartSubjectRule> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("subject_name", "平均成绩");
            queryWrapper1.eq("term", term);
            List<SmartSubjectRule> rule = smartSubjectRuleService.list(queryWrapper1);

            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]);
                Double num = Double.valueOf(scoreNum);
                if (num >= min && num <= max) {
                   String scoreLevel = rule.get(j).getLevel();
                   vo.setScoreLevel(scoreLevel);
                   break;
                }
            }

        }


        return CommonResult.ok(vos);
    }

    @Override
    public CommonResult getSEvaluationExcel(SmartEvaluateStudent smartEvaluateStudent, HttpServletResponse response, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        //导出
        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("测评等级");
        headerRow.createCell(6).setCellValue("教师寄语");

        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.eq("term_id", 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");
        List<SmartEvaluateStudent> list = smartEvaluateStudentService.queryPageSmartEvaluateStudent(queryWrapper1);
        if (list != null && list.size() > 0) {
            List<Integer> gradeIds = list.stream().map(SmartEvaluateStudent::getGradeId).distinct().collect(Collectors.toList());
            List<Integer> termIds = list.stream().map(SmartEvaluateStudent::getTermId).distinct().collect(Collectors.toList());
            List<TemplateRuleVo> templateRules = smartTemplateRuleService.queryTemplateRuleByIds(gradeIds, termIds);
            int i = 0;
            for (SmartEvaluateStudent student : list) {
                List<TemplateRuleVo> ownerRules = templateRules.stream().filter(e -> e.getGradeId().equals(student.getGradeId())
                        && e.getTermId().equals(student.getTermId())).collect(Collectors.toList());
                if (ownerRules != null && ownerRules.size() > 0) {
                    for (TemplateRuleVo ownerRule : ownerRules) {
                        Integer minValue = 0;
                        Integer maxValue = 0;
                        String[] levels = ownerRule.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();
                        }

                        Double scoreNum = (double) student.getScoreNum() / student.getSubjectNum();
                        if(scoreNum >= minValue && scoreNum <= maxValue){
                            student.setScoreLevel(ownerRule.getLevel());
                        }
                    }
                }

                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(i + 1);
                dataRow.createCell(1).setCellValue(student.getTerm());
                dataRow.createCell(2).setCellValue(student.getGradeName());
                dataRow.createCell(3).setCellValue(student.getClassName());
                dataRow.createCell(4).setCellValue(student.getName());
                dataRow.createCell(5).setCellValue(student.getScoreLevel());
                dataRow.createCell(6).setCellValue(student.getScoreComment());
                i++;
            }
        }

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "学生综评管理.xlsx", response);


        return CommonResult.ok("导出成功");
    }
}
