package com.xhkjedu.sapi.service.notice;

import com.xhkjedu.sapi.listener.MessageSender;
import com.xhkjedu.sapi.mapper.notice.NoticeClassMapper;
import com.xhkjedu.sapi.mapper.notice.NoticeFileMapper;
import com.xhkjedu.sapi.mapper.notice.NoticeMapper;
import com.xhkjedu.sapi.mapper.notice.NoticeUserMapper;
import com.xhkjedu.sapi.model.notice.TNotice;
import com.xhkjedu.sapi.model.notice.TNoticeClass;
import com.xhkjedu.sapi.model.notice.TNoticeFile;
import com.xhkjedu.sapi.model.notice.TNoticeUser;
import com.xhkjedu.sapi.vo.notice.NoticeClassVo;
import com.xhkjedu.sapi.vo.notice.NoticeVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author ywx
 * @classname NoticeService
 * @description 
 * @date 2020/6/12 17:55
 **/
@Service
public class NoticeService {
    @Resource
    private NoticeMapper noticeMapper;
    @Resource
    private NoticeClassMapper noticeClassMapper;
    @Resource
    private NoticeUserMapper noticeUserMapper;
    @Resource
    private NoticeFileMapper noticeFileMapper;
    @Resource
    private MessageSender messageSender;

    //添加
    @Transactional(rollbackFor = Exception.class)
    public Integer save(TNotice model) {
        if (N_Utils.isEmptyInteger(model.getCreatetime())) {
            model.setCreatetime(N_Utils.getSecondTimestamp());
        }

        //根据noticetype发布对象为学生时，获取教师科目
        if(model.getNoticetype() == 3){
            //获取教师任教科目
            String subjectid = noticeMapper.getUserSubjectByUserid(model.getCreateid());
            if(N_Utils.isNotEmpty(subjectid)){
                model.setSubjectid(subjectid);
            }
        }

        noticeMapper.insertUseGeneratedKeys(model);
        model.setNoticeid(model.getId());
        //添加通知对象
        saveNoticeObj(model);

        //添加通知附件
        saveFile(model);
        return model.getId();
    }

    /**
     * @Description 添加通知附件
     * @Date 2023/12/20 9:33
     * @Author YWX
     * @Param [model]
     * @Return void
     **/
    private void saveFile(TNotice model) {
        List<TNoticeFile> files = model.getFiles();
        if (N_Utils.isListNotEmpty(files)) {
            Integer noticeid = model.getNoticeid();
            for (TNoticeFile file : files) {
                file.setNoticeid(noticeid);
            }
            noticeFileMapper.insertList(files);
        }
    }

    //删除
    public void deleteById(Integer noticeid) {
        List<TNoticeFile> files = noticeFileMapper.listByNoticeId(noticeid);
        noticeMapper.deleteByPrimaryKey(noticeid);
        resourceDel(files);
    }

    /**
     * @Description 删除服务器文件
     * @Date 2023/12/20 9:48
     * @Author YWX
     * @Param [files]
     * @Return void
     **/
    private void resourceDel(List<TNoticeFile> files) {
        if (N_Utils.isListNotEmpty(files)) {
            List<String> resourceUrls = new ArrayList<>();
            for (TNoticeFile file : files) {
                resourceUrls.add(file.getResourceurl());
                String resourcecover = file.getResourcecover();
                if (N_Utils.isNotEmpty(resourcecover)) resourceUrls.add(resourcecover);
                String pdfurl = file.getPdfurl();
                if (N_Utils.isNotEmpty(pdfurl)) resourceUrls.add(pdfurl);
            }
            messageSender.resourceDel(resourceUrls);//给文件服务器发送mq删除文件
        }
    }

    //修改
    @Transactional(rollbackFor = Exception.class)
    public void update(TNotice model) {
        noticeMapper.updateByPrimaryKeySelective(model);
        Integer noticeid = model.getNoticeid();
        //添加通知对象
        noticeUserMapper.deleteByNoticeId(noticeid);//删除通知对象
        saveNoticeObj(model);//重新添加

        //添加通知附件
        List<TNoticeFile> oldFiles = noticeFileMapper.listByNoticeId(noticeid);
        noticeFileMapper.deleteByNoticeId(noticeid);//删除通知附件
        saveFile(model);//重新添加
        //删除的文件从服务器删除
        List<TNoticeFile> delFiles = new ArrayList<>();
        List<String> resourceurls = model.getFiles().stream().map(TNoticeFile::getResourceurl).collect(Collectors.toList());
        for (TNoticeFile oldFile : oldFiles) {
            String resourceurl = oldFile.getResourceurl();
            if(!resourceurls.contains(resourceurl)){
                delFiles.add(oldFile);
            }
        }
        resourceDel(delFiles);
    }

