package com.xhkjedu.suser.service.system;

import com.xhkjedu.exception.MissingParametersException;
import com.xhkjedu.suser.config.ConfigKey;
import com.xhkjedu.suser.mapper.gradeclass.ClassTeacherMapper;
import com.xhkjedu.suser.mapper.gradeclass.GradeMapper;
import com.xhkjedu.suser.mapper.gradeclass.SchoolMapper;
import com.xhkjedu.suser.mapper.subjectbook.TeacherPowersbMapper;
import com.xhkjedu.suser.mapper.subjectbook.TeacherSubjectbookMapper;
import com.xhkjedu.suser.mapper.system.UserModuleMapper;
import com.xhkjedu.suser.mapper.system.UserRoleMapper;
import com.xhkjedu.suser.model.gradeclass.TClassTeacher;
import com.xhkjedu.suser.model.gradeclass.TSchool;
import com.xhkjedu.suser.model.subjectbook.TTeacherPowersb;
import com.xhkjedu.suser.model.system.TUserRole;
import com.xhkjedu.suser.vo.gradeclass.ClassVo;
import com.xhkjedu.suser.vo.gradeclass.GradeVo;
import com.xhkjedu.suser.vo.system.SchoolVo;
import com.xhkjedu.suser.vo.system.TeacherRoleParam;
import com.xhkjedu.suser.vo.system.TeacherRoleVo;
import com.xhkjedu.suser.vo.system.UserRoleVo;
import com.xhkjedu.utils.JedisUtil;
import com.xhkjedu.utils.N_Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

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

/**
 * @ClassName TeacherRoleService
 * Description TODO
 * Author WN
 * Date 2020/6/18 9:44
 **/
@Service
@Slf4j
public class TeacherRoleService extends JedisUtil {
    @Resource
    private ClassTeacherMapper classTeacherMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private TeacherPowersbMapper teacherPowersbMapper;
    @Resource
    private TeacherSubjectbookMapper teacherSubjectbookMapper;
    @Resource
    private UserModuleMapper userModuleMapper;
    @Resource
    private SchoolMapper schoolMapper;
    @Resource
    private GradeMapper gradeMapper;

    /**
     * @Description 校验权限科目和年级（都是只能有一个）
     * @Date 2023/11/8 16:19
     * @Author YWX
     * @Param [trole]
     * @Return void
     **/
    public void checkSubjectAndGrade(TeacherRoleParam trole) {
        List<String> lsblist = trole.getLsblist();
        if (N_Utils.isListNotEmpty(lsblist)) {
            Integer snum = teacherPowersbMapper.countSubjectByLsbId(lsblist);//获取教材下科目数量
            if (snum.compareTo(1) >= 1) throw new MissingParametersException("科目选择有误！");
        }
        List<Integer> classlist = trole.getClasslist();
        List<Map> jtclasslist = trole.getJtclasslist();
        List<Integer> classids = new ArrayList<>();
        classids.addAll(classlist);
        for (Map map : jtclasslist) {
            classids.add((Integer) map.get("classid"));
        }
        if (N_Utils.isListNotEmpty(classids)) {
            Integer cnum = teacherPowersbMapper.countGradeByClassId(classids);//获取班级下年级数量
            if (cnum.compareTo(1) >= 1) throw new MissingParametersException("班级选择有误！");
        }
    }

