package net.northking.cctp.executePlan.bus;

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.executePlan.db.entity.AtuPlanScriptLink;
import net.northking.cctp.executePlan.db.service.AtuPlanInfoService;
import net.northking.cctp.executePlan.db.service.AtuPlanScriptLinkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.amqp.core.Message;

import java.util.*;

@Component
public class ScriptReceiver {

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

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AtuPlanScriptLinkService planScriptLinkService;

    @Autowired
    private AtuPlanInfoService planInfoService;

    @RabbitListener(queuesToDeclare = {@Queue(value = "Plan.Update.Status.REQ")})
    public void process(Message message) {
        String scriptId = "";
        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 {
            scriptId = objectMapper.readValue(message.getBody(), new TypeReference<String>() {
            });
            NKSecurityContext.setUserId(userId);
            NKSecurityContext.setTenantId(tenantId);
            AtuPlanScriptLink link = new AtuPlanScriptLink();
            link.setScriptId(scriptId);
            List<AtuPlanScriptLink> query = planScriptLinkService.query(link);
            Set<String> planSet = new HashSet<>();
            for (AtuPlanScriptLink scriptLink : query) {
                planSet.add(scriptLink.getPlanId());
            }
            if (planSet.size()>0) {
                //更新计划状态
                planInfoService.updatePlanByIds(new ArrayList<>(planSet));
            }
        }catch (Exception e){
            logger.error("更新计划状态异常:", e);
        }
    }
}
