package com.yeejoin.amos.fas.client.invoke;

import com.yeejoin.amos.fas.business.feign.RemoteSecurityService;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.vo.Toke;
import com.yeejoin.amos.fas.common.enums.TriggerRpnChangeTypeEum;
import com.yeejoin.amos.fas.context.IotContext;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 风险点消费队列
 */

public class RsDataQueue {

    private static final BlockingQueue<FmeaMessage> blockingQueue = new LinkedBlockingQueue<>();
    private ScheduledExecutorService service_apdu = null;
    private IRiskSourceService riskSourceService;
    private volatile static RsDataQueue instance = null;
    private static final String TOKE = "TOKE";
    private RemoteSecurityService remoteSecurityService;

    private RsDataQueue() {
        riskSourceService = (IRiskSourceService) IotContext.getInstance().getBean(IRiskSourceService.class);
        remoteSecurityService = (RemoteSecurityService)IotContext.getInstance().getBean(RemoteSecurityService.class);
    }

    /**
     * 获取RsDataQueue 的实例
     *
     * @return 获RsDataQueue
     */
    public static RsDataQueue getInstance() {
        //先检查实例是否存在，如果不存在才进入下面的同步块
        if (instance == null) {
            //同步块，线程安全的创建实例
            synchronized (RsDataQueue.class) {
                //再次检查实例是否存在，如果不存在才真的创建实例
                if (instance == null) {
                    instance = new RsDataQueue();
                }
            }
        }
        return instance;
    }

    /**
     * 启动apdu数据消费任务
     */
    public void start() {
        service_apdu = Executors.newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        service_apdu.execute(task_runnable);
    }

    public void addUpdateMessage(Long fmeaId,String userName) {
        blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.fmeaUpdate.getCode(),userName));
    }

    public void addPatrolMessage(Long fmeaId) {
        blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.patrol.getCode()));
    }

    public void addPatrolMessage(Long fmeaId, String userName, String pointName, String checkStatus) {
        blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.patrol.getCode(),userName,pointName,checkStatus));
    }


    public void addEquipmentMessage(Long fmeaId,String equipmentName) {
        blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.alarm.getCode(),"",equipmentName,""));
    }

    public void addEquipmentMessage(Long fmeaId,String equipmentName,Integer state) {
        if(state==0){
            blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.alarmRecovery.getCode(),"",equipmentName,""));

        }else{
            blockingQueue.add(new FmeaMessage(fmeaId, TriggerRpnChangeTypeEum.alarm.getCode(),"",equipmentName,""));
        }
    }

    public void addDeleteMessage(Long riskSourceId) {
        blockingQueue.add(new FmeaMessage(riskSourceId, TriggerRpnChangeTypeEum.fmeaDelete.getCode()));
    }

    public void addRiskSourcePointDeleteMessage(Long parentId) {
        blockingQueue.add(new FmeaMessage(parentId, TriggerRpnChangeTypeEum.riskDelete.getCode()));
    }

    private Runnable task_runnable = new Runnable() {
        @Override
        public void run() {
            int k = 0;
            boolean b = true;
            while (b) {
                k++;
                b = k < Integer.MAX_VALUE;
                try {
                    FmeaMessage fmeaMessage = blockingQueue.take();
                    if (riskSourceService != null) {
                    	//获取缓存
                    	Toke toke = remoteSecurityService.getServerToken();
//                        CacheMap cacheMap = CacheFactory.newChacheMap();
//                        Toke toke = cacheMap.getValue(TOKE);
//                        if (toke == null) {
//                            toke = remoteSecurityService.come();
//                            Long times = (long) (20 * 24 * 60 * 60);
//                            cacheMap.setex(TOKE, toke, times);
//                        }
                        String from = fmeaMessage.getNorifyFrom();
                        Long handId = fmeaMessage.getHandId();
                        String userName = fmeaMessage.getUserName();
                        String relationName = fmeaMessage.getRelationName();
                        String checkStatus =null;
                        if(fmeaMessage.getCheckStatus()!=null && fmeaMessage.getCheckStatus()!=""){
                            checkStatus =(fmeaMessage.getCheckStatus().equals("1"))?"合格":"不合格";
                        }
                        if (from.equals(TriggerRpnChangeTypeEum.patrol.getCode())) {
                            //巡检不合格通知
                            riskSourceService.notifyFmeaFromAbnormal(toke.getToke(), toke.getProduct(), toke.getAppKey(), handId, from, userName,relationName,checkStatus);
                        } else if (from.equals(TriggerRpnChangeTypeEum.alarm.getCode())) {
                            //设备告警
                            riskSourceService.notifyFmeaFromAbnormal(toke.getToke(), toke.getProduct(), toke.getAppKey(), handId, from, userName,relationName,checkStatus);
                        } else if (from.equals(TriggerRpnChangeTypeEum.alarmRecovery.getCode())) {
                            //设备告警恢复
                            riskSourceService.notifyFmeaFromAbnormal(toke.getToke(), toke.getProduct(), toke.getAppKey(), handId, from, userName,relationName,checkStatus);
                        } else if (from.equals(TriggerRpnChangeTypeEum.fmeaUpdate.getCode())) {
                            //危险因素评价修改通知
                            riskSourceService.notifyFmeaFromUpdate(toke.getToke(), toke.getProduct(), toke.getAppKey(), handId, from, userName);
                        } else if (from.equals(TriggerRpnChangeTypeEum.fmeaDelete.getCode())) {
                            //危险因素删除通知
                            riskSourceService.notifyFmeaFromDelete(handId, from);
                        } else if (from.equals(TriggerRpnChangeTypeEum.riskDelete.getCode())) {
                            //风险点删除通知
                            riskSourceService.notifyRiskSourceDelete(handId);
                        }
                    }
                } catch (Exception e) {
                    LoggerFactory.getLogger(this.getClass()).error(e.getMessage(),e);
                }
        }
    }
};


}