    /**
     *功能描述  保存教师设置权限
     * @author WN
     * @date 2020/6/18
     * @param  * @param trole
     * @return void
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(TeacherRoleParam trole) throws Exception {
        try {
            SchoolVo schoolVo = schoolMapper.getSchoolCloudByUserid(trole.getTeacherid());
            trole.setYear(schoolVo.getYear());
            int timestamp = N_Utils.getSecondTimestamp();
            //处理用户角色
            // 先删除
            userRoleMapper.deleteByUserid(trole.getTeacherid());
            String key = schoolVo.getCloudcode() + "_module_" + schoolVo.getSchoolid() + "_" + trole.getTeacherid();
            if (!CollectionUtils.isEmpty(trole.getRolelist())) {
                List<TUserRole> rolelst = new ArrayList<>();
                for (Integer roleid : trole.getRolelist()) {
                    TUserRole ur = new TUserRole();
                    ur.setUserid(trole.getTeacherid());
                    ur.setRoleid(roleid);
                    ur.setCreatetime(timestamp);
                    ur.setCreateid(trole.getCreateid());

                    rolelst.add(ur);
                }
                //批量保存用户角色信息
                userRoleMapper.insertList(rolelst);

                //获取用户角色对应模块
                List<String> modules = userRoleMapper.listModuleurlsByUserid(trole.getTeacherid());
                set(key, modules, ConfigKey.redisumtime);
            }else{
                //如果用户无角色，则移除缓存中数据
                delete(key);
            }

            //根据用户id删除没有权限的常用模块
            userModuleMapper.deleteNoRoleByUserId(trole.getTeacherid());

            //处理用户教材
            List<String> lsbids = teacherSubjectbookMapper.listLsbsByUserid(trole.getTeacherid());
            List<String> lsbId = N_Utils.listNotInList3(lsbids, trole.getLsblist());
            if (N_Utils.isListNotEmpty(lsbId)) {//删除教师收藏教材
                teacherSubjectbookMapper.deleteByLsbIdTeacherId(lsbId, trole.getTeacherid());
            }
            //先删除
            teacherPowersbMapper.deleteByUserid(trole.getTeacherid());
            if (!CollectionUtils.isEmpty(trole.getLsblist())) {
                List<TTeacherPowersb> tpowerlist = new ArrayList<>();
                //根据教材id获取科目id
                String subjectid = teacherPowersbMapper.getSubjectidBylsbid(trole.getLsblist().get(0));
                for (String lsbid : trole.getLsblist()) {
                    TTeacherPowersb tp = new TTeacherPowersb();
                    tp.setTeacherid(trole.getTeacherid());
                    tp.setLsbid(lsbid);
                    tp.setCreateid(trole.getCreateid());
                    tp.setCreatetime(timestamp);
                    tp.setSchoolid(trole.getSchoolid());
                    tp.setSubjectid(subjectid);

                    tpowerlist.add(tp);
                }

                teacherPowersbMapper.insertList(tpowerlist);
            }

            //处理用户班级
            //先删除任教班级
            classTeacherMapper.deleteByUserid(trole.getTeacherid(),trole.getYear());
            List<TClassTeacher> ctlst = new ArrayList<>();//班级教师
            //处理本校班级
            if(!CollectionUtils.isEmpty(trole.getClasslist())){

                for(Integer classid : trole.getClasslist()){
                    TClassTeacher ct = new TClassTeacher();
                    ct.setTeacherid(trole.getTeacherid());
                    ct.setClassid(classid);
                    ct.setCreateid(trole.getCreateid());
                    ct.setSchoolid(trole.getSchoolid());
                    ct.setCreatetime(timestamp);

                    ctlst.add(ct);
                }
            }

            //处理集团校班级
            if(N_Utils.isListNotEmpty(trole.getJtclasslist())){
                for(Map ctmap : trole.getJtclasslist()){
                    Integer schoolid = Integer.parseInt(ctmap.get("schoolid").toString());
                    Integer classid = Integer.parseInt(ctmap.get("classid").toString());
                    TClassTeacher ct = new TClassTeacher();
                    ct.setTeacherid(trole.getTeacherid());
                    ct.setClassid(classid);
                    ct.setCreateid(trole.getCreateid());
                    ct.setSchoolid(schoolid);
                    ct.setCreatetime(timestamp);

                    ctlst.add(ct);
                }
            }
            //保存教师设置班级
            if(N_Utils.isListNotEmpty(ctlst)){
                classTeacherMapper.insertList(ctlst);
            }

        } catch (Exception e) {
            log.error("教师设置权限失败："+e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("教师设置权限失败");
        }

    }

    //获取用户权限--角色、班级、教材 集合
    public Map getTeacherRoles(TeacherRoleParam trparam) {
        Map school = schoolMapper.getYearSchoolidByUserId(trparam.getTeacherid());
        Integer year = Integer.parseInt(school.get("year").toString());
        trparam.setYear(year);
        //当前用户所在学校id
        Integer schoolid = Integer.parseInt(school.get("schoolid").toString());

        //获取已设置角色集合
        List<UserRoleVo> roleids = userRoleMapper.listRolesByUserid(trparam.getTeacherid());
        List<ClassVo> classids = classTeacherMapper.listClassesByUserid(trparam.getTeacherid(), trparam.getYear(), trparam.getClasstype(),schoolid);
        List<Map> lsbids = teacherPowersbMapper.listLsbsByUserid(trparam.getTeacherid());

        List<Map> jtclasslist = gradeMapper.listTeacherJtClasses(schoolid,trparam.getTeacherid(),year);//集团学校班级

        Map rtnmap = new HashMap();
        rtnmap.put("rolelist",roleids);
        rtnmap.put("classlist",classids);
        rtnmap.put("lsblist",lsbids);
        rtnmap.put("jtclasslist",jtclasslist);

        return rtnmap;
    }

    /**
     * 教师权限教材列表
     * @Param [teacherid]
     * @Author ywx
     * @Date 2020/7/1 10:42
     * @return com.xhkjedu.suser.vo.system.TeacherRoleVo
     **/
    public TeacherRoleVo listBook(Integer teacherid) {
        TeacherRoleVo trvo = new TeacherRoleVo();
        //获取已设置角色集合
        List<Map> lsbids = teacherPowersbMapper.listLsbsByUserid(teacherid);
        trvo.setLsblist(lsbids);
        return trvo;
    }

