package com.xhkjedu.sstudy.utils;

import com.xhkjedu.constant.PlatformConstant;
import com.xhkjedu.sstudy.config.ConfigKey;
import com.xhkjedu.sstudy.mapper.paper.PaperAnalyzeMapper;
import com.xhkjedu.sstudy.model.paperstudent.TPaperStudent;
import com.xhkjedu.vo.paper.PaperClassVo;
import com.xhkjedu.vo.paper.PaperListVo;
import com.xhkjedu.sstudy.vo.paperstudent.PaperStudentQuestionVo;
import com.xhkjedu.sstudy.vo.paperstudent.StudentPaperTypeVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.xhkjedu.utils.N_Utils.getSecondTimestamp;

/**
 * @ClassName StudyUtil
 * Description study模块用到的工具类
 * Author WN
 * Date 2022/2/21 10:01
 **/
@Slf4j
public class StudyUtil {
    public static Integer id = 0;
    public static Map<String, String> uriMap = new ConcurrentHashMap<>();
    //学生作业提交状态（1已提交2超时提交4自动收卷）
    public static List<Integer> tjlist = Arrays.asList(1, 2, 4);
    //学生作业未提交状态（0未提交3退回）
    public static List<Integer> wtjlist = Arrays.asList(0, 3);
    //视频类型
    public static List<String> videoList =Arrays.asList("mp4","flv");

    //获取id
    public static synchronized String getId(){
        Integer nummin = ConfigKey.nummin;
        Integer nummax = ConfigKey.nummax;
        if (id == 0 || id.equals(nummax)) {
            id = nummin;
        } else {
            id ++;
        }
        String _num = (getSecondTimestamp() + ConfigKey.numadd) +"" + id;
        long num = Long.parseLong(_num);
        return Long.toString(num,36).toUpperCase();
    }

