package org.springblade.mq.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.mq.entity.MqConf;
import org.springblade.mq.enums.Instruct;
import org.springblade.mq.service.MsgPublishService;
import org.springblade.mq.util.RabbitMqConnectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * description:
 */
@Slf4j
@Service
public class MsgPublishServiceImpl implements MsgPublishService {

	@Autowired
	private MqConf mqConf;


	@Override
	@SneakyThrows
	public void publish(Object obj, String routing, Instruct instruct) {

		Connection connection = RabbitMqConnectionUtil.openConnection(mqConf);
		Channel channel = null;
		try {
			//  创建管道
			channel = connection.createChannel();
			//  构建数据
			Map<String,Object> map = new HashMap<>(2);
			map.put("code",instruct.getCode());
			map.put("data",obj);
			String msg = JSON.toJSONString(map, SerializerFeature.WriteNonStringValueAsString, SerializerFeature.WriteDateUseDateFormat);
			channel.basicPublish(instruct.getExchangeName(), routing, null, msg.getBytes(StandardCharsets.UTF_8));
		} finally {
			//  关闭连接,抛出异常
			RabbitMqConnectionUtil.closeConnection(connection,channel);
		}
	}

	@Override
	@SneakyThrows
	public void publishJVT(Object obj, String mac, Instruct instruct) {

		Connection connection = RabbitMqConnectionUtil.openConnection(mqConf);
		Channel channel = null;
		try {
			//  创建管道
			channel = connection.createChannel();
			//  构建数据
			Map<String,Object> map = new HashMap<>(2);
			map.put("id","10086");
			map.put("code",instruct.getCode());
			map.put("data",obj);
			map.put("serialNumber", mac);
			String msg = JSON.toJSONString(map, SerializerFeature.WriteNonStringValueAsString, SerializerFeature.WriteDateUseDateFormat);
			channel.basicPublish(instruct.getExchangeName(), mac, null, msg.getBytes(StandardCharsets.UTF_8));
		} finally {
			//  关闭连接,抛出异常
			RabbitMqConnectionUtil.closeConnection(connection,channel);
		}
	}
}