    /**
     * 教师权限科目
     *
     * @return java.util.List<com.xhkjedu.suser.vo.subjectbook.SubjectVo>
     * @Param [teacherid]
     * @Author ywx
     * @Date 2020/7/24 9:26
     **/
    public List<Map> listSubject(Integer teacherid) {
        return teacherPowersbMapper.listSubject(teacherid);
    }

    /**
     * 功能描述 教师权限科目下，权限教材
     *
     * @param *         @param teacherid
     * @param subjectid
     * @return java.util.List<com.xhkjedu.suser.vo.subjectbook.LsbBookVo>
     * @author WN
     * @date 2020/8/11
     */
    public List<Map> listBookBySubjectid(Integer teacherid, String subjectid) {
        return teacherPowersbMapper.listBookBySubjectid(teacherid, subjectid);
    }

    /**
     * 教师权限班级-本校
     * @Param [teacherid, year]
     * @Author ywx
     * @Date 2020/7/29 9:56
     * @return java.util.List<com.xhkjedu.suser.vo.gradeclass.ClassVo>
     **/
    public List<GradeVo> listGradeClassesByUserid(TeacherRoleParam role) {
        TSchool school = schoolMapper.getSchoolInfoByUserid(role.getTeacherid());
        role.setYear(school.getYear());
        role.setSchoolid(school.getSchoolid());
        return classTeacherMapper.listGradeClassesByUserid(role);
    }

    /**
     * @Description 教师权限班级学生
     * @Date 2023/12/19 10:40
     * @Author YWX
     * @Param [role]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listClassStu(TeacherRoleParam role) {
        TSchool school = schoolMapper.getSchoolInfoByUserid(role.getTeacherid());
        role.setYear(school.getYear());
        role.setSchoolid(school.getSchoolid());
        return classTeacherMapper.listClassStu(role);
    }

    /**
     * 教师权限班级
     * @Param [role]
     * @Author ywx
     * @Date 2021/6/15 17:41
     * @return java.util.List<com.xhkjedu.suser.vo.gradeclass.GradeVo>
     **/
    public List<GradeVo> listGradeClassesByUserid2(TeacherRoleParam role) {
        //Integer year = schoolMapper.getYearByUserId(role.getTeacherid());
        //role.setYear(year);
        role.setSchoolid(schoolMapper.getSchoolidByUserId(role.getTeacherid()));
        return classTeacherMapper.listGradeClassesByUserid2(role);
    }

    /**
     * @Description 获取教师权限年级下所有班级
     * @Param [trole]
     * @Return java.util.List<com.xhkjedu.suser.vo.gradeclass.GradeVo>
     * @Author wn
     * @Date 2022/6/28 9:32
     **/
    public List<GradeVo> listRoleGradeAllClass(TeacherRoleParam trole) {
        TSchool school = schoolMapper.getSchoolInfoByUserid(trole.getTeacherid());
        trole.setYear(school.getYear());
        trole.setSchoolid(school.getSchoolid());
        return classTeacherMapper.listRoleGradeAllClass(trole);
    }
}
