package com.srs.routine.service.impl;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.SrsClass;
import com.srs.comprehensive.domain.SrsGrade;
import com.srs.comprehensive.domain.SrsMajors;
import com.srs.comprehensive.mapper.SrsClassMapper;
import com.srs.comprehensive.mapper.SrsGradeMapper;
import com.srs.comprehensive.mapper.SrsMajorsMapper;
import com.srs.routine.domain.RtClassMeetingClass;
import com.srs.routine.domain.SrsAttachResource;
import com.srs.routine.domain.vo.ClassMettingThemeSumitListVo;
import com.srs.routine.mapper.RtClassMeetingClassMapper;
import com.srs.routine.mapper.SrsAttachResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.routine.mapper.RtClassMettingThemeMapper;
import com.srs.routine.domain.RtClassMettingTheme;
import com.srs.routine.service.IRtClassMettingThemeService;

import static com.srs.common.utils.SecurityUtils.getUsername;


/**
 * 班会主题Service业务层处理
 *
 * @author deng
 * @date 2024-05-18
 */
@Service
public class RtClassMettingThemeServiceImpl extends ServiceImpl<RtClassMettingThemeMapper,RtClassMettingTheme> implements IRtClassMettingThemeService {
    @Autowired
    private RtClassMettingThemeMapper rtClassMettingThemeMapper;

    @Autowired
    private SrsAttachResourceMapper srsAttachResourceMapper;

    @Autowired
    public SrsMajorsMapper _majorMapper;

    @Autowired
    public SrsGradeMapper _gradeMapper;

    @Autowired
    public SrsClassMapper _classMapper;

    @Autowired
    public RtClassMeetingClassServiceImpl _classMeetingClassService;

    @Autowired
    public RtClassMeetingClassMapper _classMeetingClassMapper;

