package com.xhkjedu.sstudy.service.recite;

import com.xhkjedu.sstudy.mapper.recite.ReciteGroupMapper;
import com.xhkjedu.sstudy.mapper.recite.ReciteMapper;
import com.xhkjedu.sstudy.mapper.recite.ReciteStudentMapper;
import com.xhkjedu.sstudy.mapper.system.UserMapper;
import com.xhkjedu.sstudy.model.recite.TRecite;
import com.xhkjedu.sstudy.model.recite.TReciteGroup;
import com.xhkjedu.sstudy.model.recite.TReciteStudent;
import com.xhkjedu.sstudy.service.gradeclass.ClassService;
import com.xhkjedu.sstudy.vo.recite.ReciteStudentVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ReciteStudentService
 * Description TODO
 * Author WN
 * Date 2020/6/10 14:38
 **/
@Service
public class ReciteStudentService {
    @Resource
    private ReciteStudentMapper reciteStudentMapper;
    @Resource
    private ReciteGroupMapper reciteGroupMapper;
    @Resource
    private ClassService classService;
    @Resource
    private ReciteMapper reciteMapper;
    @Resource
    private UserMapper userMapper;

    /**
     *功能描述 列表--学生
     * @author WN
     * @date 2020/6/10
     * @param  * @param rs
     * @return java.util.List<com.xhkjedu.vo.recite.ReciteStudentVo>
     */
    public List<ReciteStudentVo> listStuReceites(TReciteStudent rs){
        rs.setNowtime(N_Utils.getSecondTimestamp());
        return reciteStudentMapper.listStuReceites(rs);
    }

    /**
     *功能描述 保存--学生保存背诵内容
     * @author WN
     * @date 2020/6/10
     * @param  * @param rs
     * @return java.lang.Integer
     */
    public Integer updateStudRecite(TReciteStudent rs){
        TReciteGroup rg = reciteGroupMapper.findByRsId(rs.getReciteid());
        Integer nowtime = N_Utils.getSecondTimestamp();
        if(rg.getStoptime()>=nowtime){
            rs.setRsstate(1);//准时提交
        }else{
            rs.setRsstate(2);//超时提交
        }

        return reciteStudentMapper.updateStudRecite(rs);
    }

    /**
     * 功能描述 详情--根据学生背诵id获取背诵内容
     *
     * @param *        @param rsid
     * @param reciteid
     * @return com.xhkjedu.vo.recite.ReciteStudentVo
     * @author WN
     * @date 2020/6/10
     */
    public ReciteStudentVo getReciteStuByRsid(Integer studentid, Integer reciteid) {
        return reciteStudentMapper.getReciteStuByRsid(studentid, reciteid);
    }

