package com.zd.laboratory.event;

import com.alibaba.fastjson.JSONObject;
import com.zd.common.core.constant.CacheConstants;
import com.zd.common.core.constant.CacheDevice;
import com.zd.common.redis.service.RedisService;
import com.zd.laboratory.mqtt.service.impl.SubMessageSendManager;
import com.zd.laboratory.service.ILabSensorService;
import com.zd.laboratory.service.impl.LabSubjectManagerService;
import com.zd.system.api.laboratory.domain.SensorFunctionStatus;
import com.zd.system.api.laboratory.domain.vo.SubFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author 董高升
 * @Date 2022-01-02
 * @descipt 新采集捕捉事件
 */
@Component
public class SensorNewStatusListener implements ApplicationListener<SensorNewStatusEvent> {

    private static final Logger logger = LoggerFactory.getLogger(SensorNewStatusListener.class);

    @Autowired
    private ILabSensorService labSensorService;

    @Autowired
    private LabSubjectManagerService labSubjectManagerService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SubMessageSendManager subMessageSendManager;

    @Override
    public void onApplicationEvent(SensorNewStatusEvent sensorNewStatusEvent) {
        String eventSensorStr=sensorNewStatusEvent.getSource().toString();
        JSONObject jsonObject=JSONObject.parseObject(eventSensorStr);
        if(null==jsonObject) return;
        String deviceNo=jsonObject.getString("deviceNo");
        Long subjectId = labSensorService.getCacheSubByGateway(deviceNo);
        if(null==subjectId) return;
        jsonObject.put("subjectId",subjectId);
        redisService.setCacheObject(CacheConstants.SENSOR_DATA_KEY+subjectId,jsonObject,5L, TimeUnit.MINUTES);
        redisService.setCacheObject( CacheDevice.SENSOR_LIFE.getRedisKey() + deviceNo, deviceNo,
                CacheDevice.SENSOR_LIFE.getRedisTime() ,TimeUnit.SECONDS);
        List<SensorFunctionStatus> list = labSubjectManagerService.querySenseNewFunctionBySubId(subjectId);
        SubFunction subFunction= new SubFunction();
        subFunction.setFunctionStatuses(list);
        subFunction.setSubId(subjectId);
        subMessageSendManager.sendFunctionUpdateToCommon(subFunction);
    }
}
