package org.springblade.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springblade.community.parkinglot.entity.ParkingLot;
import org.springblade.community.parkinglot.service.IParkingLotService;
import org.springblade.community.tdcarrecord.entity.TdCarRecord;
import org.springblade.community.tdcarrecord.service.ITdCarRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Component
@AllArgsConstructor
@RestController
public class MqttRecieveCallback implements MqttCallback{

	private final ITdCarRecordService tdCarRecordService;

	@Autowired
	private MyMqttClient myMqttClient;
	@Autowired
	private IParkingLotService parkingLotService;

	@Override
	public void connectionLost(Throwable cause) {
		cause.printStackTrace();
		// 连接丢失后，一般在这里面进行重连
//		System.out.println("连接断开，可以做重连");
		myMqttClient.reConnect();
		System.out.println("连接断开，尝试重连");
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		System.out.println("deliveryComplete---------" + token.isComplete());
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) {

		try{
			System.out.println("Client 接收消息主题 : " + topic);
			System.out.println("Client 接收消息Qos : " + message.getQos());
			System.out.println("Client 接收消息内容 : " + new String(message.getPayload()));
			String dataStr = new String(message.getPayload());
//		JSONArray jsonArray = JSONUtil.parseArray(dataStr);
			JSONObject jsonObject = JSON.parseObject(dataStr);

			// 可能这里通过这个字段来区分消息类型
			Object serviceId = jsonObject.get("serviceId");
			if (serviceId != null){
				switch (serviceId.toString()){
					// 入场记录
					case "sync.enter.in.record":
						String dataItemsOut = ((JSONArray) jsonObject.get("dataItems")).get(0).toString();
						TdCarRecord tdCarRecordOut = JSON.parseObject(dataItemsOut, TdCarRecord.class);
						String inMac = tdCarRecordOut.getInMac();
						ParkingLot lot1 = parkingLotService.getByKey(inMac);
						if(lot1 != null){
							tdCarRecordOut.setTenantId(lot1.getTenantId());
						}
						tdCarRecordService.save(tdCarRecordOut);
						//返回数据
						ArrayList<Object> dataItems = new ArrayList<>();
						dataItems.add(new HashMap<>().put("num", 1));

						Map map = new HashMap();
						map.put("code", 1);
						map.put("parkCode", jsonObject.get("parkCode"));
						map.put("serviceId", jsonObject.get("serviceId"));
						map.put("uuid", jsonObject.get("uuid"));
						myMqttClient.publishMessage("tcp/" + jsonObject.get("parkCode"), map.toString(),1);
						break;
					// 出场记录
					case "sync.leave.out.record":
						String dataItemsOut2 = ((JSONArray) jsonObject.get("dataItems")).get(0).toString();
						JSONObject jsonObject1 = JSONObject.parseObject(dataItemsOut2);
						tdCarRecordOut = JSON.parseObject(dataItemsOut2, TdCarRecord.class);
						tdCarRecordOut.setExitOut(jsonObject1.getString("exit"));
						String outMac = tdCarRecordOut.getOutMac();
						ParkingLot lot2 = parkingLotService.getByKey(outMac);
						if(lot2 != null){
							tdCarRecordOut.setTenantId(lot2.getTenantId());
						}
						tdCarRecordService.save(tdCarRecordOut);
						//返回数据
						dataItems = new ArrayList<>();
						dataItems.add(new HashMap<>().put("num", 1));

						map = new HashMap();
						map.put("code", 1);
						map.put("parkCode", jsonObject.get("parkCode"));
						map.put("serviceId", jsonObject.get("serviceId"));
						map.put("uuid", jsonObject.get("uuid"));
						myMqttClient.publishMessage("tcp/" + jsonObject.get("parkCode"), map.toString(),1);
						break;
					default:
						System.out.println("不是需要是业务类型数据，serviceId=" + serviceId.toString());
						break;
				}

			} else {
				System.out.println("找不到业务类型serviceId！");
			}
		}catch (Exception e){
			e.printStackTrace();
		}

	}

//	@GetMapping(value = "/openinterface/jiyue/aaaaaa")
	public void test1(){
		String dataStr = "{\n" +
			"\t\"parkCode\": \"SLZX/1P11\",\n" +
			"\t\"code\": 1,\n" +
			"\t\"msg\": null,\n" +
			"\t\"uuid\": \"415c3b6d-390c-4e02-bc2c-8b36679d5c68\",\n" +
			"\t\"serviceId\": \"sync.leave.out.record\",\n" +
			"\t\"action\": null,\n" +
			"\t\"dataItems\": [{\n" +
			"\t\t\"plateNumber\": \"宁BR0376\",\n" +
			"\t\t\"plateColorTxt\": \"蓝\",\n" +
			"\t\t\"carType\": 1,\n" +
			"\t\t\"carSubType\": 17,\n" +
			"\t\t\"carStatus\": 2,\n" +
			"\t\t\"enterTime\": \"2021-09-18 18:00:34\",\n" +
			"\t\t\"entrance\": null,\n" +
			"\t\t\"inChannelid\": \"0\",\n" +
			"\t\t\"enterPic\": null,\n" +
			"\t\t\"enterPicSmall\": null,\n" +
			"\t\t\"useTime\": 0,\n" +
			"\t\t\"releaseType\": 1,\n" +
			"\t\t\"leaveTime\": \"2021-09-18 18:00:34\",\n" +
			"\t\t\"exit\": \"出口一\",\n" +
			"\t\t\"paidFee\": 0.0,\n" +
			"\t\t\"payableFee\": 0.0,\n" +
			"\t\t\"discountFee\": 0.0,\n" +
			"\t\t\"payTime\": \"2021-09-18 18:00:34\",\n" +
			"\t\t\"payType\": 4,\n" +
			"\t\t\"payChannel\": 1,\n" +
			"\t\t\"type\": 1,\n" +
			"\t\t\"leaveOpId\": 2,\n" +
			"\t\t\"leaveOpName\": \"Admin\",\n" +
			"\t\t\"remainParkNum\": 998,\n" +
			"\t\t\"totalParkNum\": 1000,\n" +
			"\t\t\"leavePic\": \"http://68_ae_6d_0_1a_3b.tdzntech.com:9898/ftpdir/pic/Recognize/20210918/192.168.0.100_2021091818003400000_6636.jpg\",\n" +
			"\t\t\"leavePicSmall\": \"http://68_ae_6d_0_1a_3b.tdzntech.com:9898/ftpdir/pic/Recognize/20210918/192.168.0.100_2021091818003400000_6636_M.jpg\",\n" +
			"\t\t\"outChannelid\": \"1\",\n" +
			"\t\t\"recordNo\": \"\",\n" +
			"\t\t\"trigger\": 0,\n" +
			"\t\t\"hardwareId\": 1,\n" +
			"\t\t\"hardwareUuid\": \"C2C944802B7611B2A92968AE6D001A3B\",\n" +
			"\t\t\"shopId\": 0,\n" +
			"\t\t\"shopName\": null,\n" +
			"\t\t\"ticketMark\": null,\n" +
			"\t\t\"ticketNo\": null,\n" +
			"\t\t\"groupId\": 0,\n" +
			"\t\t\"groupName\": \"无车组\",\n" +
			"\t\t\"inMac\": null,\n" +
			"\t\t\"outMac\": \"68_ae_6d_0_1a_3b\",\n" +
			"\t\t\"openGateRemark\": \"自动放行\",\n" +
			"\t\t\"groupChargeDetails\": null,\n" +
			"\t\t\"workspaceName\": \"默认岗亭\",\n" +
			"\t\t\"workspaceIp\": \"192.168.0.233\",\n" +
			"\t\t\"isportmapping\": 0,\n" +
			"\t\t\"routerip\": \"192.168.0.1\",\n" +
			"\t\t\"routerport\": \"80\",\n" +
			"\t\t\"cplx\": \"02\",\n" +
			"\t\t\"jckbh\": \"2\",\n" +
			"\t\t\"jckmc\": \"1\",\n" +
			"\t\t\"zxd\": \"99\",\n" +
			"\t\t\"cb\": \"\",\n" +
			"\t\t\"clys\": \"255\",\n" +
			"\t\t\"sfwc\": \"1\",\n" +
			"\t\t\"bcbz\": \"1\",\n" +
			"\t\t\"stopTime\": \"2099-01-31 12:00:00\",\n" +
			"\t\t\"balance\": 0.0,\n" +
			"\t\t\"tel\": \"\"\n" +
			"\t}],\n" +
			"\t\"opt\": \"Admin\",\n" +
			"\t\"timestamp\": \"2021-09-18 18:00:34\"\n" +
			"}";
		JSONObject jsonObject = JSON.parseObject(dataStr);

		// 可能这里通过这个字段来区分消息类型
		Object serviceId = jsonObject.get("serviceId");

		if (serviceId != null){
			switch (serviceId.toString()){
				// 入场记录
				case "sync.enter.in.record":
					String dataItemsOut = ((JSONArray) jsonObject.get("dataItems")).get(0).toString();
					TdCarRecord tdCarRecordOut = JSON.parseObject(dataItemsOut, TdCarRecord.class);
//					tdCarRecordService.save(tdCarRecordOut);
					//返回数据
					ArrayList<Object> dataItems = new ArrayList<>();
					dataItems.add(new HashMap<>().put("num", 1));

					Map map = new HashMap();
					map.put("code", 1);
					map.put("parkCode", jsonObject.get("parkCode"));
					map.put("serviceId", jsonObject.get("serviceId"));
					map.put("uuid", jsonObject.get("uuid"));
//					myMqttClient.publishMessage("tcp/" + jsonObject.get("parkCode"), map.toString(),1);
					break;
				// 出场记录
				case "sync.leave.out.record":
					String dataItemsOut2 = ((JSONArray) jsonObject.get("dataItems")).get(0).toString();
					JSONObject jsonObject1 = JSONObject.parseObject(dataItemsOut2);
					tdCarRecordOut = JSON.parseObject(dataItemsOut2, TdCarRecord.class);
					tdCarRecordOut.setExitOut(jsonObject1.getString("exit"));
					tdCarRecordService.save(tdCarRecordOut);
					//返回数据
					dataItems = new ArrayList<>();
					dataItems.add(new HashMap<>().put("num", 1));

					map = new HashMap();
					map.put("code", 1);
					map.put("parkCode", jsonObject.get("parkCode"));
					map.put("serviceId", jsonObject.get("serviceId"));
					map.put("uuid", jsonObject.get("uuid"));
//					myMqttClient.publishMessage("tcp/" + jsonObject.get("parkCode"), map.toString(),1);
					break;
				default:
					System.out.println("不是需要是业务类型数据，serviceId=" + serviceId.toString());
					break;
			}

		} else {
			System.out.println("找不到业务类型serviceId！");
		}
	}


	private boolean recordSave(TdCarRecord tdCarRecord){
		return tdCarRecordService.save(tdCarRecord);
	}
}
