package com.zksy.data.listener;

import com.zksy.data.service.XhDataLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Optional;

@Configuration
@Slf4j
public class LogListener {
    @Autowired
    private XhDataLogService xhDataLogService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = "delay"
    ))
    public void listenDelayIdForLog(String id){
        Optional.ofNullable(id)
                .flatMap(i -> Optional.ofNullable(xhDataLogService.getById(i)))
                .filter(log -> System.currentTimeMillis() - log.getCreateTime().getTime() > 7200000L)
                .filter(log -> log.getIsSuccess() == 0)
                .filter(log -> log.getIsRunning() == 1)
                .ifPresent(log -> {
                    log.setIsRunning(0);
                    log.setUseTime((int) (System.currentTimeMillis() - log.getCreateTime().getTime()));
                    log.setUpdateTime(new Date());
                    log.setException("超时异常");
                    xhDataLogService.updateById(log);
                });
        log.info("设置id为：{}的日志为未完成", id);
    }
}
