package com.xhkjedu.sstudy.service.recite;

import com.xhkjedu.sstudy.mapper.gradeclass.ClassMapper;
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.subjectbook.TeacherSubjectbookMapper;
import com.xhkjedu.sstudy.mapper.system.SchoolMapper;
import com.xhkjedu.sstudy.model.recite.TRecite;
import com.xhkjedu.sstudy.model.recite.TReciteGroup;
import com.xhkjedu.sstudy.model.recite.TReciteStudent;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * @ClassName ReciteService
 * Description TODO
 * Author WN
 * Date 2020/6/10 9:25
 **/
@Slf4j
@Service
public class ReciteService {
    @Autowired
    private ReciteMapper reciteMapper;

    @Autowired
    private ReciteGroupMapper reciteGroupMapper;

    @Autowired
    private ReciteStudentMapper reciteStudentMapper;

    @Autowired
    private ClassMapper classMapper;

    @Resource
    private SchoolMapper schoolMapper;

    @Resource
    private TeacherSubjectbookMapper teacherSubjectbookMapper;

    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(TRecite recite){
        try {
            //根据用户id获取用户权限科目，如果上传科目和权限科目不一致，不允许保存
            String subjectid = teacherSubjectbookMapper.listSubjectidByTeacherid(recite.getCreateid());
            if(!subjectid.equals(recite.getSubjectid())){
                return new ResultVo(1,"保存失败");
            }else{
                recite.setCreatetime(N_Utils.getSecondTimestamp());
                recite.setRecitestate(22);//背诵作业状态：21未布置 22 已布置
                if(N_Utils.isListNotEmpty(recite.getJtrclist())){
                    recite.setHashb(1);
                }else{
                    recite.setHashb(0);
                }

                int year = schoolMapper.getYearById(recite.getSchoolid());
                recite.setYear(year);
                reciteMapper.insertUseGeneratedKeys(recite);
                //保存背诵班级-分组-学生
                saveReciteGroup(recite);
                return new ResultVo(0,"保存成功");
            }
        }catch (Exception e){
            log.error("发布背诵失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultVo(1,"保存失败");
        }
    }

    //保存背诵班级-分组-学生
    private void saveReciteGroup(TRecite recite){
        //班级
        List<TReciteGroup> classlst = recite.getRclist().stream().distinct().collect(Collectors.toList());

        List<TReciteGroup> savegroup = new ArrayList<>();//保存班级分组
        List<TReciteStudent> savestu = new ArrayList<>();//保存班级学生

        //本校班级学生
        for(TReciteGroup cl : classlst){
            TReciteGroup rg = new TReciteGroup();
            rg.setCreateid(recite.getCreateid());
            rg.setSchoolid(recite.getSchoolid());
            rg.setCreatetime(N_Utils.getSecondTimestamp());
            rg.setRgstate(22);//已布置
            rg.setReciteid(recite.getId());
            rg.setCreatetime(N_Utils.getSecondTimestamp());
            rg.setClassid(cl.getClassid());
            rg.setStarttime(recite.getStarttime());
            rg.setStoptime(recite.getStoptime());
            savegroup.add(rg);

            String groupids = StringUtils.join(cl.getGroups(),",");

            //获取选中班级分组下所有学生
            List<Integer> stus = classMapper.listStudentidsByGroupids(groupids);
            for(Integer s : stus){
                TReciteStudent rs = new TReciteStudent();
                rs.setReciteid(recite.getId());
                rs.setClassid(cl.getClassid());
                rs.setStudentid(s);
                rs.setCreateid(recite.getCreateid());
                rs.setCreatetime(N_Utils.getSecondTimestamp());
                rs.setSchoolid(recite.getSchoolid());

                savestu.add(rs);
            }
        }

        //集团校班级学生
        List<Map> jtrclist = recite.getJtrclist();
        if(N_Utils.isListNotEmpty(jtrclist)){
            for(Map schoolmap : jtrclist){
                Integer schoolid = Integer.parseInt(schoolmap.get("schoolid").toString());
                List<Map> classlist = (List<Map>) schoolmap.get("classlist");
                for(Map classmap : classlist){
                    Integer classid = Integer.parseInt(classmap.get("classid").toString());
                    List<Integer> grouplist = (List<Integer>) classmap.get("groups");
                    if(N_Utils.isListNotEmpty(grouplist)){
                        TReciteGroup rg = new TReciteGroup();
                        rg.setCreateid(recite.getCreateid());
                        rg.setSchoolid(schoolid);
                        rg.setCreatetime(N_Utils.getSecondTimestamp());
                        rg.setRgstate(22);//已布置
                        rg.setReciteid(recite.getId());
                        rg.setCreatetime(N_Utils.getSecondTimestamp());
                        rg.setClassid(classid);
                        rg.setStarttime(recite.getStarttime());
                        rg.setStoptime(recite.getStoptime());
                        savegroup.add(rg);

                        String groupids = StringUtils.join(grouplist,",");

                        //获取选中班级分组下所有学生
                        List<Integer> stus = classMapper.listStudentidsByGroupids(groupids);
                        for(Integer s : stus){
                            TReciteStudent rs = new TReciteStudent();
                            rs.setReciteid(recite.getId());
                            rs.setClassid(classid);
                            rs.setStudentid(s);
                            rs.setCreateid(recite.getCreateid());
                            rs.setCreatetime(N_Utils.getSecondTimestamp());
                            rs.setSchoolid(schoolid);

                            savestu.add(rs);
                        }
                    }
                }
            }
        }

        //批量保存背诵班级分组
        reciteGroupMapper.insertList(savegroup);
        //批量保存背诵班级分组学生
        reciteStudentMapper.saveBatch(savestu);
    }

    /**
     *功能描述 修改
     * @author WN
     * @date 2020/6/10
     * @param  * @param recite
     * @return java.lang.Integer
     */
    public Integer updateRecite(TRecite recite) throws Exception{
        return reciteMapper.updateRecite(recite);
    }

    /**
     *功能描述 删除
     * @author WN
     * @date 2020/6/10
     * @param  * @param reciteid
     * @return java.lang.Integer
     */
    public Integer delRecite(Integer reciteid){
        return reciteMapper.deleteByPrimaryKey(reciteid);
    }

    /**
     * 功能描述 列表--网页
     *
     * @param * @param recite
     * @return java.util.Map
     * @author WN
     * @date 2020/6/10
     */
    public List<Map> listRecites(TRecite recite, Integer usertype) {
        List<Map> list = reciteMapper.listRecites(recite, usertype);
        for(Map map : list){
            List<Map> reciteStus = (List<Map>) map.get("reciteStus");//背诵关联学生
            Integer hashb = Integer.parseInt(map.get("hashb").toString());
            Integer schoolid = Integer.parseInt(map.get("schoolid").toString());
            String classidStr = "";
            if (recite.getCreateid().equals(map.get("createid")) || usertype.equals(0)) {//管理员或自己发布的看所有班级
                List<Map> commitList = reciteStus.stream().filter(s -> Integer.parseInt(s.get("rsstate").toString()) > 0).collect(Collectors.toList());
                map.put("stunum",reciteStus.size());
                map.put("commitnum",commitList.size());
                map.remove("reciteStus");
                continue;
            } else if (hashb == 1 && recite.getSchoolid().equals(schoolid)) {
                //当条背诵为集团校发布并且发布学校为当前登录学校。获取所有数量为学生数量和提交数量
                classidStr = recite.getClassids();
            }else{
                classidStr = recite.getBxclassids();
            }

            List<String> classids = Arrays.asList(classidStr.split(","));
            List<Map> stuList = reciteStus.stream().filter(s -> classids.contains(s.get("classid").toString())).collect(Collectors.toList());
            List<Map> commitList = stuList.stream().filter(s -> Integer.parseInt(s.get("rsstate").toString()) > 0).collect(Collectors.toList());

            map.put("stunum",stuList.size());
            map.put("commitnum",commitList.size());
            map.remove("reciteStus");
        }
        return list;
    }

    /*
     * @Description 列表--网页--我的
     * @Date 2024/3/12 9:37:59
     * @Author WN
     * @Param [recite, usertype]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listMyRecites(TRecite recite, Integer usertype) {

        List<Map> list = reciteMapper.listMyRecites(recite);
        for(Map map : list){
            List<Map> reciteStus = (List<Map>) map.get("reciteStus");//背诵关联学生
            Integer hashb = Integer.parseInt(map.get("hashb").toString());
            Integer schoolid = Integer.parseInt(map.get("schoolid").toString());
            String classidStr = "";
            if (recite.getCreateid().equals(map.get("createid")) || usertype.equals(0)) {//管理员或自己发布的看所有班级
                List<Map> commitList = reciteStus.stream().filter(s -> Integer.parseInt(s.get("rsstate").toString()) > 0).collect(Collectors.toList());
                map.put("stunum",reciteStus.size());
                map.put("commitnum",commitList.size());
                map.remove("reciteStus");
                continue;
            } else if (hashb == 1 && recite.getSchoolid().equals(schoolid)) {
                //当条背诵为集团校发布并且发布学校为当前登录学校。获取所有数量为学生数量和提交数量
                classidStr = recite.getClassids();
            }else{
                classidStr = recite.getBxclassids();
            }

            List<String> classids = Arrays.asList(classidStr.split(","));
            List<Map> stuList = reciteStus.stream().filter(s -> classids.contains(s.get("classid").toString())).collect(Collectors.toList());
            List<Map> commitList = stuList.stream().filter(s -> Integer.parseInt(s.get("rsstate").toString()) > 0).collect(Collectors.toList());

            map.put("stunum",stuList.size());
            map.put("commitnum",commitList.size());
            map.remove("reciteStus");
        }
        return list;
    }

    /**
     * 获取背诵班级
     *
     * @return java.util.List<java.util.Map>
     * @Param [reciteid]
     * @Author ywx
     * @Date 2022/6/21 10:33
     **/
    public Map listClass(TRecite recite, Integer usertype) {
        Map<String,List<Map>> rtnMap = new LinkedHashMap<>();
        //获取本背诵内容
        TRecite reObj = reciteMapper.selectByPrimaryKey(recite.getReciteid());
        if (recite.getCreateid().equals(reObj.getCreateid()) || usertype.equals(0)) {//管理员或自己发布的看所有班级
            recite.setClassids(null);
        } else if(reObj.getHashb() == 1 && recite.getSchoolid().equals(reObj.getSchoolid())){
            //当前登录用户发布的包含伙伴学校的内容
        }else{
            recite.setClassids(recite.getBxclassids());
        }

        List<Map> classlist = reciteMapper.listClass(recite);
        List<Map> bxclass = new ArrayList<>();
        List<Map> hbclass = new ArrayList<>();
        if(N_Utils.isListNotEmpty(classlist)){
            for(Map map : classlist){
                Integer schoolid = Integer.parseInt(map.get("schoolid").toString());
                if(schoolid.equals(reObj.getSchoolid())){
                    //代表本校
                    bxclass.add(map);
                }else{
                    hbclass.add(map);
                }
            }
        }

        rtnMap.put("bx",bxclass);
        rtnMap.put("hb",hbclass);

        return rtnMap;
    }

    //获取背诵年份
    public Integer getYearById(Integer reciteid){
        return reciteMapper.getYearById(reciteid);
    }
}