    //添加通知对象
    private void saveNoticeObj(TNotice model) {
        model.setUsers(N_Utils.listDistinct(model.getUsers()));//通知对象去重
        noticeUserMapper.batchSave(model);
    }

    //获取详情
    public TNotice findById(Integer noticeid) {
        TNotice notice = noticeMapper.findById(noticeid);
        notice.setFiles(noticeFileMapper.listByNoticeId(noticeid));
        return notice;
    }

    //获取列表
    public List <NoticeVo> listAll(TNotice notice) {
        return noticeMapper.listAll(notice);
    }

    /**
     * 用户通知列表
     * @Param [notice]
     * @Author ywx
     * @Date 2020/6/13 9:55
     * @return java.util.List<com.xhkjedu.vo.notice.NoticeVo>
     **/
    public List<NoticeVo> listMy(TNotice notice) {
        return noticeMapper.listMy(notice);
    }

    /**
     * 学生通知列表
     * @Param [notice]
     * @Author ywx
     * @Date 2020/6/22 10:02
     * @return java.util.List<com.xhkjedu.vo.notice.NoticeVo>
     **/
    public List<NoticeVo> listStudent(TNotice notice) {
        return noticeMapper.listStudent(notice);
    }

    /**
     * 用户查看
     * @Param [noticeid, createid]
     * @Author ywx
     * @Date 2020/6/13 11:21
     * @return com.xhkjedu.model.notice.TNotice
     **/
    public TNotice reade(Integer noticeid, Integer createid) {
        TNotice notice = noticeMapper.findById2(noticeid);
        notice.setFiles(noticeFileMapper.listByNoticeId(noticeid));
        noticeUserMapper.reade(noticeid, createid, N_Utils.getSecondTimestamp());
        return notice;
    }

    /**
     * 学生查看
     * @Param [noticeid]
     * @Author ywx
     * @Date 2020/6/22 11:00
     * @return com.xhkjedu.model.notice.TNotice
     **/
    public TNotice findById2(Integer noticeid) {
        return noticeMapper.findById2(noticeid);
    }

    /**
     * 用户未看通知数量
     * @Param [teacherid]
     * @Author ywx
     * @Date 2020/7/24 10:37
     * @return java.lang.Integer
     **/
    public Integer noReadNum(Integer teacherid) {
        return noticeMapper.noReadNum(teacherid);
    }

    //通知学生--网页--列表
    public List<NoticeVo> listNoticeStuWeb(TNotice notice) {
        return noticeMapper.listNoticeForStuWeb(notice);
    }

    /**
     * @Description 通知对象
     * @Date 2023/12/18 16:26
     * @Author YWX
     * @Param [nu]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listUser(TNoticeUser nu) {
        return noticeUserMapper.listByNoticeId(nu);
    }

    /*
     * @Description 处理班级学生通知
     * @Date 2023/12/18 16:10:36
     * @Author WN
     * @Param []
     * @Return void
     **/
    public void chandleNoticeUser() {
        //获取需要处理的通知
        List<TNoticeClass> noticeClasses = noticeClassMapper.listAll();
        for (TNoticeClass noticeClass : noticeClasses) {
            if(noticeClass.getNoticetitle().contains("作业退回")){
                //说明是退回的作业
                //获取用户所在班级信息
                TNoticeUser noticeUser = noticeClassMapper.getNoticeClassInfo(noticeClass.getClassid());
                if(noticeUser!=null){
                    noticeUser.setNoticeid(noticeClass.getNoticeid());
                    noticeUser.setReaded(1);
                    noticeUser.setCreatetime(noticeClass.getCreatetime());
                    noticeUserMapper.insert(noticeUser);
                }else{
                    noticeMapper.deleteNotice(noticeClass.getNoticeid());
                }
            }else{
                List<TNoticeUser> noticeUsers = noticeClassMapper.listClassStudent(noticeClass.getClassid());
                if (N_Utils.isListNotEmpty(noticeUsers)) {
                    for (TNoticeUser user : noticeUsers) {
                        user.setNoticeid(noticeClass.getNoticeid());
                        user.setReaded(1);
                        user.setCreatetime(noticeClass.getCreatetime());
                    }
                    noticeUserMapper.insertList(noticeUsers);
                }
            }
        }
    }

