package com.yida.data.school.news.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.notice.EduNoticeSystem;
import com.yida.data.common.core.entity.notice.EduNoticeSystemUser;
import com.yida.data.msg.dto.WebsocketMsgDTO;
import com.yida.data.rabbit.constant.RabbitConstant;
import com.yida.data.rabbit.util.RabbitUtil;
import com.yida.data.school.dto.news.SysNoticeSaveDTO;
import com.yida.data.school.news.mapper.EduNoticeSystemMapper;
import com.yida.data.school.news.service.EduNoticeSystemService;
import com.yida.data.school.news.service.EduNoticeSystemUserService;
import com.yida.data.school.vo.news.SysNoticeInfoVO;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RequiredArgsConstructor
public class EduNoticeSystemServiceImpl extends ServiceImpl<EduNoticeSystemMapper, EduNoticeSystem> implements
    EduNoticeSystemService {

    private final EduNoticeSystemUserService eduNoticeSystemUserService;
    private final RabbitUtil rabbitUtil;

    @Override
    public IPage<SysNoticeInfoVO> listNoticePage(Long userId, Integer pageNum, Integer pageSize) {
        IPage<SysNoticeInfoVO> res = baseMapper
            .listNoticePage(Page.of(pageNum, pageSize), userId);
        if (CollUtil.isNotEmpty(res.getRecords())) {
            eduNoticeSystemUserService.update(Wrappers.<EduNoticeSystemUser>lambdaUpdate()
                .in(EduNoticeSystemUser::getId,
                    res.getRecords().stream().map(SysNoticeInfoVO::getMsgId).collect(Collectors.toList()))
                .set(EduNoticeSystemUser::getReadFlag, 1));
        }
        return res;
    }

    @Override
    public Boolean existNewMsg(Long userId) {
        return baseMapper.existNewMsg(userId) != null;
    }

    @Override
    public void saveNotice(SysNoticeSaveDTO dto) {
        EduNoticeSystem notice = new EduNoticeSystem();
        notice.setCreateDate(dto.getCreateDate());
        notice.setContent(dto.getContent());
        save(notice);
        for (Long userId : dto.getUserId()) {
            EduNoticeSystemUser noticeUser = new EduNoticeSystemUser();
            noticeUser.setNoticeId(notice.getId());
            noticeUser.setUserId(userId);
            eduNoticeSystemUserService.save(noticeUser);
            // websocket通知
            WebsocketMsgDTO msg = new WebsocketMsgDTO();
            msg.setUserId(userId);
            msg.setContent(dto.getContent());
            rabbitUtil.convertAndSendMsg(RabbitConstant.MSG_EXCHANGE, RabbitConstant.MSG_WEBSOCKET_KEY, msg);
        }
    }
}

