package com.zd.laboratory.mqtt.service.hxp;

import cn.hutool.core.date.DateUtil;
import com.zd.common.core.utils.DateUtils;
import com.zd.laboratory.mapper.HxpTerminalMapper;
import com.zd.laboratory.mqtt.service.TerminalRouter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class HxpTerminalService implements TerminalRouter{

    public HxpTerminalService() {
        TerminalRouter.routerMap.put("HxpTerminalService", this);
    }

    private static List<Map<String, Object>> codeList = new CopyOnWriteArrayList();

    private static Long effective_time = 30 * 60 * 1000L;

    @Autowired
    private HxpTerminalMapper hxpTerminalMapper;

    @Override
    public void onLine(String codeNum){

        Map<String, Object> map = codeList.stream().filter(a -> a.get("codeNum").equals(codeNum)).findFirst().orElse(null);
        if(map != null && DateUtil.betweenMs((Date) map.get("time"), DateUtils.getNowDate()) < effective_time){
            return;
        }
        int count = hxpTerminalMapper.updateHxpTerminal(codeNum, 2);
        if(count > 0){
            map = new HashMap<>();
            map.put("codeNum", codeNum);
            map.put("time", DateUtils.getNowDate());
            codeList.add(map);
        }
    }

    @Override
    public void offLine(String codeNum) {
        hxpTerminalMapper.updateHxpTerminal(codeNum, 0);
    }
}
