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.modbus.serialPort.SerialOutputStream;
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.util.*;
import java.util.concurrent.atomic.AtomicReference;

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

    @Resource
    private webSocket webSocket;
    private String title;

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

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

    @SneakyThrows
    @Override
    public void run() {//线程的主体方法
        int i = 0;
        Thread.sleep(10000);//延迟10秒启动 待连接工业库成功
        // 存放可燃报警点 报警次数 报警时间
        // 可燃气体的报警只有处置了以后才会消失
        List<BjxxCal> listBjRecord = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject bjWebSocket = new JSONObject();

        while (true) {
            try {
                sssjTools.AllKrlist();
                List<CxcSssjLssjBjlsjl> listBjxx = new ArrayList<CxcSssjLssjBjlsjl>();
                //如果可燃报警map中有数据
                if (!sssjTools.mapKrbjsj.isEmpty()) {
                    Iterator<Map.Entry<String, CxcSssjLssjBjlsjl>> ite = sssjTools.mapKrbjsj.entrySet().iterator();

                    while (ite.hasNext()) {
                        Map.Entry<String, CxcSssjLssjBjlsjl> entry = ite.next();
                        //当报警数据的状态为0（已处置），判定报警结束，需要移除该报警数据
                        //当报警数据的状态为3（可燃未处置），并且存在相同的bjid，也需要将该数据移除listBjxx。
                        boolean a = sssjTools.queryBjxx(entry.getValue().getBjId());
                        if (a){
                            //重复报警，移除map
                            ite.remove();
                        }else {
                            // 新报警存入list
                            entry.getValue().setSaveflag(true);
                            listBjxx.add(entry.getValue());
                        }
                    }
                }
                List<String> msgId = new ArrayList<>();
                List<String> msgTxt = new ArrayList<>();
                //存库加发送消息
                if (!listBjxx.isEmpty()) {
                    listBjxx.forEach(item->{
                        msgId.add(item.getBz());
                        msgTxt.add(item.getBz()+","+item.getBjId() +"," +item.getBjz() + "," + item.getBjName()) ;
                        log.info("name:"+item.getBjName()+" begin:"+item.getCreateTime()+" msg:"+item.getReason());
                    });
 //*************************************  可燃计量点报警    发布时要去掉注释 ***************************************************************

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

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

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

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

                    bjWebSocket.put("cmd", "krbj110");//业务类型
                    bjWebSocket.put("msgId", msgId);//消息id ,这里存的是站ID数组
                    bjWebSocket.put("msgTxt", 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);
    }
}
