package com.tashow.cloud.app.mq.consumer.buriedPoint;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tashow.cloud.app.mapper.BuriedPointMapper;
import com.tashow.cloud.app.mapper.BuriedPointFailRecordMapper;
import com.tashow.cloud.app.model.BuriedPoint;
import com.tashow.cloud.app.model.MqMessageRecord;
import com.tashow.cloud.app.mq.message.BuriedMessages;
import com.tashow.cloud.app.service.feishu.BuriedPointMonitorService;
import com.rabbitmq.client.Channel;
import com.tashow.cloud.mq.rabbitmq.consumer.AbstractRabbitMQConsumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import java.util.Date;
import org.springframework.dao.DuplicateKeyException;
/**
 * 埋点消息消费者
 */
@Component
@RabbitListener(queues = BuriedMessages.QUEUE)
@Slf4j
@RequiredArgsConstructor
public class BuriedPointConsumer extends AbstractRabbitMQConsumer<BuriedMessages> {
    private final BuriedPointMapper buriedPointMapper;
    private final BuriedPointMonitorService buriedPointMonitorService;
    
    @Value("${spring.application.name:tashow-app}")
    private String applicationName;

    @RabbitHandler
    public void handleMessage(BuriedMessages message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        onMessage(message, channel, deliveryTag);
    }

    /**
     * 处理埋点消息
     * @param message 消息对象
     * @return
     */
    @Override
    public boolean processMessage(BuriedMessages message) {
        try {
            BuriedPoint existingPoint = buriedPointMapper.selectByEventId(message.getId());
            if (existingPoint != null) {
                existingPoint.setStatus(message.getStatusCode());
                existingPoint.setUpdateTime(new Date());
                return buriedPointMapper.updateById(existingPoint) > 0;
            }
            BuriedPoint buriedPoint = new BuriedPoint(message);
            buriedPoint.setService(applicationName);
            buriedPointMapper.insert(buriedPoint);
            
            if(buriedPoint.getStatus() == BuriedMessages.STATUS_ERROR){
                buriedPointMonitorService.checkFailRecordsAndAlert("埋点数据处理异常");
            }
            return true;
        } catch (DuplicateKeyException e) {
            return true;
        } catch (Exception e) {
            log.error("[埋点消费者] 保存数据失败", e);
            throw e;
        }
    }
}
