package com.zd.laboratory.event;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zd.laboratory.mqtt.entiy.MessageBody;
import com.zd.laboratory.service.ILabRiskPlanService;
import com.zd.system.api.face.factory.RemoteFaceFallbackFactory;
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.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Controller
 *
 * @author cyl
 * @date 2021/10/14
 */
@Component
public class LabMessageListener implements ApplicationListener <SensorLabMessageEvent> {
    private static final Logger log = LoggerFactory.getLogger(LabMessageListener.class);

//    private Lock lock = new ReentrantLock(true);

    @Autowired
    ILabRiskPlanService riskPlanService;
    static TypeReference<SubFunction<SensorFunctionStatus>> typeReference = new TypeReference<SubFunction<SensorFunctionStatus>>() {
    };

    @Override
    public void onApplicationEvent(SensorLabMessageEvent sensorLabMessageEvent) {
        SubFunction<SensorFunctionStatus> message = sensorLabMessageEvent.getMessage();
        log.error("实验室ID======================================================="+message.getSubId());
//        JSONObject object = JSONObject.parseObject(payload);
//
//        SubFunction<SensorFunctionStatus> messageBody = object.getObject("data", typeReference);
        //触发事件
//        try{
//            lock.lock();
            log.error("锁住预案，一次只执行一个预案，实验室ID======================================================="+message.getSubId());
            //没有实验室Id 不处理
            if(message.getSubId()==null) return;
            riskPlanService.triggerRiskPlan(message);
//        }catch(Exception e){
//            e.printStackTrace();
//            log.error("LabMessageListener: " + e.getMessage());
//        }finally {
////            lock.unlock();
//        }

    }
}