    /**
     * @Description 获取通知科目和班级
     * @Date 2023/12/25 14:19
     * @Author YWX
     * @Param [noticeid]
     * @Return java.util.Map
     **/
    public Map listSubjectAndClass(Integer noticeid) {
        Map<String, Object> map = new LinkedHashMap<>();
        List<TNoticeUser> users = noticeUserMapper.listSubjectAndClass(noticeid);
        List<Map<String, Integer>> grades = new ArrayList<>();
        List<Map<String, Object>> subjects = new ArrayList<>();
        List<NoticeClassVo> classes = new ArrayList<>();
        for (TNoticeUser user : users) {
            String subjectid = user.getSubjectid();
            Integer gradeid = user.getGradeid();
            Map<String, Integer> g = new LinkedHashMap<>();
            g.put("gradeid", gradeid);
            grades.add(g);
            String[] username = user.getUsername().split("_");
            if (N_Utils.isEmpty(subjectid)) {
                NoticeClassVo c = new NoticeClassVo();
                c.setGradeid(gradeid);
                c.setClassid(user.getClassid());
                c.setClassname(username[0]);
                String[] typeOrder = username[1].split("-");
                c.setClasstype(N_Utils.str2Int(typeOrder[0]));
                c.setClassorder(N_Utils.str2Int(typeOrder[1]));
                classes.add(c);
            } else {
                Map<String, Object> sc = new LinkedHashMap<>();
                sc.put("subjectid", subjectid);
                sc.put("subjectname", username[0]);
                sc.put("subjectorder", username[1]);
                subjects.add(sc);
            }
        }
        grades.sort(Comparator.comparing(m -> m.get("gradeid")));
        subjects.sort(Comparator.comparing(m -> N_Utils.str2Int(m.get("subjectorder").toString())));
        classes = classes.stream().sorted(
                Comparator.comparingInt(NoticeClassVo::getGradeid)
                          .thenComparing(NoticeClassVo::getClasstype)
                          .thenComparing(NoticeClassVo::getClassorder)
                          .thenComparing(NoticeClassVo::getClassname)
        ).collect(Collectors.toList());
        map.put("grades", grades.stream().distinct().collect(Collectors.toList()));
        map.put("subjects", subjects.stream().distinct().collect(Collectors.toList()));
        map.put("classes", classes);
        return map;
    }

    /*
     * @Description 获取通知id是否存在
     * @Date 2024/1/15 17:43:12
     * @Author WN
     * @Param [noticeid]
     * @Return boolean
     **/
    public boolean getNoticeid(Integer noticeid){
        Integer findid = noticeMapper.getNoticeid(noticeid);
        return N_Utils.isTrueInteger(findid);
    }

    /*
     * @Description 获取通知教师查看情况
     * @Date 2024/6/19 10:31:08
     * @Author WN
     * @Param [noticeUser]
     * @Return java.util.Map
     **/
    public List<Map> noticeReadTeacher(TNoticeUser noticeUser) {
        return noticeMapper.listNoticeTeacherRead(noticeUser);
    }

    /*
     * @Description 获取通知学生查看情况
     * @Date 2024/6/19 10:31:08
     * @Author WN
     * @Param [noticeUser]
     * @Return java.util.Map
     **/
    public List<Map> noticeReadStudent(TNoticeUser noticeUser) {
        return noticeMapper.listNoticeStudentRead(noticeUser);
    }

    /*
     * @Description 获取学生通知科目
     * @Date 2024/7/9 16:33:37
     * @Author WN
     * @Param [studentid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listNoticeSubjects(Integer studentid){
        List<Map> rtnList = noticeMapper.listNoticeSubjects(studentid);
        boolean qt = false;
        int index = 0;
        for(int i = 0;i<rtnList.size();i++){
            if(N_Utils.isEmpty(rtnList.get(i))){
                qt = true;
                index = i;
                break;
            }
        }
        if(qt){
            rtnList.remove(index);
            Map map = new HashMap();
            map.put("subjectid","qt");
            map.put("subjectname","其他");
            rtnList.add(map);
        }
        return rtnList;
    }
}
