package net.northking.cctp.flowable.bus.mq;

import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.flowable.bus.BusConstants;
import net.northking.cctp.flowable.dto.sm.SyncCltDictItemDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class FlowPublisher {

    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(FlowPublisher.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 终态发生变化
     * @param spId
     */
    public void finishedChangedSend(String spId, String spName) {
        try {
            MessageBuilder mb = MessageBuilder.withBody(spId.getBytes(StandardCharsets.UTF_8));
            mb.setContentType(MediaType.TEXT_PLAIN_VALUE);
            mb.setHeader(BusConstants.Key_CCTP_User_ID, NKSecurityContext.getUserId());
            mb.setHeader(BusConstants.Key_SaaS_Tenant_ID, NKSecurityContext.getTenantId());
            rabbitTemplate.send(BusConstants.Q_Flow_Finished_REQ, mb.build());
            logger.info("缺陷流程【{}】终结状态发生变化，信息发送成功", spName);
        } catch (Exception e) {
            logger.error("缺陷流程【{}】终结状态发生变化，信息发送失败", spName);
            logger.error("失败堆栈", e);
        }
    }
    /**
     * 状态列表发生变化
     * @param syncCltDictItemDto
     */
    public void stateListChangedSend(SyncCltDictItemDto syncCltDictItemDto) {
        try {
            rabbitTemplate.convertAndSend("flowable.exchange","flow.state.status.list.req", syncCltDictItemDto);
            logger.info("缺陷流程【{}】状态列表发生变化，信息发送成功", syncCltDictItemDto.getBugProcessId());
        } catch (Exception e) {
            logger.error("缺陷流程【{}】状态列表发生变化，信息发送失败", syncCltDictItemDto.getBugProcessId());
            logger.error("失败堆栈", e);
        }
    }
}
