package com.mcwl.memberCenter.consumer;

import com.mcwl.common.constant.QueueConstants;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.memberCenter.domain.Member;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.resource.service.ISysAdviceService;
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 java.io.IOException;

/**
 * 会员账单消费者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MemberBillingConsumer {

    private final ISysAdviceService sysAdviceService;

    private final ISysUserService sysUserService;

    /**
     * 会员账单
     */
    @RabbitListener(queues = QueueConstants.MEMBER_BILLING_QUEUE, ackMode = "MANUAL")
    public void memberBillingQueue(Member member, Channel channel, Message message) {
        try {
            // TODO 发送短信提醒用户会员账单，如果支付成功，更新last_payment_date，并重新计算end_date（start_date + 1个月）
            SysUser sysUser = sysUserService.selectUserByUserName("admin");
            SysAdvice sysAdvice = new SysAdvice();
            sysAdvice.setSenderId(sysUser.getUserId());
            sysAdvice.setReceiverId(member.getUserId());
            sysAdvice.setType(AdviceEnum.SYSTEM_NOTICE);
            sysAdvice.setTitle("会员账单");
            sysAdvice.setContent("您的会员即将到期，请及时支付");
            sysAdviceService.save(sysAdvice);
            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);
            }
        }
    }

}
