package cn.estsh.i3plus.core.apiservice.mq;

import cn.estsh.i3plus.core.api.iservice.busi.ISysConfigService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysMessageService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysUserService;
import cn.estsh.i3plus.core.apiservice.util.MailUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysMessage;
import cn.estsh.i3plus.pojo.platform.bean.SysRefUserMessage;
import cn.estsh.i3plus.pojo.platform.bean.SysUser;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description : 邮件队列处理
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-15 22:15
 * @Modify:
 **/
@ConditionalOnExpression("'${impp.mq.queue.mail}' == 'true'")
@Component
public class MessageMailQueueReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageMailQueueReceiver.class);

    @Autowired
    ISysMessageService sysMessageService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    MailUtil mailUtil;

    /**
     * 系统邮件处理队列
     * @param msg
     * @param channel
     * @param message
     */
    @RabbitListener(queues = PlatformConstWords.IMPP_MESSAGE_MAIL_QUEUE)
    public void processImppMail(SysMessage msg, Channel channel, Message message) {
        try {
            LOGGER.info("【MQ-IMPP_MESSAGE_MAIL_QUEUE】数据接收成功：{}",msg);
            if (msg.getMessageSendTime() == null) {
                msg.setMessageSendTime(TimeTool.getNowTime(true));
            }
            msg = sysMessageService.insertSysMessage(msg);

            // 设置邮件主题内容及收件人
            mailUtil.init();
            mailUtil.setSubject(msg.getMessageTitle());
            mailUtil.setContentType(ImppEnumUtil.MESSAGE_TYPE_CONTENT.valueOfDescription(msg.getMessageContentType()));
            mailUtil.setBody(msg.getMessageContent());

            if(msg.getMessageReceiverType() != null){
                if(msg.getMessageReceiverType().intValue() == ImppEnumUtil.MESSAGE_RECEIVER_TYPE.URGENT.getValue()){
                    // 判断是否为系统紧急提示 微服注册状态提示
                    mailUtil.setTo(sysConfigService.getSysConfigByCode(PlatformConstWords.CONTACT_MAIL).getConfigValue());
                    // 次数过于频繁
//                mailUtil.send();

                } else if(msg.getMessageReceiverType().intValue() == ImppEnumUtil.MESSAGE_RECEIVER_TYPE.EXTERNAL.getValue()){
                    //判断是否为外部邮件
                    mailUtil.setTo(StringUtils.split(msg.getMessageReceiversNameRdd(),","));
                    mailUtil.send();

                } else if (msg.getMessageReceiverType().intValue() == ImppEnumUtil.MESSAGE_RECEIVER_TYPE.INTERNAL.getValue()) {
                    // 收件人信息
                    String[] messageReceiver = msg.getMessageReceiversId().split(",");
                    String[] receiverName = new String[messageReceiver.length];

                    SysRefUserMessage refUserMessage;
                    SysUser sysUser;

                    for (int i = 0; i < messageReceiver.length; i++) {
                        sysUser = sysUserService.getSysUserById(Long.parseLong(messageReceiver[i]));
                        receiverName[i] = sysUser.getUserName();

                        refUserMessage = new SysRefUserMessage();
                        refUserMessage.setMessageId(msg.getId());
                        refUserMessage.setMessageTitleRdd(msg.getMessageTitle());
                        refUserMessage.setMessageTypeRdd(msg.getMessageType());
                        refUserMessage.setMessageSenderNameRdd(msg.getMessageSenderNameRdd());
                        refUserMessage.setReceiverId(sysUser.getId());
                        refUserMessage.setReceiverNameRdd(sysUser.getUserName());
                        refUserMessage.setMessageStatus(ImppEnumUtil.MESSAGE_STATUS.UNREAD.getValue());
                        refUserMessage.setReceiverTime(TimeTool.getNowTime(true));

                        sysMessageService.insertSysRefUserMessage(refUserMessage);

                        mailUtil.setTo(sysUser.getUserEmail());
                        mailUtil.send();
                    }

                    msg.setMessageReceiversNameRdd(StringUtils.join(receiverName, ","));
                    sysMessageService.updateSysMessage(msg);
                }
            }

            //信息已处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            LOGGER.error("【MQ-IMPP_MESSAGE_MAIL_QUEUE】处理出错：{}",e.getMessage(),e);
            //丢弃这条消息
            try {
                // 未成功处理，重新发送
                //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                //todo 此处对邮件持久化，通过参数设置，是否还需要重复重新发送
                // 改为接收成功
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
