package org.ta.pddserver.rabbit;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.ta.pddserver.entity.YjtLogEntity;
import org.ta.pddserver.service.impl.YjtLogImpl;
import org.ta.pddserver.utils.YjtHttpTool;

import java.util.Date;

//@Component
@Slf4j
public class RabbitYJTSender {
    private static final String SEND_TO_YJT = "SEND_TO_YJT";
    private static final String SAVE_FROM_YGT = "SAVE_FROM_YGT";

    @Resource
    AmqpAdmin amqpAdmin;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    YjtLogImpl yjtLogImpl;

    @PostConstruct
    public void init() {
        // 声明QUEUE
        amqpAdmin.declareQueue(new Queue(SEND_TO_YJT));
        amqpAdmin.declareQueue(new Queue(SAVE_FROM_YGT));
    }

    /**
     * 将拼多多发送过来的消息发送给Yjt
     *
     * @param msg 待转发消息信息
     */
    public void mqSendToYJTFromPdd(String msg) {
        rabbitTemplate.convertAndSend(SEND_TO_YJT, msg);
    }

    /**
     * 异步保存来自Yjt的信息
     *
     * @param msg 待转发消息信息
     */
    public void mqSaveMsgFromYjt(String msg, String ip) {
        rabbitTemplate.convertAndSend(SAVE_FROM_YGT, msg + "~~" + ip);
    }

    /**
     * 转发消息
     *
     * @param message 消息信息
     */
    @RabbitListener(queues = SEND_TO_YJT)
    public void handleSendToYJTFromPdd(Message message) {
        String msg = new String(message.getBody());
        YjtHttpTool.sendJsonPost(msg);
    }

    /**
     * 异步保存来自Yjt的信息
     *
     * @param message 消息信息
     */
    @RabbitListener(queues = SEND_TO_YJT)
    public void handleSaveMsgFromYjt(Message message) {
        String msg = new String(message.getBody());
        String[] msgs = msg.split("~~");
        YjtLogEntity yjtLogEntity = new YjtLogEntity();
        yjtLogEntity.setMsg(msgs[0]);
        yjtLogEntity.setIp(msgs[1]);
        yjtLogEntity.setTime(new Date());
        if (!yjtLogImpl.save(yjtLogEntity)) {
            log.error("日志保存失败，内容为:\n" + msg);
        }

    }


}
