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

import cn.estsh.i3plus.core.api.iservice.busi.ISysTaskPlanService;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ImppEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysMessage;
import cn.estsh.i3plus.pojo.platform.bean.SysTaskPlan;
import cn.estsh.i3plus.pojo.platform.platbean.SysLogTaskTime;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
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-12-20 21:56
 * @Modify:
 **/
@ConditionalOnExpression("'${impp.mq.queue.schedule}' == 'true'")
@Component
public class ScheduleQueueReceiver {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleQueueReceiver.class);

    @Autowired
    private ISysTaskPlanService sysTaskPlanService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 定时任务通道处理
     * @param logTaskTime
     * @param channel
     * @param message
     */
    @RabbitListener(queues = PlatformConstWords.IMPP_SCHEDULE_QUEUE)
    public void processSchedule(SysLogTaskTime logTaskTime, Channel channel, Message message) {
        try {
            LOGGER.info("【MQ-IMPP_SCHEDULE_QUEUE】数据接收成功：{}",logTaskTime);
            // 跟新最后执行时间 及 任务状态
            SysTaskPlan taskPlan = sysTaskPlanService.getSysTaskPlanByNameAndGroup(logTaskTime.getName(),logTaskTime.getGroupName());
            if (taskPlan != null) {
                taskPlan.setLastRunDateTime(logTaskTime.getCreateDatetime());
                taskPlan.setTaskPlanExecNum(taskPlan.getTaskPlanExecNum() + 1);
                taskPlan.setTaskPlanStatus(logTaskTime.getTaskStatus());
                // 更新任务状态以及最后执行时间
                sysTaskPlanService.updateSysTaskPlan(taskPlan);

                // 添加定时任务日志
                logTaskTime.setTaskPlanId(taskPlan.getId());
                logTaskTime.setTaskCycleNameRdd(taskPlan.getTaskCycleNameRdd());
                logTaskTime.setTaskCycleExpsRdd(taskPlan.getTaskCycleExpsRdd());
                sysTaskPlanService.logInsertSysLogTaskTime(logTaskTime);

                // 定时任务失败通知
                if (CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == logTaskTime.getTaskStatus()
                        && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == taskPlan.getIsNotice()) {
                    // 设置通知邮件内容
                    SysMessage sysMessage = new SysMessage();
                    sysMessage.setMessageSenderNameRdd("系统管理员");
                    sysMessage.setMessageTitle("任务计划失败通知");
                    sysMessage.setMessageContent(
                            String.format("<p>管理员 您好：</p><div style=\"text-align:center\">任务计划(Name: %s,GroupName: %s）执行失败,详细信息请查看定时任务日志(ID: %s).</div>",
                                    taskPlan.getName(),taskPlan.getGroupName(),logTaskTime.getId())
                    );
                    sysMessage.setMessageContentType(ImppEnumUtil.MESSAGE_TYPE_CONTENT.HTML.getValue());
                    sysMessage.setMessageSendTime(TimeTool.getNowTime(true));
                    sysMessage.setIsSystem(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());

                    // 是否内部成员
                    if (CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == taskPlan.getIsInternalUser()) {
                        sysMessage.setMessageReceiverType(ImppEnumUtil.MESSAGE_RECEIVER_TYPE.EXTERNAL.getValue());
                        sysMessage.setMessageReceiversNameRdd(taskPlan.getNoticeChannel());
                    }else{
                        sysMessage.setMessageReceiverType(ImppEnumUtil.MESSAGE_RECEIVER_TYPE.INTERNAL.getValue());
                    }

                    // 发送到对应处理队列
                    if(taskPlan.getNoticeMethod() != null  && ImppEnumUtil.MESSAGE_TYPE.MAIL.getValue() == taskPlan.getNoticeMethod().intValue()){
                        rabbitTemplate.convertAndSend(PlatformConstWords.IMPP_MESSAGE_MAIL_QUEUE,sysMessage);
                    }else{
                        rabbitTemplate.convertAndSend(PlatformConstWords.IMPP_MESSAGE_LETTER_QUEUE,sysMessage);
                    }
                }
            }

            //信息已处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            LOGGER.error("【MQ-IMPP_MESSAGE_MAIL_QUEUE】处理出错：{}",e.getMessage(),e);
            //丢弃这条消息
            try {
                // 未成功处理，重新发送
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
