package com.yeejoin.amos.boot.module.jyjc.biz.event.publisher;

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgInspectionDetectionInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Component
@Slf4j
@Getter
public class BizEmqPublisher {

    private final EmqKeeper emqKeeper;

    public BizEmqPublisher(EmqKeeper emqKeeper) {
        this.emqKeeper = emqKeeper;
    }

    /**
     * 检验检测结果入库消息
     */
    private static final String INSPECTION_DETECTION_SAVE_TO_DB_TOPIC_PREFIX = "safetyProblemTracing/jy/bj";
    private static final String INSPECTION_DETECTION_SAVE_TO_DB_TOPIC_TYPE_UPDATE = "update";

    public void sendInspectionMsgAfterSave(IdxBizJgInspectionDetectionInfo info, String type) {
        try {
            if (emqKeeper.getMqttClient() == null) {
                return;
            }
            // 安全追溯目前只需要type=update的信息
            if (INSPECTION_DETECTION_SAVE_TO_DB_TOPIC_TYPE_UPDATE.equals(type)) {
                List<IdxBizJgInspectionDetectionInfo> list = new ArrayList<>();
                list.add(info);
                emqKeeper.getMqttClient().publish(this.buildSave2DbEmqTopic(type), JSON.toJSONBytes(list), 2, false);
            }
        } catch (MqttException e) {
            log.error("发送检验检测信息入库消息失败", e);
        }
    }

    private String buildSave2DbEmqTopic(String type) {
        return String.format("%s/%s", INSPECTION_DETECTION_SAVE_TO_DB_TOPIC_PREFIX, type);
    }
}
