package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSON;
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 lombok.extern.slf4j.Slf4j;

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;

@Slf4j
@Service
public class MqttEventReceiveServiceImpl implements MqttEventReceiveService {

  @Autowired
  MonitorEventService monitorEventService;


  @Override
  @Transactional(rollbackFor = Exception.class)
  public void handlerMqttIncrementMessage(String topic, String message) {
    try {
      log.debug(message);
      JSONObject json = JSON.parseObject(message);
      String deviceCode = json.getString("deviceCode");
      String event = json.getString("event");
      JSONObject eventJson = JSONObject.parseObject(event);
      
      String eventContent = eventJson.getString("eventContent");
      String eventType = String.valueOf(eventJson.get("eventType")).toString();
      
      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();
    }
  }
  
//  public static void main(String[] args) {
//	  MqttEventReceiveServiceImpl m = new MqttEventReceiveServiceImpl();
//	  m.handlerMqttIncrementMessage("", "{\"deviceCode\":\"13485741871310161013\",\"traceId\":\"-1202608724639988142\",\"event\":{\"pic\":\"upload/iot/1433672253282881537/752F8D2FCC745F218EE936C673DAB.jpg\",\"eventContent\":\"人数变化事件 \",\"eventType\":15}}");
//  }
}
