package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.common.entity.dto.MonitorEventDto;
import com.yeejoin.equipmanage.common.enums.VideoEventEnum;
import com.yeejoin.equipmanage.service.MqttEventReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MqttEventReceiveServiceImpl implements MqttEventReceiveService {

  @Autowired
  MonitorEventService monitorEventService;


  @Override
  @Transactional(rollbackFor = Exception.class)
  public void handlerMqttIncrementMessage(String topic, String message) {
    JSONObject json = JSONObject.parseObject(message);
    try {
      String deviceCode = json.getString("deviceCode");
      String event = json.getString("event");
      JSONObject eventJson = JSONObject.parseObject(event);
      
      String eventContent = eventJson.getString("eventContent");
      String eventType = eventJson.getString("eventType");
      String eventPic = eventJson.getString("pic");
      
      List<String> eventPicList = new ArrayList<String>();
      eventPicList.add(eventPic);
      String snapPictures = JSONObject.toJSONString(eventPicList);
      
      MonitorEventDto model = new MonitorEventDto();

      if (VideoEventEnum.LEAVE.getCode().equals(eventType)) {
        model.setEventType(VideoEventEnum.LEAVE.getName());
      }
      if (VideoEventEnum.PERSONCHANGE.getCode().equals(eventType)) {
        model.setEventType(VideoEventEnum.PERSONCHANGE.getName());
      }

      if (ObjectUtils.isEmpty(model.getEventType())) {
        return;
      }
      model.setVideoCode(deviceCode);
      model.setEventContent(eventContent);
      model.setSnapPictures(snapPictures);
      model.setCreateDate(new Date());
      model.setEventState("未处理");
      monitorEventService.createMonitorEvent(model);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
