package com.yeejoin.amos.boot.module.jyjc.biz.kafka;

import com.yeejoin.amos.boot.module.jyjc.api.common.BizCommonConstant;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionApplicationPushLog;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcInspectionApplicationPushLogServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * @author Administrator
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class KafkaProducer {

    private final KafkaTemplate<String, String> kafkaTemplate;

    private final JyjcInspectionApplicationPushLogServiceImpl pushLogService;


    /**
     * 发送消息（异步）
     *
     * @param topic   主题
     * @param message 消息内容
     */
    public void sendMessageWithLog(String topic, String message, JyjcInspectionApplicationPushLog pushLog) {
        if (log.isInfoEnabled()) {
            log.info("kafka开始发送数据：主题:{}，消息{}", topic, message);
        }
        try {
            ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, message);
            future.addCallback(result -> {
                if (log.isInfoEnabled()) {
                    if (result != null) {
                        log.info("Kafka发送成功! 主题: {}, 分区: {}, Offset: {}", topic, result.getRecordMetadata().partition(), result.getRecordMetadata().offset()
                        );
                    }
                }
                updatePushLogStatus(pushLog, BizCommonConstant.PUSH_STATUS_SUCCESS, null);
            }, ex -> {
                log.error("Kafka发送失败! 主题: {}, 消息: {}", topic, message, ex);
                updatePushLogStatus(pushLog, BizCommonConstant.PUSH_STATUS_FAILED, ex.getMessage());
                throw new RuntimeException("Kafka消息发送失败", ex);  // 触发事务回滚（需配合事务配置）
            });
        } catch (Exception e) {
            // 同步阶段即失败（如Topic不存在、Broker宕机）
            log.error("Kafka同步发送失败! 主题: {}, 消息丢弃", topic, e);
            updatePushLogStatus(pushLog, BizCommonConstant.PUSH_STATUS_FAILED, e.getMessage());
        }
    }

    private void updatePushLogStatus(JyjcInspectionApplicationPushLog pushLog, String status, String errorMsg) {
        try {
            pushLog.setPushStatus(status);
            pushLog.setRemark(errorMsg);
            pushLogService.updateById(pushLog);
        } catch (Exception e) {
            log.error("更新推送日志状态失败! ID: {}", pushLog.getSequenceNbr(), e);
            throw e;
        }
    }
}