package com.ruoyi.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.aliyun.teautil.Common;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.enums.PaperType;
import com.ruoyi.learn.domain.LearnStudent;
import com.ruoyi.learn.mapper.LearnAnswerMapper;
import com.ruoyi.learn.mapper.LearnExamineeMapper;
import com.ruoyi.learn.service.ILearnStudentService;
import com.ruoyi.mingxue.mapper.CustomerVideoWatchesMapper;
import com.ruoyi.web.domain.TestRecordCond;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class LearnStatService {
    private final CustomerVideoWatchesMapper customerVideoWatchesMapper;
    private final LearnAnswerMapper answerMapper;
    private final LearnExamineeMapper examineeMapper;
    private final ILearnStudentService learnStudentService;
    private final LearnTeacherService learnTeacherService;

    public LearnStatService(CustomerVideoWatchesMapper customerVideoWatchesMapper, LearnAnswerMapper answerMapper, LearnTeacherService learnTeacherService, LearnExamineeMapper examineeMapper, ILearnStudentService learnStudentService, LearnTeacherService learnTeacherService1) {
        this.customerVideoWatchesMapper = customerVideoWatchesMapper;
        this.answerMapper = answerMapper;
        this.examineeMapper = examineeMapper;
        this.learnStudentService = learnStudentService;
        this.learnTeacherService = learnTeacherService1;
    }
    public List<JSONObject> selectStudentPractices(Long studentId, PaperType paperType, Integer questionType) {
        return examineeMapper.selectStudentPractices(studentId, paperType.getVal(), questionType);
    }


    public List<JSONObject> getTestRecord(TestRecordCond cond) {
        JSONObject stats = examineeMapper.selectTestStats(cond.toMap());
        List<JSONObject> dataList = Lists.newArrayList();
        dataList.add(JSONObject.of("buildStatus", null, "count", stats.getInteger("total")));
        dataList.add(JSONObject.of("buildStatus", 10, "count", stats.getInteger("undirect")));
        dataList.add(JSONObject.of("buildStatus", 20, "count", stats.getInteger("unsend")));
        dataList.add(JSONObject.of("buildStatus", 30, "count", stats.getInteger("undone")));
        dataList.add(JSONObject.of("buildStatus", 40, "count", stats.getInteger("done")));
        return dataList;
    }

    public List<JSONObject> getTestStudentRecord(TestRecordCond cond) {
        return examineeMapper.selectTestStudents(cond.toMap());
    }

    public List<JSONObject> getSimulatedClassRecord(Long teacherId) {
        return examineeMapper.selectSimulatedStats(teacherId);
    }

    public List<JSONObject> getSimulatedStudentRecord(Long classId) {
        return examineeMapper.selectSimulatedStudentStats(classId);
    }

    public List<JSONObject> getSimulatedSubjectRecord(Long studentId) {
        return examineeMapper.selectSimulatedStuSubjectStats(studentId);
    }

    public JSONObject getClassRecordKnowledge(Long classId) {
        JSONObject result = new JSONObject();
        Map cond = Dict.create().set("classId", classId);
        JSONObject header = answerMapper.selectClassKnowledgeHeader(cond);
        result.put("rate", null == header ? 0 : header.getIntValue("rate"));
        List<JSONObject> list = answerMapper.selectClassKnowledgeDetail(cond);
        AtomicInteger index = new AtomicInteger(1);
        list.forEach(s -> {
            CommonUtils.normalRate(s);
            s.put("seq", index.getAndAdd(1));
        });
        result.put("list", list);
        return result;
    }

    public List<JSONObject> getRecordKnowledge(Long studentId, Integer planYear) {
        LearnStudent learnStudent = learnStudentService.selectLearnStudentByStudentId(studentId);
        Set<Long> knowledgeIdSet = null != learnStudent ? learnTeacherService.getKnowledgeIdSet(null, learnStudent.getMajorPlanId(), planYear, learnStudent.getExamType()) : Sets.newHashSet(0L);
        knowledgeIdSet.add(0L);
        List<JSONObject> list = answerMapper.selectKnowledgeStats(Dict.create().set("studentId", studentId).set("knowIds", knowledgeIdSet));
        list.forEach(o -> {
            CommonUtils.normalRate(o);
            o.put("directed", "1".equals(o.getString("directed")));
        });
        return list;
    }

    public List<JSONObject> getClassRecordVideo(Long classId, Boolean asc) {
        Map cond = Dict.create().set("classId", classId).set("desc", null != asc && !asc);
        List<JSONObject> list = customerVideoWatchesMapper.selectClassStats(cond);
        AtomicInteger index = new AtomicInteger(1);
        list.forEach(t -> {
            t.put("seq", index.getAndAdd(1));
        });
        return list;
    }
    public JSONObject getRecordVideo(Long studentId) {
        Map cond = Dict.create().set("studentId", studentId);
        JSONObject header = customerVideoWatchesMapper.selectLearnStatsHeader(cond);
        JSONObject result = new JSONObject();
        result.put("total", header.getIntValue("total"));
        result.put("study", header.getIntValue("value"));
        List<JSONObject> list = Lists.newArrayList();
        customerVideoWatchesMapper.selectLearnStatsDetail(cond).stream().forEach(s -> {
            JSONObject data = JSONObject.of("name", s.getString("name"), "date", DateUtils.format(s.getDate("time"), "yyyy-MM-dd"), "study", s.getString("value"));
            list.add(data);
        });
        result.put("list", list);
        return result;
    }

    public List<JSONObject> getClassRecordPlanStudy(Long classId, String sortField, Boolean asc) {
        Map cond = Dict.create().set("classId", classId).set("sortField", sortField).set("desc", null != asc && !asc);
        List<JSONObject> list = answerMapper.selectClassQuestionStats(cond);
        AtomicInteger index = new AtomicInteger(1);
        list.forEach(t -> {
            CommonUtils.normalRate(t);
            t.put("seq", index.getAndAdd(1));
        });
        return list;

    }
    public JSONObject getRecordPlanStudy(Long studentId, Integer year, Long month) {
        Date beginDate, endDate;
        Calendar cal  = Calendar.getInstance();
        if(NumberUtils.isPositive(month)) {
            cal.set(year, month.intValue() - 1, 1);
            beginDate = DateUtil.beginOfDay(cal.getTime());
            cal.add(Calendar.MONTH, 1);
            endDate = DateUtil.beginOfDay(cal.getTime());
        } else {
            cal.set(year, 0, 1);
            beginDate = DateUtil.beginOfDay(cal.getTime());
            cal.add(Calendar.YEAR, 1);
            endDate = DateUtil.beginOfDay(cal.getTime());
        }

        Map cond = Dict.create().set("studentId", studentId).set("beginDate", beginDate).set("endDate", endDate);
        JSONObject header = answerMapper.selectQuestionStatsHeader(cond);
        JSONObject result = new JSONObject();
        result.put("total", header.getIntValue("total"));
        result.put("rate", header.getIntValue("rate"));
        result.put("studyDays", header.getIntValue("time"));
        if(null == month || month.equals(0L)) {
            return result;
        }
        List<JSONObject> list = Lists.newArrayList();
        answerMapper.selectQuestionStatsDetail(cond).forEach(s -> {
            CommonUtils.normalRate(s);
            JSONObject data = JSONObject.of("date", DateUtils.format(s.getDate("time"), "yyyy-MM-dd"), "study", s.getString("total"), "rate", s.getString("rate"));
            list.add(data);
        });
        result.put("list", list);
        return result;


    }
}
