package com.xjrsoft.module.xycxedu.util;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.module.base.entity.BaseCourseSubject;
import com.xjrsoft.module.base.service.IBaseCourseSubjectService;
import com.xjrsoft.module.xycxedu.entity.ExamSubjectScore;
import com.xjrsoft.module.xycxedu.entity.XycxeduExamList;
import com.xjrsoft.module.xycxedu.service.IExamSubjectScoreService;
import com.xjrsoft.module.xycxedu.service.IXycxeduExamListService;
import com.yomahub.liteflow.util.JsonUtil;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dzx
 * @date 2024/7/17
 */
public class DataUtil {

    /**
     * 同步考试计划信息
     * @param examListService
     */
    public void examListData(IXycxeduExamListService examListService){
        JsonArray examList = ApiUtil.getExamList();
        List<XycxeduExamList> updateList = new ArrayList<>();
        List<XycxeduExamList> insertList = new ArrayList<>();
        Date date = new Date();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (JsonElement jsonElement : examList) {
            XycxeduExamList parseObject = new XycxeduExamList();
            JsonObject object = jsonElement.getAsJsonObject();
            parseObject.setMilexamname(object.get("milexamname").getAsString());
            parseObject.setMilexamid(object.get("milexamid").getAsLong());
            parseObject.setRegyear(object.get("regyear").getAsInt());
            parseObject.setGrade(object.get("grade").getAsString());
            parseObject.setSdate(LocalDate.parse(object.get("sdate").getAsString(), formatter));
            XycxeduExamList oldData = examListService.getOne(
                    new QueryWrapper<XycxeduExamList>().lambda()
                            .eq(XycxeduExamList::getMilexamid, parseObject.getMilexamid())
            );
            if(oldData != null){
                BeanUtil.copyProperties(parseObject, oldData);
                oldData.setModifyDate(date);
                updateList.add(oldData);
                continue;
            }

            parseObject.setCreateDate(date);
            insertList.add(parseObject);
        }
        if(!updateList.isEmpty()){
            examListService.updateBatchById(updateList);
        }
        if(!insertList.isEmpty()){
            examListService.saveBatch(insertList);
        }
    }

    public void studentScoreData(IXycxeduExamListService examListService, IExamSubjectScoreService scoreService, IBaseCourseSubjectService courseService){
        //  查询出所有的考试计划
        List<XycxeduExamList> list = examListService.list(
                new QueryWrapper<XycxeduExamList>().lambda()
        );
        Map<Integer, Integer> examidXMilexamidMap = new HashMap<>();//存考试下的科目id和考试id关系
        Map<Integer, String> examidXCoursenameMap = new HashMap<>();
        for (XycxeduExamList el : list) {
            // 根据考试计划，查询出所有科目信息
            JsonArray courseByExam = ApiUtil.getCourseByExam(el.getMilexamid());
            for (JsonElement jsonElement : courseByExam) {
                JsonObject courseObj = jsonElement.getAsJsonObject();
                examidXMilexamidMap.put(courseObj.get("examid").getAsInt(), courseObj.get("milexamid").getAsInt());
                examidXCoursenameMap.put(courseObj.get("examid").getAsInt(), courseObj.get("coursename").getAsString());
            }
        }
        Map<String, Long> courseMap = courseService.list(
                new QueryWrapper<BaseCourseSubject>().lambda().eq(BaseCourseSubject::getDeleteMark, DeleteMark.NODELETE.getCode())
        ).stream().collect(
                Collectors.toMap(BaseCourseSubject::getName, BaseCourseSubject::getId)
        );

        Date date = new Date();
        // 查询每次考试每个科目的学生的成绩
        for (Integer examid : examidXMilexamidMap.keySet()) {
            List<ExamSubjectScore> insertList = new ArrayList<>();
            JsonArray jsonArray = ApiUtil.getStudentScoreByCourse(examid);
            for (JsonElement jsonElement : jsonArray) {
                JsonObject scoreObj = jsonElement.getAsJsonObject();
                Long userId = scoreService.getUserIdByIdNumber(scoreObj.get("stunum").getAsString());

                long count = scoreService.count(
                        new QueryWrapper<ExamSubjectScore>().lambda()
                                .eq(ExamSubjectScore::getUserId, userId)
                                .eq(ExamSubjectScore::getCourseSubjectId, courseMap.get(examidXCoursenameMap.get(examid)))
                                .eq(ExamSubjectScore::getMilexamid, examidXMilexamidMap.get(examid).longValue())
                );
                if(count > 0){
                    continue;
                }
                ExamSubjectScore score = new ExamSubjectScore() {{
                    setUserId(userId);
                    setScore(scoreObj.get("score").getAsInt());
                    setMilexamid(examidXMilexamidMap.get(examid).longValue());
                    setGradeRanking(scoreObj.get("gradeorder").getAsInt());
                    setCoursename(examidXCoursenameMap.get(examid));
                    setCourseSubjectId(courseMap.get(examidXCoursenameMap.get(examid)));
                    setCreateDate(date);
                }};
                insertList.add(score);
            }
            if(!insertList.isEmpty()){
                scoreService.saveBatch(insertList);
            }
        }
    }
}
