package net.northking.cctp.dw.bus;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.dw.api.service.ChartApiService;
import net.northking.cctp.dw.constant.DWError;
import net.northking.cctp.dw.constant.MQConstant;
import net.northking.cctp.dw.db.service.MidProjectInfoService;
import net.northking.cctp.dw.dto.CpProject;
import net.northking.cctp.dw.dto.MidProjectInfoAddDto;
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.List;

@Component
public class MQNotice {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MidProjectInfoService midProjectInfoService;

    @Autowired
    private ChartApiService chartApiService;

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

    @RabbitListener(queuesToDeclare = {
            @Queue(value = MQConstant.Queue.Q_Project_Notice_Time_REQ)
    })
    public void synProjectNotice(Message message) {
        MidProjectInfoAddDto dto = new MidProjectInfoAddDto();
        try {
            CpProject data = objectMapper.readValue(message.getBody(), CpProject.class);
            dto.setStartTime(data.getStartTime());
            dto.setProjectId(data.getId());
            dto.setProductionTime(data.getProductionTime());
        } catch (Exception e) {
            logger.error("synSystemNotice", e);
            throw new PlatformRuntimeException(DWError.MQ_SYNC_PROJECT_INFO_FAILED, e);
        }
        MessageProperties mp = message.getMessageProperties();
        String tenantId = mp.getHeaders().get(MQConstant.Key_SaaS_Tenant_ID).toString();
        NKSecurityContext.setTenantId(tenantId);
        midProjectInfoService.addOrUpdateInfo(dto);
    }

    @RabbitListener(queuesToDeclare = {
            @Queue(value = MQConstant.Queue.Q_Project_Notice_Delete_REQ)
    })
    public void deployDeleteProject(Message message) {
        try {
            List<String> projectIds = objectMapper.readValue(message.getBody(), List.class);
            //  逻辑删除系统
            midProjectInfoService.deleteByProjectIds(projectIds);
        } catch (Exception e) {
            logger.error("deployDeleteProject", e);
            throw new PlatformRuntimeException(DWError.MQ_SYNC_PROJECT_INFO_FAILED, e);
        }
    }

}
