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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

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("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_id", smartSubjectTemplate.getGrade());
        queryWrapper1.eq("term_id", 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_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().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);
        List<SmartExamtype> examtypes = smartExamtypeService.list(null);
        if (list.getList() != null && list.getList().size() > 0) {
            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);
            }

        }
        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("该条记录已删除");
        }

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

}