    @Override
    public AjaxResult listFdyNeedByCmId(RtClassMeetingClass dto){
        try{
            List<RtClassMeetingClass> list = _classMeetingClassMapper.listFdyNeed(dto);
            return AjaxResult.success(list);
        }catch(Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Override
    public AjaxResult cancelClassMeetingById(Long id){
        try{
            int res = _classMeetingClassMapper.deleteById(id);
            if(res == 0){
                throw new Exception("删除失败");
            }

            return AjaxResult.success();
        }catch(Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @Override
    public List<RtClassMeetingClass> listChoose(RtClassMeetingClass param){
        return _classMeetingClassMapper.listView(param);
    }

    @Override
    public AjaxResult cancelClassMeetingGrade(RtClassMeetingClass param){
        try{
            Long gradeId = param.getGradeId();
            Long cmtId = param.getCmtId();

            QueryWrapper<SrsClass> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("grade_id", gradeId);
            List<SrsClass> srsClasses = _classMapper.selectList(queryWrapper);
            List<Long> classIds = srsClasses.stream().map(SrsClass::getClassId).collect(Collectors.toList());
            if(classIds.isEmpty()){
                throw new Exception("该年级下无班级");
            }

            QueryWrapper<RtClassMeetingClass> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("class_id", classIds);
            queryWrapper1.eq("cmt_id", cmtId);
            int res = _classMeetingClassMapper.delete(queryWrapper1);
            if(res == 0){
                throw new Exception("无班级删除");
            }

            return AjaxResult.success();
        }catch(Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @Override
    public AjaxResult chooseClassMeetingGrade(RtClassMeetingClass param){
        try{
            Long gradeId = param.getGradeId();

            QueryWrapper<SrsClass> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("grade_id", gradeId);
            List<SrsClass> srsClasses = _classMapper.selectList(queryWrapper);
            List<Long> classIds = srsClasses.stream().map(SrsClass::getClassId).collect(Collectors.toList());
            if(classIds.size() == 0){
                return AjaxResult.error("该年级下无班级");
            }
            QueryWrapper<RtClassMeetingClass> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("class_id", classIds);
            queryWrapper1.eq("cmt_id",param.getCmtId());
            List<RtClassMeetingClass> isExist = _classMeetingClassMapper.selectList(queryWrapper1);
            if(isExist.size() != 0){
                for(RtClassMeetingClass x : isExist){
                    Long id = x.classId;
                    for(int i = 0 ; i<classIds.size(); i++){
                        if(Objects.equals(id, classIds.get(i))){
                            classIds.remove(i);
                        }
                    }
                }
            }

            List<RtClassMeetingClass> needInsert = new ArrayList<>();
            for(Long classId:classIds) {
                RtClassMeetingClass classMeetingClass = new RtClassMeetingClass();
                classMeetingClass.setCmtId(param.getCmtId());
                classMeetingClass.setClassId(classId);
                needInsert.add(classMeetingClass);
            }

            if(needInsert.isEmpty()){
                throw new Exception("该年级开设的班级已存在");
            }

            boolean res = _classMeetingClassService.saveBatch(needInsert);

            if(!res){
                throw new Exception("班级添加失败");
            }

            return AjaxResult.success();
        }catch(Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


    @Override
    public List<SrsGrade> listEnableGrade(){
        QueryWrapper<SrsGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("grade_status", "1","3");
        return _gradeMapper.selectList(queryWrapper);
    }



    @Override
    public List<ClassMettingThemeSumitListVo> selectSubmit(String cmNo){
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", cmNo);
        RtClassMettingTheme rmt = rtClassMettingThemeMapper.selectOne(queryWrapper);

        if(rmt == null){
            return Collections.emptyList();
        }

        RtClassMeetingClass dto = new RtClassMeetingClass();
        dto.cmtId = rmt.getCmId();
        dto.cmNo  = cmNo;

        return rtClassMettingThemeMapper.selectSubmit(dto);
    }

    @Override
    public List<Map<String, Object>> listXwTreeDept(Long xyId, String cmNo){
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", cmNo);
        RtClassMettingTheme rmt = rtClassMettingThemeMapper.selectOne(queryWrapper);

        if(rmt == null){
            return Collections.emptyList();
        }

        RtClassMeetingClass dto = new RtClassMeetingClass();
        dto.cmtId = rmt.getCmId();
        dto.cmNo  = cmNo;

        List<Map<String, Object>>  classList = rtClassMettingThemeMapper.listClassCmNo(dto);
        Set<Long> deptIds = new HashSet<>();
        deptIds.add(xyId);

        List<Map<String, Object>> res = new ArrayList<>();
        for(Long deptId:deptIds){
            Map<String,Object> map = new HashMap<>();
            Map<String, Object> deptMap = classList.stream().filter(m -> Long.parseLong(m.get("college_id").toString()) == deptId).findFirst().get();
            String deptName = deptMap.get("dept_name").toString();
            map.put("label", deptName);
            List<Map<String, Object>> children1 = new ArrayList<>();
            Set<Long> majorIds = new HashSet<>();
            for(Map<String, Object> m:classList){
                if(Long.parseLong(m.get("college_id").toString()) == deptId && m.get("major_id")!= null && m.get("major_name")!= null){
                    majorIds.add(Long.parseLong(m.get("major_id").toString()));
                }
            }

            for(Long majorId:majorIds){
                Map<String,Object> map1 = new HashMap<>();
                Map<String, Object> majorMap = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId).findFirst().get();
                if(majorMap.get("major_name")!= null){
                    map1.put("label", majorMap.get("major_name").toString());
                }else{
                    map1.put("label","未知专业");
                }

                List<Map<String, Object>> children2 = new ArrayList<>();
                Set<Long> classIds = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId).map(m ->  Long.parseLong(m.get("class_id").toString())).collect(Collectors.toSet());
                for(Long classId:classIds){
                    Map<String,Object> map2 = new HashMap<>();
                    Map<String, Object> classMap = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId && Long.parseLong(m.get("class_id").toString()) == classId).findFirst().get();
                    String className = "";
                    if(classMap.get("class_name")!= null){
                        className = classMap.get("class_name").toString();
                    }else{
                        className = "未知班级";
                    }
                    String teacherName = "";
                    if(classMap.get("teacher_name") != null){
                        teacherName = classMap.get("teacher_name").toString();
                    }else{
                        teacherName = "未知辅导员";
                    }
                    String isSubmit = classMap.get("cr_id") == null ? "(未提交)" : "(已提交)";
                    map2.put("label", className+" "+teacherName+isSubmit);
                    children2.add(map2);
                }
                map1.put("children", children2);
                children1.add(map1);
            }
            map.put("children", children1);
            res.add(map);
        }

        return res;
    }

    @Override
    public List<Map<String, Object>> listTreeDept(String cmNo){
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", cmNo);
        RtClassMettingTheme rmt = rtClassMettingThemeMapper.selectOne(queryWrapper);

        if(rmt == null){
            return Collections.emptyList();
        }

        RtClassMeetingClass dto = new RtClassMeetingClass();
        dto.cmtId = rmt.getCmId();
        dto.cmNo  = cmNo;

        List<Map<String, Object>>  classList = rtClassMettingThemeMapper.listClassCmNo(dto);
        Set<Long> deptIds = new HashSet<>();
        for(Map<String, Object> map:classList){
            if(map.get("college_id")!= null && map.get("dept_name")!= null){
                deptIds.add(Long.parseLong(map.get("college_id").toString()));
            }
        }
        List<Map<String, Object>> res = new ArrayList<>();
        for(Long deptId:deptIds){
            Map<String,Object> map = new HashMap<>();
            Map<String, Object> deptMap = classList.stream().filter(m -> Long.parseLong(m.get("college_id").toString()) == deptId).findFirst().get();
            String deptName = deptMap.get("dept_name").toString();
            map.put("label", deptName);
            List<Map<String, Object>> children1 = new ArrayList<>();
            Set<Long> majorIds = new HashSet<>();
            for(Map<String, Object> m:classList){
                if(Long.parseLong(m.get("college_id").toString()) == deptId && m.get("major_id")!= null && m.get("major_name")!= null){
                    majorIds.add(Long.parseLong(m.get("major_id").toString()));
                }
            }

            for(Long majorId:majorIds){
                Map<String,Object> map1 = new HashMap<>();
                Map<String, Object> majorMap = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId).findFirst().get();
                if(majorMap.get("major_name")!= null){
                    map1.put("label", majorMap.get("major_name").toString());
                }else{
                    map1.put("label","未知专业");
                }

                List<Map<String, Object>> children2 = new ArrayList<>();
                Set<Long> classIds = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId).map(m ->  Long.parseLong(m.get("class_id").toString())).collect(Collectors.toSet());
                for(Long classId:classIds){
                    Map<String,Object> map2 = new HashMap<>();
                    Map<String, Object> classMap = classList.stream().filter(m ->  Long.parseLong(m.get("college_id").toString()) == deptId && Long.parseLong(m.get("major_id").toString()) == majorId && Long.parseLong(m.get("class_id").toString()) == classId).findFirst().get();
                    String className = "";
                    if(classMap.get("class_name")!= null){
                         className = classMap.get("class_name").toString();
                    }else{
                        className = "未知班级";
                    }
                    String teacherName = "";
                    if(classMap.get("teacher_name") != null){
                        teacherName = classMap.get("teacher_name").toString();
                    }else{
                        teacherName = "未知辅导员";
                    }
                    String isSubmit = classMap.get("cr_id") == null ? "(未提交)" : "(已提交)";
                    map2.put("label", className+" "+teacherName+isSubmit);
                    children2.add(map2);
                }
                map1.put("children", children2);
                children1.add(map1);
            }
            map.put("children", children1);
            res.add(map);
        }

        return res;
    }


    @Override
    public List<SrsClass> listClassByTNo(String tNo){
        return rtClassMettingThemeMapper.listClassByTNo(tNo);
    }


    @Override
    public List<Map<String, Object>> listClassByMajorId(RtClassMettingTheme params){
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", params.getCmNo());
        RtClassMettingTheme rmt = rtClassMettingThemeMapper.selectOne(queryWrapper);

        if(rmt == null){
            return Collections.emptyList();
        }
        params.setCmId(rmt.getCmId());
        return rtClassMettingThemeMapper.listClassByMajorId(params);
    }



    @Override
    public List<SrsMajors> listMajorsByDeptId(Long deptId){
        QueryWrapper<SrsMajors> query = new QueryWrapper<>();
        query.eq("college_id", deptId);
        return _majorMapper.selectList(query);
    }



    @Override
    public List<SysDept> listDept(){
        return rtClassMettingThemeMapper.listDept();
    }



    /**
     * 查询班会主题
     *
     * @param cmId 班会主题主键
     * @return 班会主题
     */
    @Override
    public RtClassMettingTheme selectRtClassMettingThemeByCmId(Long cmId) {
        RtClassMettingTheme rmt=rtClassMettingThemeMapper.selectRtClassMettingThemeByCmId(cmId);
        SrsAttachResource sar=new SrsAttachResource();
        sar.setResMainNo(rmt.getCmNo());
        sar.setResType("bhwj01");
        List<SrsAttachResource> list=srsAttachResourceMapper.selectSrsAttachResourceList(sar);
        rmt.setAttachResourceList(list);
        return rmt;
    }

    /**
     * 查询班会主题列表
     *
     * @param rtClassMettingTheme 班会主题
     * @return 班会主题
     */
    @Override
    public List<RtClassMettingTheme> selectRtClassMettingThemeList(RtClassMettingTheme rtClassMettingTheme) {
        List<RtClassMettingTheme> list= rtClassMettingThemeMapper.selectCurrentThemeComplateList(rtClassMettingTheme);
        for (RtClassMettingTheme rc:list) {
            SrsAttachResource sar=new SrsAttachResource();
            sar.setResMainNo(rc.getCmNo());
            sar.setResType("bhwj01");
            List<SrsAttachResource> listr=srsAttachResourceMapper.selectSrsAttachResourceList(sar);
            rc.setAttachResourceList(listr);
        }
        return list;
    }

    @Override
    public List<RtClassMettingTheme> completeStuList(RtClassMettingTheme rtClassMettingTheme) {
        rtClassMettingTheme.setStatus("1");
        List<RtClassMettingTheme> list= rtClassMettingThemeMapper.completeStuList(rtClassMettingTheme);
        for (RtClassMettingTheme rc:list) {
            SrsAttachResource sar=new SrsAttachResource();
            sar.setResMainNo(rc.getCmNo());
            sar.setResType("bhwj01");
            List<SrsAttachResource> listr=srsAttachResourceMapper.selectSrsAttachResourceList(sar);
            rc.setAttachResourceList(listr);
        }
        return list;
    }

    @Override
    public List<RtClassMettingTheme> selectCurrentThemeComplateList(RtClassMettingTheme rtClassMettingTheme) {
        rtClassMettingTheme.setStatus("1");
        List<RtClassMettingTheme> list= rtClassMettingThemeMapper.selectCurrentThemeComplateList(rtClassMettingTheme);
        for (RtClassMettingTheme rc:list) {
            SrsAttachResource sar=new SrsAttachResource();
            sar.setResMainNo(rc.getCmNo());
            sar.setResType("bhwj01");
            List<SrsAttachResource> listr=srsAttachResourceMapper.selectSrsAttachResourceList(sar);
            rc.setAttachResourceList(listr);
        }
        return list;
    }

    @Override
    public List<RtClassMettingTheme> listFdyNeedCm(RtClassMettingTheme rtClassMettingTheme){
        rtClassMettingTheme.setStatus("1");
        List<RtClassMettingTheme> res = new ArrayList<>();
        List<RtClassMettingTheme> list= rtClassMettingThemeMapper.selectCurrentThemeComplateList(rtClassMettingTheme);
        for (RtClassMettingTheme rc:list) {
            SrsAttachResource sar=new SrsAttachResource();
            sar.setResMainNo(rc.getCmNo());
            sar.setResType("bhwj01");
            List<SrsAttachResource> listr=srsAttachResourceMapper.selectSrsAttachResourceList(sar);
            rc.setAttachResourceList(listr);
        }
        list.forEach(x->{
            RtClassMeetingClass dto = new RtClassMeetingClass();
            dto.setCmtId(x.getCmId());
            dto.tNo = getUsername();
            List<RtClassMeetingClass> list1 = _classMeetingClassMapper.listFdyNeed(dto);
            if(!list1.isEmpty()){
                res.add(x);
            }
        });
        return res;
    }

    /**
     * 新增班会主题
     *
     * @param rtClassMettingTheme 班会主题
     * @return 结果
     */
    @Override
    public int insertRtClassMettingTheme(RtClassMettingTheme rtClassMettingTheme) {
        rtClassMettingTheme.setCmNo(UUID.randomUUID().toString());
        rtClassMettingTheme.setCreateTime(DateUtils.getNowDate());
        for (SrsAttachResource atta:rtClassMettingTheme.getAttachResourceList()) {
            atta.setDelFlag("0");
            atta.setResNo(UUID.randomUUID().toString());
            atta.setResMainNo(rtClassMettingTheme.getCmNo());
            atta.setResType("bhwj01");
            atta.setCreateTime(DateUtils.getNowDate());
            atta.setStatus("0");
            srsAttachResourceMapper.insertSrsAttachResource(atta);
        }
        return rtClassMettingThemeMapper.insertRtClassMettingTheme(rtClassMettingTheme);
    }

    /**
     * 修改班会主题
     *
     * @param rtClassMettingTheme 班会主题
     * @return 结果
     */
    @Override
    public int updateRtClassMettingTheme(RtClassMettingTheme rtClassMettingTheme) {
        rtClassMettingTheme.setUpdateTime(DateUtils.getNowDate());
        //先删除附件，再新增附件
        srsAttachResourceMapper.deleteSrsAttachResourceByResManNo(rtClassMettingTheme.getCmNo());
        for (SrsAttachResource atta:rtClassMettingTheme.getAttachResourceList()) {
            atta.setDelFlag("0");
            atta.setResNo(UUID.randomUUID().toString());
            atta.setResMainNo(rtClassMettingTheme.getCmNo());
            atta.setResType("bhwj01");
            atta.setCreateTime(DateUtils.getNowDate());
            atta.setStatus("0");
            srsAttachResourceMapper.insertSrsAttachResource(atta);
        }
        return rtClassMettingThemeMapper.updateRtClassMettingTheme(rtClassMettingTheme);
    }

    /**
     * 批量删除班会主题
     *
     * @param cmIds 需要删除的班会主题主键
     * @return 结果
     */
    @Override
    public int deleteRtClassMettingThemeByCmIds(Long[] cmIds) {
        return rtClassMettingThemeMapper.deleteRtClassMettingThemeByCmIds(cmIds);
    }

    /**
     * 删除班会主题信息
     *
     * @param cmId 班会主题主键
     * @return 结果
     */
    @Override
    public int deleteRtClassMettingThemeByCmId(Long cmId) {
        return rtClassMettingThemeMapper.deleteRtClassMettingThemeByCmId(cmId);
    }
}
