package com.xhkjedu.sapi.service.research;

import com.xhkjedu.model.BaseBean;
import com.xhkjedu.sapi.listener.MessageSender;
import com.xhkjedu.sapi.mapper.research.ResearchMapper;
import com.xhkjedu.sapi.mapper.research.ResearchUserMapper;
import com.xhkjedu.sapi.model.notice.TNotice;
import com.xhkjedu.sapi.model.research.TResearch;
import com.xhkjedu.sapi.model.research.TResearchUser;
import com.xhkjedu.sapi.service.notice.NoticeService;
import com.xhkjedu.sapi.vo.research.RteacherOtherVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.sapi.vo.notice.NoticeUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @ClassName ResearchService
 * Description TODO
 * Author WN
 * Date 2020/6/11 18:06
 **/
@Slf4j
@Service
public class ResearchService {
    @Resource
    private ResearchMapper researchMapper;
    @Resource
    private ResearchUserMapper researchUserMapper;
    @Resource
    private NoticeService noticeService;
    @Resource
    private MessageSender messageSender;

    /**
     * 功能描述  列表--所有教研
     *
     * @param *      @param schoolid
     * @param rorder
     * @return java.util.List<com.xhkjedu.vo.research.ResearchVo>
     * @author WN
     * @date 2020/6/11
     */
    public List<Map<String, String>> listResearchs(Integer schoolid, String rorder) {
        return researchMapper.listResearchs(schoolid, rorder);
    }

    /**
     * 功能描述  保存信息
     *
     * @param * @param research
     * @return void
     * @author WN
     * @date 2020/6/11
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer save(TResearch research) {
        int timestamp = N_Utils.getSecondTimestamp();
        research.setCreatetime(timestamp);
        research.setReadnum(0);

        List<TResearchUser> rslist = new ArrayList<>();

        List<Map<String, Integer>> teacherids = research.getTeacherids();
        Set<Integer> userids = new HashSet<>();
        //集合去重
        for (Map<String, Integer> u : teacherids) {
            TResearchUser ru = new TResearchUser();
            ru.setResearchid(research.getId());
            Integer teacherid = u.get("teacherid");
            userids.add(teacherid);
            ru.setUserid(teacherid);
            ru.setRustate(0);
            ru.setSchoolid(u.get("schoolid"));
            ru.setCreatetime(timestamp);

            rslist.add(ru);
        }
        long count = rslist.stream().filter(r -> !research.getSchoolid().equals(r.getSchoolid())).count();
        int hashb = 0;
        if (count != 0) hashb = 1;
        research.setHashb(hashb);
        researchMapper.insertUseGeneratedKeys(research);


        if( research.getNotice() == 1){//发送通知
            List<NoticeUserVo> teachers = new ArrayList<>();
            TNotice notice = new TNotice();
            notice.setNoticetitle(research.getResearchname());
            notice.setNoticecontent(research.getResearchcontent());
            notice.setNoticetxt(research.getResearchcontent());
            notice.setNoticetype(2);
            notice.setCreateid(research.getCreateid());
            notice.setSchoolid(research.getSchoolid());

            //获取用户的id对应的用户年级和科目信息
            List<RteacherOtherVo> teaInfos = researchUserMapper.listResearchTeacherOthers(userids);
            Map<Integer,RteacherOtherVo> teacherMap = teaInfos.stream().collect(Collectors.toMap(RteacherOtherVo::getTeacherid, a -> a,(k1,k2)->k1));
            userids.forEach(uid->{
                NoticeUserVo nt = new NoticeUserVo();
                nt.setUserid(uid);
                if (teacherMap != null) {
                    RteacherOtherVo rt = teacherMap.get(uid);
                    if (rt != null) {
                        nt.setGradeid(rt.getGradeid());
                        nt.setSubjectid(rt.getSubjectid());
                    }
                }
                teachers.add(nt);
            });
            notice.setUsers(teachers);
            noticeService.save(notice);
        }

        //批量保存教研老师关联信息
        researchUserMapper.saveBatchResearchUser(rslist, research.getId());
        research.setResearchid(research.getId());
        convertVideo(research);//视频转换mq
        return research.getId();
    }

    /**
     * 功能描述  修改教研信息
     *
     * @param * @param research
     * @return void
     * @author WN
     * @date 2020/6/11
     */
    public void update(TResearch research) {
        researchMapper.updateResourch(research);
    }

