package com.usky.agbox.service.mqtt.event;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.usky.agbox.service.job.patrolAgbox;
import com.usky.agbox.service.mqtt.MqttStrategy;
import com.usky.agbox.service.vo.MqttBaseVO;
import com.usky.common.core.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@Service("event")
public class event implements MqttStrategy {
    @Autowired
    private patrolAgbox PatrolAgbox;

    //处理下发命令响应消息
    public String disposeMessage(MqttBaseVO mqttBaseVO) {

        try {
            JSONObject eventVO1 = JSONObject.parseObject(mqttBaseVO.getData().toString());
            JSONObject eventVO = new JSONObject();
            JSONObject eventVO2 = new JSONObject();
            if (eventVO1.get("eventType").equals(31)){
                eventVO1.put("eventCode",1);
                PatrolAgbox.addEvent(eventVO1.toString());
                eventVO2.put("deviceId",eventVO1.get("deviceId"));
                PatrolAgbox.updateHeart(eventVO2.toJSONString());
            }else if (eventVO1.get("eventType").equals(32)){
                eventVO1.put("eventCode",2);
                PatrolAgbox.addEvent(eventVO1.toString());
                eventVO2.put("deviceId",eventVO1.get("deviceId"));
                PatrolAgbox.updateHeart(eventVO2.toJSONString());
            }else {
                if (eventVO1.get("eventType").equals(33)||eventVO1.get("eventType").equals(34)){
                    eventVO.put("eventCode",5);
                }else {
                    eventVO.put("eventCode",16);
                }
                // 定义原始格式的解析器（包含'T'和毫秒）
                DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String timeWithT = eventVO1.get("createTime").toString();
                LocalDateTime dateTime = LocalDateTime.parse(timeWithT, originalFormatter);
                String targetTime = dateTime.format(targetFormatter);
                eventVO.put("deviceId",eventVO1.get("deviceId"));
                eventVO.put("triggerTime",targetTime);
                eventVO.put("name",eventVO1.get("createBy"));
                eventVO.put("certifiedNo","");
                PatrolAgbox.addEvent(eventVO.toJSONString());
                eventVO2.put("deviceId",eventVO1.get("deviceId"));
                PatrolAgbox.updateHeart(eventVO2.toJSONString());
            }
            System.out.println("FEventReceiver消费者收到消息： " + mqttBaseVO.getData().toString());
        } catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }


}
