package com.mcwl.resource.consumer;



import com.mcwl.common.constant.QueueConstants;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.resource.domain.*;
import com.mcwl.resource.domain.dto.SysAdviceDto;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MsgConsumer {

    private final ISysAdviceService sysAdviceService;

    private final ISysUserService sysUserService;

    /**
     * 发送系统通知消息
     */
    @RabbitListener(queues = QueueConstants.SYS_MSG_QUEUE, ackMode = "MANUAL")
    @Transactional(rollbackFor = Exception.class)
    public void sendSysMsg(SysAdviceDto sysAdviceDto, Channel channel, Message message) {
        try {
            SysUser adminUser = sysUserService.selectUserByUserName("admin");
            Long sendId = adminUser.getUserId();
            List<SysUser> sysUserList = sysUserService.list();
            List<SysAdvice> sysAdviceList = new ArrayList<>();
            for (SysUser sysUser : sysUserList) {
                Long receiverId = sysUser.getUserId();
                SysAdvice sysAdvice = new SysAdvice();
                sysAdvice.setSenderId(sendId);
                sysAdvice.setReceiverId(receiverId);
                sysAdvice.setTitle(sysAdviceDto.getTitle());
                sysAdvice.setContent(sysAdviceDto.getContent());
                sysAdvice.setIsRead(0);
                sysAdvice.setType(AdviceEnum.SYSTEM_NOTICE);
                sysAdviceList.add(sysAdvice);
            }
            sysAdviceService.saveBatch(sysAdviceList);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("系统通知消息时出错: {}", e.getMessage(), e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                log.error("消息确认失败: {}", ex.getMessage(), ex);
            }
        }
    }

}
