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

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.platform.api.log.service.CpLogApiService;
import net.northking.cctp.platform.bus.BusConstants;
import net.northking.cctp.platform.dto.log.CpLogAddDto;
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;

@Component
public class LogReceiver {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(LogReceiver.class);

    @Autowired
    private CpLogApiService cpLogService;

    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queuesToDeclare = {@Queue(value = BusConstants.Q_Platform_Log_Insert_REQ)})
    public void process(Message message) {

        CpLogAddDto cpLogAddDto;
        MessageProperties mp = message.getMessageProperties();
        Map<String, Object> headers = mp.getHeaders();
        String userId = (String) headers.get(BusConstants.Key_CCTP_User_ID);  // 创建人
        String tenantId = (String) headers.get(BusConstants.Key_SaaS_Tenant_ID);  // 租户id
        try {
            cpLogAddDto = objectMapper.readValue(message.getBody(), new TypeReference<CpLogAddDto>() {
            });
            NKSecurityContext.setUserId(userId);
            NKSecurityContext.setTenantId(tenantId);
            NKSecurityContext.setDomains("");

            cpLogService.add(cpLogAddDto);
        }catch (Exception e){
            logger.error("生成日志发生异常", e);
        }
    }
}
