package org.gyk.modules.sssj.util;

//import com.alibaba.fastjson.JSONObject;

import lombok.SneakyThrows;
import net.minidev.json.JSONObject;
import org.gyk.modules.lssj.bjls.entity.CxcSssjLssjBjlsjl;
import org.gyk.modules.sssj.entity.BjxxCal;
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.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

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

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

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

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

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

        JSONObject bjWebSocket = new JSONObject();

        while (true) {
            try {
                sssjTools.GetAllBj();  //获取当前所有的报警信息
                List<CxcSssjLssjBjlsjl> listBjxx = new ArrayList<CxcSssjLssjBjlsjl>();

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

                        if (!entry.getValue().isSaveflag()) {
//                            log.info("who:"+entry.getKey()+" be:"+entry.getValue().getCreateTime()+" end:"+entry.getValue().getEndTime() );

                            listBjxx.add(entry.getValue());
                            entry.getValue().setSaveflag(true);
                        }

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

                        if (ls > 30 || ls < -30) {
//                    String bjms = entry.getValue().getBjMs();
//                    entry.getValue().setBjMs(bjms+"  报警结束，时间："+entry.getValue().getBeginTime()+" - "+entry.getValue().getEndTime());
                            entry.getValue().setId(UUID.randomUUID().toString());
                            listBjxx.add(entry.getValue());
                            ite.remove();
                        }
                    }
                }

                if (listBjxx.size() > 0) {
                    listBjxx.forEach(item->{
                        log.info("name:"+item.getBjName()+" begin:"+item.getCreateTime()+" msg:"+item.getReason());
                    });

 //*************************************  计量点报警    发布时要去掉注释 ***************************************************************

                    sssjTools.saveBjls(listBjxx);// 将新报警立即存盘

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

                    log.info(sssjTools.getStrCurrentTime() + "-----保存计量点报警历史数据" + listBjxx.size() + "条成功");

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

                    bjWebSocket.put("cmd", "ssbj110");//业务类型
                    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() + "报警异常2:" + e.getMessage());
            }

            i++;

            if (i > 45) {
                JSONObject pingWebSocket = new JSONObject();
                pingWebSocket.put("cmd","ping");
                pingWebSocket.put("msgId", "6666");//消息id
                pingWebSocket.put("msgTxt", "ping");//消息内容

                webSocket.sendAllMessage(pingWebSocket.toJSONString());
                i = 0;
            }

            Thread.sleep(2000);
        }
//        return (webSocket);
    }

    /* 将saveBj多线程中获取的所有报警信息存入历史数据库中 */
//    public static void   sendAllMessage(String strMessage){
//
//            webSocket.sendAllMessage(strMessage);
//
//
//    }
}
