package com.heyu.api.listener;

import com.alibaba.fastjson.JSON;
import com.heyu.api.data.dao.api.ApiPostCodeDao;
import com.heyu.api.data.entity.api.ApiPostCodeEntity;
import com.heyu.api.data.utils.MD5Utils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;

import java.io.IOException;


//@Component
@Slf4j
public class PostCodeQueueSimpleRabbitListener {



    @Autowired
    private ApiPostCodeDao apiPostCodeDao;

    @RabbitHandler
    @RabbitListener(queues = "#{postCodeDataNameQueue.name}", containerFactory = "accountAmountQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        try {
            ApiPostCodeEntity apiPostCodeEntity = JSON.parseObject(message, ApiPostCodeEntity.class);
            String param =
                    apiPostCodeEntity.getParam1()
                    + apiPostCodeEntity.getParam2()
                    + apiPostCodeEntity.getParam3()
                    + apiPostCodeEntity.getParam4()
                    + apiPostCodeEntity.getParam5()
                    + apiPostCodeEntity.getParam6()
                    + apiPostCodeEntity.getParam7()
                    + apiPostCodeEntity.getParam8()
                    + apiPostCodeEntity.getParam9()
                    + apiPostCodeEntity.getParam10()
                    + apiPostCodeEntity.getParam11()
                    + apiPostCodeEntity.getParam12();
            String md5 = MD5Utils.encode(param);
            ApiPostCodeEntity apiPostCodeEntity1 = apiPostCodeDao.selectApiPostCodeByMd5(md5);
            if (apiPostCodeEntity1 != null) {
                return;
            }
            apiPostCodeDao.insertApiPostCode(apiPostCodeEntity);
        } catch (Exception e) {
            log.error("exception e " + message, e);
        } finally {
            try {
                channel.basicAck(delivertTag, true);
            } catch (IOException e) {
                log.error("消息确认异常", e);
            }
        }
    }

}