    /**
     * 发送form-data请求返回json结果
     * @Param [apiUrl, param]
     * @Author ywx
     * @Date 2021/5/14 17:41
     * @return java.lang.String
     **/
    public static String sendFormData(String apiUrl, MultiValueMap<String, String> param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            List<MediaType> acceptableMediaTypes = new ArrayList<>();
            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(param, headers);
            ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
            String result = response.getBody();
            return result;
        } catch (RestClientException e) {
            log.error("发送form-data请求失败",e.getMessage());
            return null;
        }
    }

    //处理母子题
    public static List<StudentPaperTypeVo> setPaperQuestion(List<StudentPaperTypeVo> types, PaperAnalyzeMapper paperAnalyzeMapper){
        List<PaperStudentQuestionVo> qlist = new ArrayList<>();
        types.forEach(t -> {
            qlist.addAll(t.getQuestions());
        });
        List<String> questionpids = qlist.stream().filter(q -> q.getQlevel() == 3)
                .map(q -> q.getQuestionpid()).distinct().collect(Collectors.toList());
        List<PaperStudentQuestionVo> mquestions = new ArrayList<>();
        if (N_Utils.isListNotEmpty(questionpids)) {
            mquestions = paperAnalyzeMapper.listQuestionByQuestionIds(questionpids);
        }
        for (StudentPaperTypeVo t : types) {
            List<PaperStudentQuestionVo> questionList = new ArrayList<>();
            List<PaperStudentQuestionVo> questions = t.getQuestions();
            LinkedHashMap<String, List<PaperStudentQuestionVo>> collect = questions.stream()
                    .collect(Collectors.groupingBy(q -> q.getQuestionpid(), LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<String, List<PaperStudentQuestionVo>> entry : collect.entrySet()) {
                String questionpid = entry.getKey();
                List<PaperStudentQuestionVo> list = entry.getValue();
                PaperStudentQuestionVo tq = list.get(0);
                PaperStudentQuestionVo q;
                if(tq.getQlevel()==3){//子题
                    q = mquestions.stream().filter(mq -> mq.getQuestionid().equals(questionpid)).findFirst().orElse(null);
                    double score = list.stream().mapToDouble(PaperStudentQuestionVo::getQscore).sum();
                    List<PaperStudentQuestionVo> sonques = list.stream().filter(l -> l.getQuestionpid().equals(questionpid)).collect(Collectors.toList());
                    q.setQscore(score);
                    q.setQorder(tq.getQorder());
                    q.setSonques(sonques);
                    q.setStuscore(sonques.stream().mapToDouble(sq->sq.getStuscore()).sum());
                    Integer good = 0;
                    long count = sonques.stream().filter(s -> s.getGood().equals(1)).count();
                    if (count != 0) {
                        good = 1;
                    }
                    q.setGood(good);
                }else {
                    q=tq;
                }
                questionList.add(q);
            }
            t.setQuestions(questionList);
        }
        return types;
    }

    //处理母子题（无答案）
    public static List<StudentPaperTypeVo> setPaperQuestionNoAnswer(List<StudentPaperTypeVo> types, PaperAnalyzeMapper paperAnalyzeMapper){
        List<PaperStudentQuestionVo> qlist = new ArrayList<>();
        types.forEach(t -> {
            qlist.addAll(t.getQuestions());
        });
        List<String> questionpids = qlist.stream().filter(q -> q.getQlevel() == 3)
                                         .map(q -> q.getQuestionpid()).distinct().collect(Collectors.toList());
        List<PaperStudentQuestionVo> mquestions = new ArrayList<>();
        if (N_Utils.isListNotEmpty(questionpids)) {
            mquestions = paperAnalyzeMapper.listQuestionNoPointByQuestionIds(questionpids);
        }
        for (StudentPaperTypeVo t : types) {
            List<PaperStudentQuestionVo> questionList = new ArrayList<>();
            List<PaperStudentQuestionVo> questions = t.getQuestions();
            LinkedHashMap<String, List<PaperStudentQuestionVo>> collect = questions.stream()
                   .collect(Collectors.groupingBy(q -> q.getQuestionpid(), LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<String, List<PaperStudentQuestionVo>> entry : collect.entrySet()) {
                String questionpid = entry.getKey();
                List<PaperStudentQuestionVo> list = entry.getValue();
                PaperStudentQuestionVo tq = list.get(0);
                PaperStudentQuestionVo q;
                if(tq.getQlevel()==3){//子题
                    q = mquestions.stream().filter(mq -> mq.getQuestionid().equals(questionpid)).findFirst().orElse(null);
                    double score = list.stream().mapToDouble(PaperStudentQuestionVo::getQscore).sum();
                    List<PaperStudentQuestionVo> sonques = list.stream().filter(l -> l.getQuestionpid().equals(questionpid)).collect(Collectors.toList());
                    q.setQscore(score);
                    q.setQorder(tq.getQorder());
                    q.setSonques(sonques);
                }else {
                    q=tq;
                }
                questionList.add(q);
            }
            t.setQuestions(questionList);
        }
        return types;
    }

    /**
     * @Description 得分率分组：1优秀率≥85% 2良好率≥70% 3合格率≥60% 4其他40%~60% 5低分率≤40%
     * @Param [scorerate]
     * @Return java.lang.Integer
     * @Author wn
     * @Date 2022/10/8 9:33
     **/
    public static Integer getScoreRateType(Double scorerate) {
        Integer ratetype = 0;
        if (scorerate != null) {
            if (scorerate >= 85) {
                ratetype = 1;
            } else if (scorerate >= 70) {
                ratetype = 2;
            } else if (scorerate >= 60) {
                ratetype = 3;
            } else if (scorerate < 60 && scorerate > 40) {
                ratetype = 4;
            } else if (scorerate <= 40) {
                ratetype = 5;
            }
        }
        return ratetype;
    }

    /**
     * @Description obj转double
     * @Param [obj]
     * @Author ywx
     * @Date 2023/4/27 14:41
     * @return java.lang.Double
     **/
    public static Double objToDouble(Object obj) {
        if (obj == null) return 0.0;
        return Double.valueOf(obj.toString());
    }

    /**
     * 作业列表
     * @Param [list]
     * @Author ywx
     * @Date 2020/6/18 15:09
     * @return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    public static List<PaperListVo> getPaperListVo(List<PaperListVo> list) {
        for (PaperListVo p : list) {
            if (p.getPaperstate() == 21){//未布置
                p.setClasses(null);
                p.setChecklist(null);
            } else {
                List<Map> schools = p.getSchools();
                List<PaperClassVo> classes = new ArrayList<>();
                for (Map school : schools) {
                    List<PaperClassVo> classList = (List<PaperClassVo>) school.get("classes");
                    classes.addAll(classList);
                    for (PaperClassVo c : classList) {
                        if (!N_Utils.isEmptyInteger(c.getClassnum())) {
                            c.setWtjnum(c.getClassnum() - c.getYtjnum());
                        }
                    }
                }
                p.setClassnum(classes.stream().mapToInt(c -> c.getClassnum()).sum());
                p.setYtjnum(classes.stream().mapToInt(c -> c.getYtjnum()).sum());
                p.setYpgnum(classes.stream().mapToInt(c -> c.getYpgnum()).sum());

                /*if(p.getChecktype() == 3){
                    List<Map> rtnList = new ArrayList<>();
                    //指定学生批阅
                    List<Map> checklist = p.getChecklist();
                    //按照班级分组
                    Map<Integer,List<Map>> classMap = checklist.stream().collect(Collectors.groupingBy(s -> Integer.parseInt(s.get("classid").toString())));
                    for(Map.Entry<Integer,List<Map>> entry : classMap.entrySet()){
                        List<Map> stuList = entry.getValue();
                        Map stuMap = stuList.get(0);
                        Map map = new LinkedHashMap();
                        map.put("classid",entry.getKey());
                        map.put("classname",stuMap.get("classname").toString());
                        map.put("gradeid",stuMap.get("gradeid").toString());
                        map.put("stulist",stuList);
                        rtnList.add(map);
                    }
                    p.setChecklist(rtnList);
                }*/
            }
        }
        return list;
    }

    /**
     * @Description 教师权限班级
     * @Param [classlist]
     * @Author ywx
     * @Date 2023/7/31 14:03
     * @return java.util.Map
     **/
    public static Map setQxClass(List<Map> classlist) {
        //所有权限班级集合
        List<Integer> classidlist = classlist.stream().map(s -> Integer.parseInt(s.get("classid").toString())).collect(Collectors.toList());
        //本校班级集合
        List<Integer> bxclassidlist = classlist.stream().filter(c -> c.get("schoolid").equals(c.get("userschoolid")))
                                               .map(s -> Integer.parseInt(s.get("classid").toString())).collect(Collectors.toList());

        String classids = StringUtils.join(classidlist, ",");
        String bxclassids = StringUtils.join(bxclassidlist,",");
        if(N_Utils.isEmpty(classids)) classids = "0";
        if(N_Utils.isEmpty(bxclassids)) bxclassids = "0";

        Map rtnmap = new HashMap();
        rtnmap.put("classids",classids);
        rtnmap.put("bxclassids",bxclassids);
        return rtnmap;
    }

    //校验学生作业提交状态
    public static ResultVo checkPsState(TPaperStudent ps) {
        //如果学生作业不存在或是已提交，直接返回提交成功
        if (ps == null) return PlatformConstant.COMMIT_SUCCESS;
        Integer psstate = ps.getPsstate();
        if (psstate.equals(4)) return PlatformConstant.AFTER_COMMIT;
        if (tjlist.contains(psstate)) return PlatformConstant.COMMIT_SUCCESS;
        return null;
    }
}
