package com.trade.service.contract.queue;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.common.utils.StringUtils;
import com.trade.service.contract.config.RabbitMqConfig;
import com.trade.service.contract.constant.ContractConstant;
import com.trade.service.contract.service.SignPlatformService;
import com.trade.service.contract.util.esign.bizprocess.BizProcessorFactory;
import com.trade.service.contract.util.esign.entity.ESignProcessStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 主要是处理电子签署回调消息，如果当前服务未注册回调处理器工厂，则不需要订阅此队列
 */
@Service
@ConditionalOnBean(BizProcessorFactory.class)
@Slf4j
public class MessageReceiver {

    @Resource
    private Map<String, SignPlatformService> signPlatformServiceMap;

    // e签宝回调消息消费接口
    @RabbitListener(queuesToDeclare = @Queue(RabbitMqConfig.QUEUE_E_SIGN_CALLBACK))
    public void receiveMessage(String message) {
        log.info("Received message: " + message);
        ESignProcessStatus noticeInfo = JSON.parseObject(message, new TypeReference<ESignProcessStatus>() {
        });
        if (null == noticeInfo || StringUtils.isEmpty(noticeInfo.getFlowId())) {
            throw new ServiceException("合同签署流程ID为空", HttpStatus.BAD_REQUEST);
        }
        signPlatformServiceMap.get(ContractConstant.contractStrategyMap.get(ContractConstant.CONTRACT_PLATFORM_ESIGN))
                .handleCallback(noticeInfo);
    }
}