    /*
    * @Description 背诵统计
    * @Author WN
    * @Date 2023/4/12 16:05
    */
    public List<Map> listRecitesClassForAnalyze(TReciteStudent reciteStudent) {
        List<Map> list = new ArrayList<>();
        List<Map> students = new ArrayList<>();
        TRecite recite = null;
        Integer rschoolid = reciteStudent.getSchoolid();
        Integer teacherid = reciteStudent.getTeacherid();
        Integer usertype = userMapper.getUsertypeByUserid(teacherid);
        if(N_Utils.isEmptyInteger(reciteStudent.getClassid())){
            //教师网页端获取所有
            recite = reciteMapper.selectByPrimaryKey(reciteStudent.getReciteid());
            Map classidMap = classService.getQxClassidsByTeacherid(teacherid, recite.getYear());//教师权限班级
            String classids = "";//教师本校和集团校权限班级
            if (teacherid.equals(recite.getCreateid()) || usertype.equals(0)) {//管理员或自己发布的看所有班级
                classids = null;
            } else if(recite.getHashb() == 1 && recite.getSchoolid().equals(rschoolid)){
                //说明该条数据为登录用户学校发布，包含伙伴学校
                classids = classidMap.get("classids").toString();
            }else{
                classids = classidMap.get("bxclassids").toString();
            }

            students = reciteStudentMapper.listRecitesClassForAnalyze(reciteStudent.getReciteid(), classids,null, rschoolid);//获取教师权限下班级所有学生背诵
        }else{
            //教师app获取指定班级
            students = reciteStudentMapper.listRecitesClassForAnalyze(reciteStudent.getReciteid(), null,reciteStudent.getClassid(), rschoolid);//获取教师权限下班级所有学生背诵
        }

        if (N_Utils.isListEmpty(students)) return list;

        //按学校分组
        Map<Object, List<Map>> schoolMap = students.stream().collect(Collectors.groupingBy(m -> m.get("schoolid")
                , LinkedHashMap::new, Collectors.toList()));

        for(Map.Entry<Object, List<Map>> entry : schoolMap.entrySet()){
            Map saveSchoolMap = new LinkedHashMap();
            List<Map> classList = new ArrayList<>();
            //学校下学生集合
            List<Map> classStuList = entry.getValue();
            Map<Object, List<Map>> classMap = classStuList.stream().collect(Collectors.groupingBy(m -> m.get("classid")
                    , LinkedHashMap::new, Collectors.toList()));//班级下学生集合
            for(Map.Entry<Object, List<Map>> classEntry : classMap.entrySet()){
                Map saveClassMap = new LinkedHashMap();
                //班级下学生集合
                List<Map> stuList = classEntry.getValue();
                Map claMap = stuList.get(0);
                saveSchoolMap.put("schoolid",claMap.get("schoolid"));
                saveSchoolMap.put("schoolname",claMap.get("schoolname"));
                saveClassMap.put("classid",claMap.get("classid"));
                saveClassMap.put("classname",claMap.get("classname"));
                saveClassMap.put("gradeid",claMap.get("gradeid"));
                stuList = stuList.stream().filter(s->N_Utils.isNotEmpty(s.get("studentid"))).collect(Collectors.toList());

                for(int i=0;i<stuList.size();i++){
                    Map stuMap = stuList.get(i);
                    stuMap.remove("schoolid");
                    stuMap.remove("schoolname");
                    stuMap.remove("classid");
                    stuMap.remove("classname");
                    stuMap.remove("gradeid");
                }
                saveClassMap.put("stunum", stuList.size());//学生人数
                List<Map> commitStus = stuList.stream().filter(s -> (int) s.get("rsstate") > 0).collect(Collectors.toList());
                saveClassMap.put("commitnum", commitStus.size());//已提交人数
                double avgscore = commitStus.stream().mapToInt(s -> (int) s.get("userscore")).summaryStatistics().getAverage();
                saveClassMap.put("avgscore", N_Utils.formatDouble(avgscore,2));//平均分
                saveClassMap.put("stulist", stuList);//学生列表

                classList.add(saveClassMap);
            }
            saveSchoolMap.put("classlist",classList);
            list.add(saveSchoolMap);
        }

        /*if(schoolMap.size() > 1){
            //把集团校放在第一个位置
            for(int i=0;i<list.size();i++){
                Map rtnMap= list.get(i);
                Integer schoolid = Integer.parseInt(rtnMap.get("schoolid").toString());
                if(schoolid.equals(recite.getSchoolid())){
                    Collections.swap(list, i, 0);
                    break;
                }
            }
        }*/

        return list;
    }

    /**
     * 背诵学生--网页--列表
     *
     * @return java.util.List<com.xhkjedu.vo.recite.ReciteStudentVo>
     * @Param [student]
     * @Author ywx
     * @Date 2020/9/4 9:08
     **/
    public List<ReciteStudentVo> listReciteStuWeb(TReciteStudent student) {
        student.setNowtime(N_Utils.getSecondTimestamp());
        return reciteStudentMapper.listReciteForStuWeb(student);
    }
}
