package org.springblade.mqtt;


import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

/**
 * java开发（采用Future模式） 订阅主题
 */
@Component
public class MyMqttClient {

	public static MqttClient mqttClient = null;
	private static MemoryPersistence memoryPersistence = null;
	private static MqttConnectOptions mqttConnectOptions = null;
	public static TendaConfig myTendaConfig = null;
	public static MqttRecieveCallback mymqttReceriveCallback = null;


	public void init(TendaConfig tendaConfig, MqttRecieveCallback mqttReceriveCallback) {
		myTendaConfig = tendaConfig;
		mymqttReceriveCallback = mqttReceriveCallback;

		//初始化连接设置对象
		mqttConnectOptions = new MqttConnectOptions();
		//初始化MqttClient
		if(null != mqttConnectOptions) {
//			true可以安全地使用内存持久性作为客户端断开连接时清除的所有状态
			mqttConnectOptions.setCleanSession(true);
//			设置连接超时
			mqttConnectOptions.setConnectionTimeout(30);
			// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
			mqttConnectOptions.setKeepAliveInterval(20);

			// 设置用户名&密码（有的话）
			if (StringUtils.isNotBlank(tendaConfig.getUserName())) {
				mqttConnectOptions.setUserName(tendaConfig.getUserName());
			}
			if (StringUtils.isNotBlank(tendaConfig.getPassWord())) {
				mqttConnectOptions.setPassword(tendaConfig.getPassWord().toCharArray());
			}

//			设置持久化方式
			memoryPersistence = new MemoryPersistence();
			if(null != memoryPersistence && null != tendaConfig.getClientId()) {
				try {
					mqttClient = new MqttClient(tendaConfig.getHost(), tendaConfig.getClientId(), memoryPersistence);
				} catch (MqttException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {

			}
		}else {
			System.out.println("mqttConnectOptions对象为空");
		}

		System.out.println(mqttClient.isConnected());
		//设置连接和回调
		if(null != mqttClient) {
			if(!mqttClient.isConnected()) {

//			创建回调函数对象
//				MqttRecieveCallback mqttReceriveCallback = new MqttRecieveCallback();
//			客户端添加回调函数
				mqttClient.setCallback(mymqttReceriveCallback);
//			创建连接
				try {
					System.out.println("创建连接");
					mqttClient.connect(mqttConnectOptions);
				} catch (MqttException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}else {
			System.out.println("mqttClient为空");
		}
		System.out.println("连接状态" + mqttClient.isConnected());
	}

	//	关闭连接
	public void closeConnect() {
		//关闭存储方式
		if(null != memoryPersistence) {
			try {
				memoryPersistence.close();
			} catch (MqttPersistenceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			System.out.println("memoryPersistence is null");
		}

//		关闭连接
		if(null != mqttClient) {
			if(mqttClient.isConnected()) {
				try {
					mqttClient.disconnect();
					mqttClient.close();
				} catch (MqttException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				System.out.println("mqttClient is not connect");
			}
		}else {
			System.out.println("mqttClient is null");
		}
	}

	//	发布消息
	public void publishMessage(String pubTopic,String message,int qos) {
		if (StringUtils.isBlank(pubTopic)){
			pubTopic = myTendaConfig.getTopic();
		}
		if(null != mqttClient&& mqttClient.isConnected()) {
			System.out.println("发布消息   "+mqttClient.isConnected());
			System.out.println("id:"+mqttClient.getClientId());
			MqttMessage mqttMessage = new MqttMessage();
			mqttMessage.setQos(qos);
			mqttMessage.setPayload(message.getBytes());

			MqttTopic topic = mqttClient.getTopic(pubTopic);

			if(null != topic) {
				try {
					MqttDeliveryToken publish = topic.publish(mqttMessage);
					if(!publish.isComplete()) {
						System.out.println("消息发布成功");
					}
				} catch (MqttException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}else {
			reConnect();
		}

	}
	//	重新连接
	public void reConnect() {
		if(null != mqttClient) {
			if(!mqttClient.isConnected()) {
				if(null != mqttConnectOptions) {
					try {
						mqttClient.connect(mqttConnectOptions);
						System.out.println("重连成功！");
					} catch (MqttException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else {
					System.out.println("mqttConnectOptions is null");
				}
			}else {
				System.out.println("mqttClient is null or connect");
			}
		}else {
			init(myTendaConfig, mymqttReceriveCallback);
		}

	}
	//	订阅主题
	public void subTopic(String topic) {
		if(null != mqttClient&& mqttClient.isConnected()) {
			try {
				mqttClient.subscribe(topic, 1);
			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			System.out.println("mqttClient is error");
		}
	}


	//	取消订阅
	public void unsubTopic(String topic) {
		if(null != mqttClient&& !mqttClient.isConnected()) {
			try {
				mqttClient.unsubscribe(topic);
			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			System.out.println("mqttClient is error");
		}
	}

/*	public static void main(String[] args) {
		MyMqttClient myMqttClient = new MyMqttClient("123");
		myMqttClient.subTopic("/test");

//		String mess = "{\"parkCode\":\"TEST/3P8\",\"code\":1,\"msg\":null,\"uuid\":\"96b17db5-ce30-4e7f-974e-8c90877bb169\",\"serviceId\":\"sync.enter.in.record\",\"action\":null,\"dataItems\":[{\"plateNumber\":\"闽A12345\",\"plateColorTxt\":\"未知\",\"carType\":8,\"enterTime\":\"2020-11-18 15:46:16\",\"entrance\":\"入口默认通道\",\"carSubType\":81,\"carStatus\":1,\"enterOpId\":2,\"enterOpame\":\"Admin\",\"remainParkNum\":143,\"totalParkNum\":2432,\"recognizeType\":2,\"enterPic\":\"\",\"enterPicSmall\":null,\"inChannelid\":\"27\",\"recordNo\":\"99E1889200B44A5EBEC92AD27FEE2174\",\"groupId\":1001,\"groupUuid\":\"88E1889200B44A5EBEC92AD27FEE2174\",\"groupName\":\"1\",\"inMac\":\"28_b9_87_c3_c4_8c\",\"visitorTime\":null,\"ticketNo\":null,\"trigger\":0,\"workspaceIp\":\"192.168.0.241\",\"isportmapping\":0,\"routerip\":\"192.168.0.1\",\"routerport\":\"80\",\"cplx\":\"41\",\"jckbh\":\"1\",\"jckmc\":\"27\",\"zxd\":\"100\",\"cb\":\"\",\"clys\":\"未知\",\"sfwc\":\"0\",\"bcbz\":\"1\",\"hardwareUuid\":\"58DD4A7CCEC849988CC21A41C8733661\"}],\"opt\":\"Admin\",\"timestamp\":\"2020-11-18 15:47:12\"}";
//		String mess = "{\"parkCode\":\"TEST/3P8\",\"code\":1,\"msg\":null,\"uuid\":\"69d5e48b-f427-459a-8251-b7749584642a\",\"serviceId\":\"sync.leave.out.record\",\"action\":null,\"dataItems\":[{\"plateNumber\":\"浙A33333\",\"plateColorTxt\":\"未知\",\"carType\":9,\"carSubType\":91,\"carStatus\":2,\"enterTime\":\"2020-11-09 15:40:00\",\"entrance\":\"入口默认通道\",\"inChannelid\":\"27\",\"enterPic\":\"\",\"enterPicSmall\":null,\"useTime\":12958,\"releaseType\":1,\"leaveTime\":\"2020-11-18 15:38:52\",\"exit\":\"出口默认通道c\",\"paidFee\":0.1,\"payableFee\":0.1,\"discountFee\":0,\"payTime\":\"2020-11-18 15:43:11\",\"payType\":4,\"payChannel\":1,\"type\":1,\"leaveOpId\":2,\"leaveOpName\":\"Admin\",\"remainParkNum\":143,\"totalParkNum\":2432,\"leavePic\":\"\",\"leavePicSmall\":null,\"outChannelid\":\"28\",\"recordNo\":\"69738904C6684B94980D43AC9C593883\",\"trigger\":0,\"hardwareId\":42,\"hardwareUuid\":\"25BCCDAFCD4541E4A0B88601EBFED788\",\"shopId\":0,\"shopName\":null,\"ticketMark\":null,\"ticketNo\":null,\"groupId\":0,“groupUuid”:\"\",\"groupName\":\"无车组\",\"inMac\":\"28_b9_87_c3_c4_8c\",\"outMac\":\"28_b9_87_c3_c4_8c\",\"openGateRemark\":\"确认放行\",\"groupChargeDetails\":null,\"workspaceName\":\"241岗亭\",\"workspaceIp\":\"192.168.0.241\",\"isportmapping\":0,\"routerip\":\"192.168.0.1\",\"routerport\":\"80\",\"cplx\":\"41\",\"jckbh\":\"2\",\"jckmc\":\"28\",\"zxd\":\"100\",\"cb\":\"\",\"clys\":\"白\",\"sfwc\":\"0\",\"bcbz\":\"1\",\"stopTime\":null,\"balance\":0,\"tel\":null}],\"opt\":\"Admin\",\"timestamp\":\"2020-11-18 15:43:11\"}";
//		myMqttClient.publishMessage("/test", mess, 1);
	}*/

}
