package org.gyk.modules.sssj.util;

//import com.alibaba.fastjson.JSONObject;

import lombok.SneakyThrows;
import net.minidev.json.JSONObject;
import org.gyk.modules.sssj.entity.BjxxCal;
import org.gyk.modules.sssj.entity.YasuojiBjSj;
import org.gyk.modules.websocket.webSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @Description: 多线程-报警数据20s存库
 * @Author: liao
 * @Date: 2021-04-05
 * @Version: V1.0
 */
//@Slf4j
public class YasuojBj extends Thread {//线程主体+
    @Value("${HeartBeatbj}")
    private int HeartBeatbj = 2000;
    @Resource
    private webSocket webSocket;
    private String title;

    public YasuojBj(String title, webSocket webSocket) {
        this.title = title;
        this.webSocket = webSocket;
    }

    private static Logger log = LoggerFactory.getLogger(YasuojBj.class);

    @SneakyThrows
    @Override
    public void run() {//线程的主体方法
        int i = 0;

        Thread.sleep(10000);//延迟10秒启动 待连接工业库成功
        // 存放所有的报警点 报警次数 报警时间  //5分钟保存一次清零一次
        List<BjxxCal> listBjRecord = new ArrayList<>();
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        JSONObject bjWebSocket = new JSONObject();

        while (true) {
            try {
                sssjTools.GetYasuoBj();  //获取当前所有的报警信息

                List<YasuojiBjSj> listSaveBjxx = new ArrayList<>();  //存放需要保存的报警信息
                //循环所有报警信息，记录报警次数 报警时间

                if (sssjTools.mapbjsj.size() > 0) {
                    Iterator<Map.Entry<String, YasuojiBjSj>> ite = sssjTools.mapbjsj.entrySet().iterator();
                    while (ite.hasNext()) {
                        Map.Entry<String, YasuojiBjSj> entry = ite.next();

                        if (!entry.getValue().isSaveFlag()) {
                            entry.getValue().setId(UUID.randomUUID().toString());

                                listSaveBjxx.add(entry.getValue());

                                entry.getValue().setSaveFlag(true);

//                                log.warn("key: " + entry.getKey() + " begin:" + entry.getValue().getBeginTime() + " end:" + entry.getValue().getEndTime() + " canshu: " + entry.getValue().getCanshuZhi());

                        }
                        //当报警数据的结束时间与当前时间差值超过9秒时，判定报警结束，需要移除该报警数据
                        long ls = 0;
                        if (entry.getValue().getEndTime() != null) {
                            LocalDateTime now = LocalDateTime.now();
                            ls = ChronoUnit.SECONDS.between(entry.getValue().getEndTime(), now);
                        }

                        if (ls > 30 || ls < -30) {
                            String bjms = entry.getValue().getBjMs();
                            entry.getValue().setId(UUID.randomUUID().toString());
                            entry.getValue().setBjMs(bjms + "  报警结束，时间：" + entry.getValue().getBeginTime().format(sdf) + " - " + entry.getValue().getEndTime().format(sdf));
                            entry.getValue().setZt("0");  //0为不需要处置，1为未处置，2为已处置
                            listSaveBjxx.add(entry.getValue());
                            log.info("delete from map:" + entry.getValue().getBjId() + " " + entry.getValue().getCanshuZhi());
                            ite.remove();
                        }

                    }
                }

                if (listSaveBjxx.size() > 0) {

//******************************        压缩机报警    发布时要去掉注释      ******************************************************************************

                    sssjTools.saveYasuojiBjtoslave(listSaveBjxx);// 将新报警立即存盘
                    log.info(sssjTools.getStrCurrentTime() + "-----保存压缩机报警数据" + listSaveBjxx.size() + "条成功");

//***************************************************************************************



                    bjWebSocket.put("cmd", "ysjbj110");//业务类型
                    bjWebSocket.put("msgId", "1002");//消息id
                    bjWebSocket.put("msgTxt", "压缩机报警");//消息内容

                    try {
                        webSocket.sendAllMessage(bjWebSocket.toJSONString());
                    } catch (Exception e) {
                        log.error("hi:" + e);
                    }
                }
            } catch (Exception e) {
                log.info(sssjTools.getStrCurrentTime() + "报警异常1:" + e.getMessage());
            }

            i++;

            Thread.sleep(HeartBeatbj);
        }
    }

}
