package com.persagy.bdtp.adm.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.bdtp.adm.common.AdmConst;
import com.persagy.bdtp.adm.common.AdmMessageConst;
import com.persagy.bdtp.adm.dao.AdmMessagePMapper;
import com.persagy.bdtp.adm.entity.db.AdmMessageP;
import com.persagy.dmp.amqp.handler.AbstractRabbitHandlerTemplate;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
@RabbitListener(queues = AdmMessageConst.M2D_QUEUE)
public class M2DMessageHandler extends AbstractRabbitHandlerTemplate {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AdmMessagePMapper messageMapper;

    /**
     * 消费
     * @param message 消息体字符串
     * @param channel 通道对象
     * @param vo     消息对象
     */
    @Override
    protected void handler(String message, Channel channel, Message vo) {
        Map<String, Object> msg = null;
        try {
            msg = objectMapper.readValue(message, Map.class);
        }catch (IOException e){
            throw new RuntimeException(e);
        }

        if(msg != null)
            handleD2mReply(msg);
    }

    private void handleD2mReply(Map<String, Object> reply){
        String id = (String) reply.get("id");
        String result = (String) reply.get("result");
        Object content = reply.get("content");

        AdmMessageP message = messageMapper.selectById(id);
        if (message != null) {
            boolean flag = "success".equals(result);

            message.setStatus(flag ? AdmConst.UPLOAD_FINISHED : AdmConst.UPLOAD_ERROR);
            message.setReturnContent(content);
            message.setReturnTime(new Timestamp(new Date().getTime()));
            messageMapper.updateById(message);

            if(!flag)
                handleD2mError();
        }
    }

    private void handleD2mError(){
        //TODO
    }

}
