package com.template.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.template.annotation.PassToken;
import com.template.api.SmartEvaluateTeacherControllerAPI;
import com.template.common.utils.ExcelUtils;
import com.template.common.utils.UUIDUtil;
import com.template.model.evaluate.teacher.*;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.services.SmartEvaluateTdetailService;
import com.template.services.SmartEvaluateTeacherService;
import com.template.services.SmartScoreManageService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class SmartEvaluateTeacherController implements SmartEvaluateTeacherControllerAPI {

    @Autowired
    public SmartEvaluateTdetailService smartEvaluateTdetailService;
    @Autowired
    public SmartEvaluateTeacherService smartEvaluateTeacherService;
    @Autowired
    public SmartScoreManageService smartScoreManageService;

    @PassToken
    public CommonResult operateSmartScoreManage(JSONObject jsonObject) {
        SimpleScore simpleScoreLists = null;
        try {
            simpleScoreLists = JSONObject.parseObject(jsonObject.toString(), SimpleScore.class);
        } catch (Exception e){
            return CommonResult.errorMsg("参数格式错误");
        }
        List<SmartScoreManageList> allList = simpleScoreLists.getSimpleScoreList();
        List<String> mainScoreItems =allList.stream().filter(e->e.getDeleted()==0).map(m->m.getTerm()+m.getScoreItem()).collect(Collectors.toList());
        Set<String> mainScoreSet = new HashSet<>(mainScoreItems);
        if (mainScoreItems.size()!=mainScoreSet.size()){
            return CommonResult.fail("存在重复主项");
        }
        String term = allList.get(0).getTerm();
        QueryWrapper<SmartEvaluateTdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("term",term);
        List<SmartEvaluateTdetail> smartEvaluateTdetails = smartEvaluateTdetailService.getEvaluateTdetailByKey(queryWrapper1);
        if (smartEvaluateTdetails.size()>0){
            return CommonResult.fail("该学期已评分，不可再操作");
        }
        List<SmartScoreManage> smList = new ArrayList<>();
        for (int i = 0; i < allList.size(); i++) {
            SmartScoreManage mainScoreManage = new SmartScoreManage();
            double mainScoreNum = 0;
            if (allList.get(i).getId()==null){
                allList.get(i).setId((int) UUIDUtil.generateID());
            }
            mainScoreManage.setId(allList.get(i).getId());
            mainScoreManage.setTerm(term);
            mainScoreManage.setScoreItem(allList.get(i).getScoreItem());
            mainScoreManage.setParentId(allList.get(i).getParentId());
            mainScoreManage.setDeleted(allList.get(i).getDeleted());
            List<SmartScoreManageList> childList = allList.get(i).getSmartScoreManageList();
            List<String> scoreItems =childList.stream().filter(e->e.getDeleted()==0).map(m->term+m.getScoreItem()).collect(Collectors.toList());
            Set<String> ScoreSet = new HashSet<>(scoreItems);
            if (scoreItems.size()!=ScoreSet.size()){
                return CommonResult.fail("存在重复子项");
            }
            for (int j = 0; j < childList.size(); j++) {
                SmartScoreManage childScoreManage = new SmartScoreManage();
                if (childList.get(j).getId()==null){
                    childList.get(j).setId((int) UUIDUtil.generateID());
                }
                childScoreManage.setId(childList.get(j).getId());
                childScoreManage.setTerm(term);
                childScoreManage.setScoreItem(childList.get(j).getScoreItem());
                childScoreManage.setParentId(allList.get(i).getId());
                childScoreManage.setScoreNum(childList.get(j).getScoreNum());
                childScoreManage.setDeleted(childList.get(j).getDeleted());
                smList.add(childScoreManage);
                if (childList.get(j).getDeleted()==0){
                    mainScoreNum+=childList.get(j).getScoreNum();
                }
            }
            mainScoreManage.setScoreNum(mainScoreNum);
            smList.add(mainScoreManage);
        }
        for (int i = 0; i < smList.size(); i++) {
            // 相关判断
            SmartScoreManage scoreManage = smList.get(i);
            SmartScoreManage sc = smartScoreManageService.getSmartScoreManageById(scoreManage.getId());
            if (sc==null){
                smartScoreManageService.insertSmartScoreManage(scoreManage);
            } else {
                smartScoreManageService.updateSmartScoreManage(scoreManage);
            }
        }
        return CommonResult.ok("操作成功");
    }

    @PassToken
    public CommonResult getScoreManage(String term){
        if (term==null){
            term=smartScoreManageService.getMaxTerm();
        }
        SimpleScore simpleScore = smartScoreManageService.queryScoreDetail(term);
        return CommonResult.ok(simpleScore);
    }

    @PassToken
    public CommonResult getTeacherScoreList(SmartEvaluateTeacher smartEvaluateTeacher,Integer currentPage, Integer pageCount){
        QueryWrapper<SmartEvaluateTeacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        if (smartEvaluateTeacher.getName()!=null && !smartEvaluateTeacher.getName().trim().equals("")){
            queryWrapper.and(qw->qw.like("name", smartEvaluateTeacher.getName()).or().like("card_no", smartEvaluateTeacher.getName()));
        }
        if (smartEvaluateTeacher.getTerm()!=null && !smartEvaluateTeacher.getTerm().trim().equals("")){
            queryWrapper.like("term", smartEvaluateTeacher.getTerm());
        }
        if (smartEvaluateTeacher.getSubject()!=null && !smartEvaluateTeacher.getSubject().trim().equals("")){
            queryWrapper.eq("subject", smartEvaluateTeacher.getSubject());
        }
        if (smartEvaluateTeacher.getClassName()!=null && !smartEvaluateTeacher.getClassName().trim().equals("")){
            queryWrapper.eq("class_name", smartEvaluateTeacher.getClassName());
        }
        queryWrapper.orderByDesc("id");
        PageUtils<SmartEvaluateTeacher> list = smartEvaluateTeacherService.queryPageSmartEvaluateTeacher(currentPage,pageCount,queryWrapper);
        return CommonResult.ok(list);
    }

    @PassToken
    public void getTeacherScoreExcel(SmartEvaluateTeacher smartEvaluateTeacher, HttpServletResponse response){
        String term = smartScoreManageService.getMaxTerm();
        QueryWrapper<SmartEvaluateTeacher> queryWrapper = new QueryWrapper<>();
        if (smartEvaluateTeacher.getName()!=null && !smartEvaluateTeacher.getName().trim().equals("")){
            queryWrapper.and(qw->qw.like("name", smartEvaluateTeacher.getName()).or().like("card_no", smartEvaluateTeacher.getName()));
        }
        if (smartEvaluateTeacher.getTerm()!=null && !smartEvaluateTeacher.getTerm().trim().equals("")){
            queryWrapper.like("term", smartEvaluateTeacher.getTerm());
        } else {
            queryWrapper.like("term", term);
        }
        if (smartEvaluateTeacher.getSubject()!=null && !smartEvaluateTeacher.getSubject().trim().equals("")){
            queryWrapper.eq("subject", smartEvaluateTeacher.getSubject());
        }
        if (smartEvaluateTeacher.getClassName()!=null && !smartEvaluateTeacher.getClassName().trim().equals("")){
            queryWrapper.eq("class_name", smartEvaluateTeacher.getClassName());
        }
        List<SmartEvaluateTeacher> outlist = smartEvaluateTeacherService.getEvaluateTeacherByKey(queryWrapper);
        //导出
        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("班级");
        QueryWrapper<SmartScoreManage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("parent_id", 0);
        queryWrapper1.eq("term", term);
        List<SmartScoreManage> scoreManageList = smartScoreManageService.getScoreManageByKey(queryWrapper1);
        for (int i = 0; i < scoreManageList.size(); i++) {
            headerRow.createCell(i+6).setCellValue(scoreManageList.get(i).getScoreItem());
        }
        headerRow.createCell(scoreManageList.size()+6).setCellValue("总分");
        for (int i = 0; i < outlist.size(); i++) {
            SmartEvaluateTeacher teacherScore = outlist.get(i);

            Row dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(i + 1);
            dataRow.createCell(1).setCellValue(teacherScore.getCardNo());
            dataRow.createCell(2).setCellValue(teacherScore.getName());
            dataRow.createCell(3).setCellValue(teacherScore.getTerm());
            dataRow.createCell(4).setCellValue(teacherScore.getSubject());
            dataRow.createCell(5).setCellValue(teacherScore.getClassName());
            // 分数详情
            JSONObject scoreDetail = JSON.parseObject(teacherScore.getEvaluateDetail());
            for (int j = 0; j < scoreManageList.size(); j++) {
                for (Map.Entry entry : scoreDetail.entrySet()) {
                    if (scoreManageList.get(j).getScoreItem().equals(entry.getKey())) {
                        dataRow.createCell(j+6).setCellValue(entry.getValue().toString());
                    }
                }
            }
        }
        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "教师评测信息.xlsx", response);
    }

    @PassToken
    public CommonResult evaluateScore(JSONObject jsonObject){
        SimpleEvaluateScore simpleEvaluateScore = null;
        try {
            simpleEvaluateScore = JSONObject.parseObject(jsonObject.toString(), SimpleEvaluateScore.class);
        } catch (Exception e){
            return CommonResult.errorMsg("参数格式错误");
        }
        SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(simpleEvaluateScore.getId());
        teacher.setLowingScore(simpleEvaluateScore.getLowingScore());
        teacher.setTotalScore(simpleEvaluateScore.getTotalScore());
        JSONObject desScore = new JSONObject();
        List<SmartEvaluateTdetailList> mainList = simpleEvaluateScore.getSimpleScoreList();
        List<SmartEvaluateTdetail> lse = new ArrayList<>();
        for (int i = 0; i < mainList.size(); i++) {
            if (mainList.get(i).getDeleted()==0){
                desScore.put(mainList.get(i).getScoreItem(), mainList.get(i).getOwnNum());
            }
            SmartEvaluateTdetail mainLse = new SmartEvaluateTdetail();
            mainLse.setId(mainList.get(i).getId()==null? (int) UUIDUtil.generateID() :mainList.get(i).getId());
            mainLse.setCardNo(teacher.getCardNo());
            mainLse.setTerm(teacher.getTerm());
            mainLse.setScoreItem(mainList.get(i).getScoreItem());
            mainLse.setParentId(mainList.get(i).getParentId());
            mainLse.setScoreNum(mainList.get(i).getScoreNum());
            mainLse.setOwnNum(mainList.get(i).getOwnNum());
            mainLse.setDeleted(mainList.get(i).getDeleted());
            lse.add(mainLse);
            List<SmartEvaluateTdetailList> childScoreList = mainList.get(i).getEvaluateList();
            for (int j = 0; j < childScoreList.size(); j++) {
                SmartEvaluateTdetailList childScore = childScoreList.get(j);
                SmartEvaluateTdetail childLse = new SmartEvaluateTdetail();
                childLse.setId(childScore.getId()==null? (int) UUIDUtil.generateID() :childScore.getId());
                childLse.setCardNo(teacher.getCardNo());
                childLse.setTerm(teacher.getTerm());
                childLse.setScoreItem(childScore.getScoreItem());
                childLse.setParentId(mainLse.getId());
                childLse.setScoreNum(childScore.getScoreNum());
                childLse.setOwnNum(childScore.getOwnNum());
                childLse.setDeleted(childScore.getDeleted());
                lse.add(childLse);
            }
        }
        for (int i = 0; i < lse.size(); i++) {
            SmartEvaluateTdetail scoreDetail = lse.get(i);
            SmartEvaluateTdetail listc = smartEvaluateTdetailService.getSmartEvaluateTdetailById(scoreDetail.getId());
            if (listc==null){
                smartEvaluateTdetailService.insertSmartEvaluateTdetail(scoreDetail);
            } else {
                smartEvaluateTdetailService.updateSmartEvaluateTdetail(scoreDetail);
            }
        }
        teacher.setTotalScore(simpleEvaluateScore.getTotalScore());
        teacher.setLowingScore(simpleEvaluateScore.getLowingScore());
        teacher.setEvaluateDetail(desScore.toString());
        smartEvaluateTeacherService.updateSmartEvaluateTeacher(teacher);
        return CommonResult.ok();
    }

    @PassToken
    public CommonResult getTeacherScoreDetail(Integer id){
        SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(id);
        if (teacher==null){
            return CommonResult.fail("该条记录已删除");
        }
        if (teacher.getEvaluateDetail()==null){
            SimpleScoreDetailList simpleScoreDetailList = smartScoreManageService.queryNoTeacherScoreDetail(teacher.getTerm());
            JSONObject resultJson = new JSONObject();
            resultJson.put("id", teacher.getId());
            resultJson.put("totalScore", 0);
            resultJson.put("lowingScore", 0);
            resultJson.put("simpleScoreList",simpleScoreDetailList);
            return CommonResult.ok(resultJson);
        }
        QueryWrapper<SmartScoreManage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("parent_id", 0);
        queryWrapper1.eq("term", teacher.getTerm());
        List<SmartScoreManage> scoreManageList = smartScoreManageService.getScoreManageByKey(queryWrapper1);
        int totalScore = 0;
        for (int i = 0; i < scoreManageList.size(); i++) {
            totalScore+=scoreManageList.get(i).getScoreNum();
        }
        QueryWrapper<SmartEvaluateTdetail> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("deleted", 0);
        queryWrapper2.eq("parent_id", 0);
        queryWrapper2.eq("term", teacher.getTerm());
        List<SmartEvaluateTdetail> scoreDetailList = smartEvaluateTdetailService.getEvaluateTdetailByKey(queryWrapper2);
        int ownTotalScore = 0;
        int lowingScore = 0;
        for (int i = 0; i < scoreDetailList.size(); i++) {
            ownTotalScore+=scoreDetailList.get(i).getOwnNum();
        }
        lowingScore=totalScore-ownTotalScore;
        SimpleScoreDetailList simpleScoreDetailList = smartScoreManageService.queryTeacherScoreDetail(teacher.getTerm(),teacher.getCardNo());
        JSONObject resultJson = new JSONObject();
        resultJson.put("id", teacher.getId());
        resultJson.put("totalScore", ownTotalScore);
        resultJson.put("lowingScore", lowingScore);
        resultJson.put("simpleScoreList",simpleScoreDetailList);
        return CommonResult.ok(resultJson);
    }

    @PassToken
    public CommonResult getScoreComparison(Integer id){
        SmartEvaluateTeacher teacher = smartEvaluateTeacherService.getSmartEvaluateTeacherById(id);
        QueryWrapper<SmartEvaluateTdetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("parent_id", 0);
        queryWrapper1.eq("term", teacher.getTerm());
        queryWrapper1.eq("card_no",teacher.getCardNo());
        List<SmartEvaluateTdetail> detailList = smartEvaluateTdetailService.getEvaluateTdetailByKey(queryWrapper1);
        List<JSONObject> resultJson = new ArrayList<>();
        for (int i = 0; i < detailList.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            SmartEvaluateTdetail smartEvaluateTdetail = detailList.get(i);
            double avgScore = smartEvaluateTdetailService.getAvgEvaluateScore(teacher.getTerm(),smartEvaluateTdetail.getScoreItem());
            jsonObject.put("name", smartEvaluateTdetail.getScoreItem());
            jsonObject.put("ownScore", smartEvaluateTdetail.getOwnNum());
            jsonObject.put("avgScore", avgScore);
            resultJson.add(jsonObject);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "扣");
        jsonObject.put("ownScore",teacher.getLowingScore());
        jsonObject.put("avgScore", smartEvaluateTeacherService.getAvgLowingScore(teacher.getTerm()));
        resultJson.add(jsonObject);
        return CommonResult.ok(resultJson);
    }

    @PassToken
    public CommonResult getScoreRank(int currentPage, int pageCount,String subject){
        QueryWrapper<SmartEvaluateTeacher> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("term", smartScoreManageService.getMaxTerm());
        queryWrapper1.eq("deleted", 0);
        if (subject!=null){
            queryWrapper1.eq("subject", subject);
        }
        queryWrapper1.orderByDesc("total_score");
        PageUtils<SmartEvaluateTeacher> list = smartEvaluateTeacherService.queryPageSmartEvaluateTeacher(currentPage,pageCount,queryWrapper1);
        return CommonResult.ok(list);
    }
}
