package net.northking.cctp.testbug.bus.receive;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.testbug.api.service.BugManagementApiService;
import net.northking.cctp.testbug.bus.constants.MQConstants;
import net.northking.cctp.testbug.dto.bus.SynModule;
import net.northking.cctp.testbug.dto.bus.SynSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: puchao.ma
 * @date: 2021/11/12 14:55
 */
@Component
public class MQNotice {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BugManagementApiService bugManagementApiService;

    private final Logger logger = LoggerFactory.getLogger(MQNotice.class);

    /**
     * 接受项目名更新信息并同步至缺陷数据中
     */
    @RabbitListener(queuesToDeclare = {
            @Queue(value = MQConstants.Queue.Q_Platform_Notice_TestBug_REQ)
    })
    public void synSystemNotice(Message message) {
        SynSystem data = new SynSystem();
        try {
            MessageProperties mp = message.getMessageProperties();
            Map<String, Object> headers = mp.getHeaders();
            String userId = headers.get(MQConstants.Key_CCTP_User_ID).toString();  // 创建人
            String tenantId = headers.get(MQConstants.Key_SaaS_Tenant_ID).toString();  // 租户id

            data = objectMapper.readValue(message.getBody(), SynSystem.class);
            data.setTenantId(tenantId);
            data.setUpdatedBy(userId);
        } catch (Exception e) {
            logger.error("synSystemNotice", e);
        }
        bugManagementApiService.synchronizationSystem(data);
    }

    /**
     * 接受模块名更新信息并同步至缺陷数据中
     * @param message
     */
    @RabbitListener(queuesToDeclare = {
            @Queue(value = MQConstants.Queue.Q_ManualCases_Notice_TestBug_REQ)
    })
    public void synModuleNotice(Message message) {
        SynModule data = new SynModule();
        try {
           data = objectMapper.readValue(message.getBody(), SynModule.class);
        } catch (Exception e) {
            logger.error("synModuleNotice", e);
        }
        bugManagementApiService.synchronizationModule(data);
    }
}