    /**
     * 功能描述 删除
     *
     * @param * @param researchid
     * @return java.lang.Integer
     * @author WN
     * @date 2020/6/11
     */
    public Integer del(Integer researchid) {
        TResearch research = researchMapper.getResarchpath(researchid);
        Integer result = researchMapper.deleteByPrimaryKey(researchid);
        List<String> resourceUrls = new ArrayList<>();
        if(research != null && N_Utils.isNotEmpty(research.getResearchcover())){
            resourceUrls.add(research.getResearchcover());
        }
        if(research != null && N_Utils.isNotEmpty(research.getResearchpath())){
            resourceUrls.add(research.getResearchpath());
        }
        if(N_Utils.isListNotEmpty(resourceUrls)){
            messageSender.resourceDel(resourceUrls);//给文件服务器发送mq删除文件
        }
        return result;
    }

    /**
     *功能描述  详情
     * @author WN
     * @date 2020/6/11
     * @param  * @param researchid
     * @param schoolid
     * @return com.xhkjedu.model.research.TResearch
     */
    public TResearch getResearchById(Integer researchid, Integer schoolid) {
        List<TResearchUser> teachers = researchUserMapper.listRuserIdByResearchid(researchid);
        Map<Integer, List<TResearchUser>> collect = teachers.stream().collect(
                Collectors.groupingBy(TResearchUser::getSchoolid, LinkedHashMap::new, Collectors.toList()));
        List<Map<String, Object>> schools = new ArrayList<>();
        for (Map.Entry<Integer, List<TResearchUser>> entry : collect.entrySet()) {
            List<TResearchUser> users = entry.getValue();
            Integer key = entry.getKey();
            Map<String, Object> s = new HashMap<>();
            s.put("schoolid", key);
            s.put("schoolname", users.get(0).getSchoolname());
            List<String> wcyList = users.stream().filter(u -> u.getRustate().equals(0)).map(BaseBean::getCreatename).collect(Collectors.toList());
            List<String> ycyList = users.stream().filter(u -> u.getRustate().equals(1)).map(BaseBean::getCreatename).collect(Collectors.toList());
            s.put("cyrate", N_Utils.getIntegerDivideAndMulitiply(ycyList.size(), users.size()));
            s.put("wcyList", wcyList);
            s.put("ycyList", ycyList);
            schools.add(s);
        }
        Map<String, Object> school = schools.stream().filter(s->s.get("schoolid").equals(schoolid)).findFirst().orElse(null);
        if (school != null) {
            schools.remove(school);
            schools.add(0, school);
        }
        TResearch research = researchMapper.getResearchById(researchid);
        research.setSchools(schools);
        convertVideo(research);//视频转换mq
        return research;
    }

    //视频转换mq
    private void convertVideo(TResearch research) {
        if (!"h264".equals(research.getMp4code())) {
            messageSender.convertVideo(research.getResearchid(), research.getResearchpath());
        }
    }

    /**
     *功能描述  修改教研mp4code
     * @author WN
     * @date 2020/8/25
     * @param  * @param research
     */
    public void updateResourceMp4code(TResearch research){
        researchMapper.updateResourceMp4code(research);
    }

    /**
     * @Description 获取学校下用户教研评价
     * @Param [researchid, schoolid]
     * @Author ywx
     * @Date 2023/7/24 9:08
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.String>>
     **/
    public List<Map<String, String>> listUserByRidAndSid(Integer researchid, Integer schoolid, Integer userid) {
        return researchUserMapper.listUserByRidAndSid(researchid, schoolid, userid);
    }

    /*
    * @Description 移除用户已评论教研
    * @Author WN
    * @Date 2023/8/8 15:34:52
    */
    public Integer delTeacherResearch(Integer ruid){
        return researchUserMapper.delTeacherResearch(ruid);
    }
}
