package org.gyk.modules.sssj.util;


import lombok.SneakyThrows;
//import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.gyk.modules.lssj.bjls.entity.CxcSssjLssjBjlsjl;
import org.gyk.modules.lssj.jldls.entity.CxcSssjLssjJldls;
import org.gyk.modules.lssj.jldls.entity.CxcSssjLssjJldlsRsj;
import org.gyk.modules.lssj.jldls.mapper.JldlsMapper;
import org.gyk.modules.lssj.jldls.service.ICxcSssjLssjJldlsRsjService;
import org.gyk.modules.lssj.ngzxsj.service.IngzxLssjService;
import org.gyk.modules.lssj.scls.entity.CxcSssjLssjScls;
import org.gyk.modules.lssj.scls.entity.CxcSssjScls;
import org.gyk.modules.sssj.entity.*;
import org.gyk.modules.sssj.service.*;
import org.gyk.modules.sz.bjpz.entity.CxcSssjSzBjsz;
import org.gyk.modules.sz.bjpz.mapper.CxcSssjSzBjszMapper;
import org.gyk.modules.sz.bjpz.service.ICxcSssjSzBjszService;
import org.gyk.modules.sz.cxcsssjjldbjcanshusz.entity.CxcSssjJldBjCanshuSz;
import org.gyk.modules.sz.cxcsssjjldbjcanshusz.service.ICxcSssjJldBjCanshuSzService;
import org.gyk.modules.sz.jdlbjpz.entity.CxcSssjJldBjShezhi;
import org.gyk.modules.sz.jdlbjpz.service.ICxcSssjJldBjShezhiService;
import org.gyk.modules.sz.jldxx.entity.CxcSssjSzJldxx;
import org.gyk.modules.sz.jldxx.service.IGetJldxxService;
import org.gyk.modules.sz.scpz.entity.CxcScdtJldxx;
import org.gyk.modules.sz.scpz.entity.CxcScdtScpz;
import org.gyk.modules.sz.scpz.entity.CxcSssjSzScsz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.lang.Double.parseDouble;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import groovy.transform.ASTTest;
//import org.apache.commons.lang3.builder.ToStringExclude;
//import org.gyk.modules.sssj.entity.CxcQijingRB;
//import org.gyk.modules.sssj.entity.CxcRsjQijing;

/**
 * @Description: 计量点实时数据方法
 * @Author: liao
 * @Date: 2021-04-05
 * @Version: V1.0
 */
//@Cacheable
//@Log4j
@Component
public class sssjTools {
    // 默认除法运算精度
    private static final Integer DEF_DIV_SCALE = 4;
    public static sssjTools judge;
    //    public static Map<String,YasuojiBjSj> mapbjsj = new HashMap<>();
    public static ConcurrentHashMap<String, YasuojiBjSj> mapbjsj = new ConcurrentHashMap<>();
    //    public static Map<String,CxcSssjLssjBjlsjl> mapTrqbjsj = new HashMap<>();
    public static ConcurrentHashMap<String, CxcSssjLssjBjlsjl> mapTrqbjsj = new ConcurrentHashMap<>();
    //可燃报警map jiang 20240308
    public static ConcurrentHashMap<String, CxcSssjLssjBjlsjl> mapKrbjsj = new ConcurrentHashMap<>();
    public static List<YasuojiJcxx> ysjGykbz = new ArrayList<>();
    public static Map<String, YasuojiSssj> mapyasuojisssj = new HashMap<>();
    public static Map<String, YasuojiJcxx> gykbzGetJcxx = new HashMap<>();
    public static List<YasuojiSssj> Ysjsssj = new ArrayList<>();
    public static Map<String, Object> MapGood = new HashMap<String, Object>();
    public static Map<String, Object> MapStop = new HashMap<String, Object>();
    public static Map<String, LocalDateTime> MapWarn = new HashMap<String, LocalDateTime>();
    public static Map<String,String> mapzrlj = new HashMap<>();
    public static Map<String, NgSssj> mapNgSssj = new HashMap<>();
    private static Logger log = LoggerFactory.getLogger(KDBClient.class);
    @Autowired
    private IGetJldxxService getJldXxService;
    @Autowired
    private IGetScpzService getScpzService;
    @Autowired
    private ISaveSclsService saveSclsService;
    @Autowired
    private ISaveJldlsService saveJldlsService;
    @Autowired
    private ICxcSssjLssjJldlsRsjService rsjService;
    @Autowired
    private IngzxLssjService ingzxLssjService;
    @Resource
    private CxcSssjSzBjszMapper bjszMapper;
    @Autowired
    private ISaveBjlsService saveBjlsService;
    @Autowired
    private IRishujuService rishujuService;
    @Autowired
    private ICxcRsjQijingService qijingService;
    @Autowired
    private ICxcSssjSzBjszService cxcSssjSzBjszService;
    @Autowired (required = false)
    private JldlsMapper jldlsMapper;
    @Autowired
    private ICxcSssjJldBjCanshuSzService cxcSssjJldBjCanshuSzService;
    @Autowired
    private ICxcSssjJldBjShezhiService cxcSssjJldBjShezhiService;
    //可燃警报
    private static double KrWarning;
    private static double KrDanger;
    @Value("${Kryz.warning}")
    public void setWKey(Double warning) {
        this.KrWarning= warning;
    }
    @Value("${Kryz.danger}")
    public void setDKey(Double danger) {
        this.KrDanger= danger;
    }

//    @Autowired
//    private ICxcSssjSzJldxxService cxcSssjSzJldxxService;


    public sssjTools() {
    }

    /**
     * 将多线程saveData每秒得到的计量点List存盘方法
     **/
    public static void saveJldls(List<CxcSssjLssjJldls> jldLsList) {
        try {
//            System.out.println(jldLsList);
            judge.jldlsMapper.insertBatchMaster(jldLsList);
        } catch (Exception e) {
            log.error("hi:" + e);
        }
    }

    public static void saveJldlstoslave(List<CxcSssjLssjJldls> jldLsList) {
        try {
            judge.jldlsMapper.insertBatchSlave(jldLsList);
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    public static void savePianyuan(List<PianyuanZhan> list) {
        try {
//            System.out.println(jldLsList);
            judge.jldlsMapper.insertPianyuanMaster(list);
        } catch (Exception e) {
            log.error("hi:" + e);
        }
    }

    public static void saveYasuojiBjtoslave(List<YasuojiBjSj> list) {
        try {
            judge.jldlsMapper.YasuojiBj(list);
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    //获取指定时长SC的压缩机报警数据
    public static List<YasuojiBjSj> getYasuojiBj() {
        return judge.jldlsMapper.getYsjBj();
    }

    //获取指定时长SC的压缩机报警数据
    public static List<CxcSssjLssjBjlsjl> getTrqBj(int sc, String lb) {
        return judge.jldlsMapper.getTrqBjxx(sc, lb);
    }

    //获取指定站场和机组号的压缩机历史数据表头
    public static List<YasuojiSj> getYasjLsBt(String zc, String jzh) {
        return judge.jldlsMapper.getYsjLsBt(zc, jzh);
    }

    //获取指定站场和机组号的压缩机历史数据
    public static List<YasuojiSj> getYasjLssj(String zc, String jzh, String startTime, String endTime) {
        return judge.jldlsMapper.getYsjLssj(zc, jzh, startTime, endTime);
    }

    //字符串转map
    public static Map<String, String> splitStringToMap(String str) {
        DecimalFormat fnum = new DecimalFormat("##0.00");
        Map<String, String> map = new HashMap<>();

        Map<String, YasuojiJcxx> mapysj = sssjTools.ysjGykbz.stream().collect(Collectors.toMap(YasuojiJcxx::getGykbz, Function.identity(), (k1, k2) -> k2));

        // 按照分号或者逗号拆分键值对
        String[] keyValuePairs = str.split(" ");

        for (String pair : keyValuePairs) {
            // 按照等号拆分键和值
            String[] keyValue = pair.split(":");

            if (keyValue.length == 2) {
                String key = keyValue[0].trim();
                String key2 = "";
                if (mapysj.containsKey(key)) {
                    key2 = mapysj.get(key).getJldName();
                    String[] jldname = key2.split("\\*");
                    String value = keyValue[1].trim();
                    float floatval = Float.parseFloat(value);
                    String lastval = fnum.format(floatval);
                    if (lastval.equals("0.00")) {
                        map.put(jldname[2], "0");
                    } else {
                        map.put(jldname[2], lastval);
                    }
                }
            }
        }
        return map;
    }

//    public static IPage<YasuojiSj> getYsjLssj(String zc,String jzh,String startTime,String endTime) {
//        IPage<YasuojiSj> iPage = judge.jldlsMapper.getYsjLssj2(new Page<>(2,5),zc,jzh,startTime,endTime);
//        log.info("hi:"+iPage.getTotal()+" "+iPage.getSize());
//        return iPage;
//    }

    //获取压缩机运行数据的表头
    public static Map<String, List<String>> getYasuojshujuBt(String zhanc, String jzh) {
        Map<String, List<String>> map = new HashMap<>();
        List<String> listbt = new ArrayList<>();
        List<String> listdataindex = new ArrayList<>();
        List<String> listellipsis = new ArrayList<>();

        Map<String, YasuojiJcxx> mapysj = sssjTools.ysjGykbz.stream().collect(Collectors.toMap(YasuojiJcxx::getGykbz, Function.identity(), (k1, k2) -> k2));

        List<YasuojiSj> list = sssjTools.getYasjLsBt(zhanc, jzh);

        if (list.size() == 1) {
            listbt.add("日期");
            listdataindex.add("日期");
            listellipsis.add("false");

            String[] allsj = list.get(0).getShuju().split(" ");
            for (int i = 0; i < allsj.length; i++) {
                String[] ls = allsj[i].split(":");

                if (mapysj.containsKey(ls[0])) {
                    String[] canshuname = mapysj.get(ls[0]).getJldName().split("\\*");
                    String strls1 = canshuname[2];
                    if (strls1.length() == 4 || strls1.length() == 5) {
                        StringBuilder strls2 = new StringBuilder(strls1);
                        strls2.insert(2, "*");
                        listbt.add(strls2.toString());
                    } else if (strls1.length() > 5) {
                        StringBuilder strls2 = new StringBuilder(strls1);
                        strls2.insert(3, "*");
                        listbt.add(strls2.toString());
                    } else {
                        listbt.add(canshuname[2]);
                    }

                    listdataindex.add(canshuname[2]);
                    listellipsis.add("false");
                }
            }
        }

        map.put("ellipsis", listellipsis);
        map.put("title", listbt);
        map.put("dataindex", listdataindex);
//        log.info("bt:"+listbt+" index:"+listdataindex);
        return map;
    }

    //获取压缩机报警数据的表头
    public static Map<String, List<String>> getYasuojBjBt() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> listbt = new ArrayList<>();
        List<String> listdataindex = new ArrayList<>();

        listbt.add("报警名称");
        listbt.add("开始时间");
        listbt.add("报警值");
        listbt.add("报警原因");

        listdataindex.add("bjId");
        listdataindex.add("beginTime");
        listdataindex.add("canshuZhi");
        listdataindex.add("bjMs");

        List<String> listellipsis = new ArrayList<>();
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");

        map.put("ellipsis", listellipsis);
        map.put("title", listbt);
        map.put("dataindex", listdataindex);

        return map;
    }

    //获取计量点历史数据的表头
    public static Map<String, List<String>> getJldLssjBt() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> listbt = new ArrayList<>();
        List<String> listdataindex = new ArrayList<>();

        listbt.add("计量点名称");
        listbt.add("日期");
        listbt.add("温度");
        listbt.add("压力");
        listbt.add("压差");
        listbt.add("瞬时量");
        listbt.add("今日量");
        listbt.add("上月流量");
        listbt.add("本月流量");
        listbt.add("累积量");
        listbt.add("今日时间");
        listbt.add("状态");

        listdataindex.add("jldName");
        listdataindex.add("createTime");
        listdataindex.add("wd");
        listdataindex.add("yl");
        listdataindex.add("yc");
        listdataindex.add("ssll");
        listdataindex.add("jrl");
        listdataindex.add("syll");
        listdataindex.add("byll");
        listdataindex.add("zll");
        listdataindex.add("jrsj");
        listdataindex.add("zt");

        List<String> listellipsis = new ArrayList<>();
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");

        map.put("ellipsis", listellipsis);
        map.put("title", listbt);
        map.put("dataindex", listdataindex);

        return map;
    }

    //获取计量点报警数据的表头
    public static Map<String, List<String>> getJldBjBt() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> listbt = new ArrayList<>();
        List<String> listdataindex = new ArrayList<>();

        listbt.add("报警名称");
        listbt.add("开始时间");
        listbt.add("报警值");
        listbt.add("报警原因");

        listdataindex.add("bjName");
        listdataindex.add("createTime");
        listdataindex.add("bjz");
        listdataindex.add("reason");

        List<String> listellipsis = new ArrayList<>();
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");

        map.put("ellipsis", listellipsis);
        map.put("title", listbt);
        map.put("dataindex", listdataindex);

        return map;
    }

    //获取压缩机报警处置记录的表头
    public static Map<String, List<String>> getJldBjChuzhiBt() {
        Map<String, List<String>> map = new HashMap<>();
        List<String> listbt = new ArrayList<>();
        List<String> listdataindex = new ArrayList<>();
        List<String> listellipsis = new ArrayList<>();

        listbt.add("报警名称");
        listbt.add("报警时间");
        listbt.add("报警信息");
        listbt.add("分析");
        listbt.add("处置措施");
        listbt.add("处置人");
        listbt.add("处置时间");

        listdataindex.add("bjName");
        listdataindex.add("bjTime");
        listdataindex.add("bjMs");
        listdataindex.add("fenxiString");
        listdataindex.add("chuzhicuoshiString");
        listdataindex.add("createBy");
        listdataindex.add("createTime");

        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("false");
        listellipsis.add("true");
        listellipsis.add("true");
        listellipsis.add("false");
        listellipsis.add("false");

        map.put("title", listbt);
        map.put("dataindex", listdataindex);
        map.put("ellipsis", listellipsis);

        return map;
    }

    //获取压缩机报警历史数据
    public static List<CxcSssjLssjBjlsjl> getYasuojbjsj(String bgtime, String endtime, String zc, String jzh) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<CxcSssjLssjBjlsjl> listByzhanc = new ArrayList<>();

        List<YasuojiBjSj> listbj = judge.jldlsMapper.getYsjBjsj(bgtime, endtime);

        List<YasuojiJcxx> listbjByZhanc = sssjTools.ysjGykbz.stream().filter(item -> item.getStationName().equals(zc)).collect(Collectors.toList());

        Map<String, YasuojiJcxx> mapzc = listbjByZhanc.stream().collect(Collectors.toMap(YasuojiJcxx::getGykbz, Function.identity(), (k1, k2) -> k2));
//log.info("listbj:"+listbj.size()+" listbyzhanc:"+listbjByZhanc.size()+" mapzc:"+mapzc.size());
        listbj.forEach(item -> {
            String gykbz = item.getBjId();

            if (mapzc.containsKey(gykbz)) {
                Optional<YasuojiJcxx> jcxx = sssjTools.ysjGykbz.stream().filter(a -> a.getGykbz().equals(gykbz)).findAny();
                if (jcxx.isPresent()) {
//                        log.info("hi:"+jcxx.get().getJldName());
                    String[] jldname = jcxx.get().getJldName().split("\\*");
                    item.setBjId(jldname[2]);
                    if (jldname[1].equals(jzh)) {
                        CxcSssjLssjBjlsjl tmp = new CxcSssjLssjBjlsjl();
                        tmp.setBjName(jldname[2]);
                        tmp.setBjz(String.valueOf(item.getCanshuZhi()));

                        tmp.setCreateTime(item.getBeginTime());

                        tmp.setReason(item.getBjMs());
                        listByzhanc.add(tmp);
                    }


                }
            }
        });

        listByzhanc.forEach(item -> {
//            log.info("id:"+ item.getBjId()+" time:"+item.getCreateTime()+" val:"+item.getReason());
        });
        //            log.info("id:"+ item.getBjId()+" time:"+item.getBeginTime()+" val:"+item.getCanshuZhi());
        return listByzhanc;

    }

    //获取指定站场和压缩机机组号的  工业库标志与参数名的映射表
    public static Map<String, String> getJldnameByJldid(String zc, String jzh) {
        Map<String, String> map = new HashMap<>();

        List<YasuojiJcxx> listByZhanc = sssjTools.ysjGykbz.stream().filter(item -> item.getStationName().equals(zc)).collect(Collectors.toList());
        listByZhanc.forEach(item -> {
            String[] jldname = item.getJldName().split("\\*");
            if (jldname[1].equals(jzh)) {
                map.put(item.getGykbz(), jldname[2]);
            }
        });

        return map;
    }

    /**
     * 将多线程saveData每填8点得到的计量点List存盘方法
     **/
    public static void saveJldlsQi(List<CxcSssjLssjJldlsRsj> saveJldlsQi) {
        judge.rsjService.saveBatch(saveJldlsQi);
    }

    /**
     * 将多线程saveData每秒得到的输差List存盘方法
     **/
    public static void saveScls(List<CxcSssjLssjScls> sclsList) {
        judge.saveSclsService.saveBatch(sclsList);
    }

    // 计算所有输差配置的输差
    public static List<CxcSssjLssjScls> AllScList() throws InterruptedException {
        List<CxcSssjLssjScls> listScData = new ArrayList<>();
        List<CxcSssjSzScsz> listScPz = judge.getScpzService.getAllScpz();
        listScPz.forEach(item -> {
            CxcSssjLssjScls sclsTemp = new CxcSssjLssjScls();
            sclsTemp = getScData(item);
            listScData.add(sclsTemp);
        });
        return listScData;
    }

    // 计算所有输差配置的输差   2022-08-31  Niujl
    public static List<CxcSssjScls> getAllSc(String lb) throws InterruptedException {
        List<CxcScdtScpz> listScPz = judge.getScpzService.getScpzByLb(lb);
        //获取所有计量点实时数据
        List<JldData> listJlData = AllJldlist();
        Map<String, JldData> mapJldDate = listJlData.stream().collect(Collectors.toMap(JldData::getId, a -> a, (k1, k2) -> k1));

        List<CxcSssjScls> listScData = getScByLb(listScPz, mapJldDate);
        return listScData;
    }

    //每天8点计算
    private static CxcSssjLssjJldlsRsj getMyData(String jldIds) {
        List<Map<String, Object>> RsjMouth = judge.rishujuService.getMouthDataByIds(jldIds);

        List<Map<String, Object>> RsjYear = judge.rishujuService.getYearDataByIds(jldIds);

        return null;
    }

    @SneakyThrows
    private static CxcSssjLssjScls getScData(CxcSssjSzScsz listSc) {
        //获取所有计量点实时数据
        List<JldData> listJlData = AllJldlist();

        //输差进气计量点逗号分割字符串
        List<String> strInjld = Arrays.asList(listSc.getInPoints().split(","));

        //输差出气计量点逗号分割字符串
        List<String> strOutjld = Arrays.asList(listSc.getOutPoints().split(","));

        List<JldData> listInJldData = new ArrayList<>();
        listJlData.forEach(item -> {
            strInjld.forEach(item1 -> {
                if (item.getId().equals(item1)) {
                    listInJldData.add(item);
                }
            });
        });


        List<JldData> listOutJldData = new ArrayList<>();

        listJlData.forEach(item -> {
            strOutjld.forEach(item1 -> {
                if (item.getId().equals(item1)) {
                    listOutJldData.add(item);
                }
            });
        });
        double sssc = 0;
        double ssscIn = 0;
        double ssscOut = 0;
        double ssscBfs = 0;

        double jrlsc = 0;
        double jrlscIn = 0;
        double jrlscOut = 0;
        double jrlscbfs = 0;


        if (listInJldData.size() > 0) {
            ssscIn = listInJldData.stream().mapToDouble(item ->
                    parseDouble(item.getSsll() == "" ? "0" : item.getSsll())).sum();

            jrlscIn = listInJldData.stream().mapToDouble(item -> parseDouble(item.getJrl() == "" ? "0" : item.getJrl())).sum();
        }

        if (listOutJldData.size() > 0) {
            ssscOut = listOutJldData.stream().mapToDouble(item -> parseDouble(item.getSsll() == "" ? "0" : item.getSsll())).sum();
            jrlscOut = listOutJldData.stream().mapToDouble(item -> parseDouble(item.getJrl() == "" ? "0" : item.getJrl())).sum();
        }

        sssc = ssscOut - ssscIn;
        if (ssscOut != 0) {
            ssscBfs = sssc / ssscOut;
        } else {
            ssscBfs = 0;
        }
        jrlsc = jrlscOut - jrlscIn;
        if (jrlscOut != 0) {
            jrlscbfs = jrlsc / jrlscOut;
        } else {
            jrlscbfs = 0;
        }
        CxcSssjLssjScls scDataTemp = new CxcSssjLssjScls();
        scDataTemp.setScId(listSc.getId());
        scDataTemp.setScName(listSc.getScName());
        scDataTemp.setDepartId(listSc.getDepartId());
        scDataTemp.setStationId(listSc.getStationId());
        scDataTemp.setInPoints(listSc.getInPoints());
        scDataTemp.setOutPoints(listSc.getOutPoints());
        scDataTemp.setScType(listSc.getScType());

        scDataTemp.setJrlIn(String.format("%.4f", jrlscIn));
        scDataTemp.setJrlOut(String.format("%.4f", jrlscOut));
        scDataTemp.setJrlsc(String.format("%.4f", jrlsc));

        scDataTemp.setSsIn(String.valueOf(ssscIn));
        scDataTemp.setSsOut(String.valueOf(ssscOut));
        scDataTemp.setSssc(String.valueOf(sssc));
        scDataTemp.setSsscbfs(String.valueOf(ssscBfs));
        scDataTemp.setJrlscbfs(String.format("%.4f", jrlscbfs));

        return scDataTemp;
    }

    //    @SneakyThrows
    private static List<CxcSssjScls> getScByLb(List<CxcScdtScpz> listScPz, Map<String, JldData> mapJldDate) {
        List<CxcSssjScls> listsc = new ArrayList<>();

        listScPz.forEach(item -> {
            //输差进气计量点逗号分割字符串
            List<String> strInjld = Arrays.asList(item.getJqjldid().split(","));

            //输差出气计量点逗号分割字符串
            List<String> strOutjld = Arrays.asList(item.getCqjldid().split(","));

            double sssc = 0;
            double ssscIn = 0;
            double ssscOut = 0;
            double ssscBfs = 0;

            double jrlsc = 0;
            double jrlscIn = 0;
            double jrlscOut = 0;
            double jrlscbfs = 0;

            int len = strInjld.size();
            if (len > 0) {
                for (int i = 0; i < len; i++) {
                    String id = strInjld.get(i);
                    if (null != mapJldDate && mapJldDate.containsKey(id)) {
                        String ls1 = mapJldDate.get(id).getSsll();
                        String ls2 = mapJldDate.get(id).getJrl();
                        if (null == ls1 || ls1.isEmpty()) ls1 = "0";
                        if (null == ls2 || ls2.isEmpty()) ls2 = "0";
                        double ls3 = parseDouble(ls1);
                        double ls4 = parseDouble(ls2);
                        ssscIn = douadd(ssscIn, ls3);
                        jrlscIn = douadd(jrlscIn, ls4);
                    }
                }
            }

            len = strOutjld.size();
            if (len > 0) {
                for (int i = 0; i < len; i++) {
                    String id = strOutjld.get(i);
                    if (null != mapJldDate && mapJldDate.containsKey(id)) {
                        String ls1 = mapJldDate.get(id).getSsll();
                        String ls2 = mapJldDate.get(id).getJrl();
                        if (null == ls1 || ls1.isEmpty()) ls1 = "0";
                        if (null == ls2 || ls2.isEmpty()) ls2 = "0";
                        double ls3 = parseDouble(ls1);
                        double ls4 = parseDouble(ls2);
                        ssscOut = douadd(ssscOut, ls3);
                        jrlscOut = douadd(jrlscOut, ls4);
                    }
                }
            }

            sssc = dousub(ssscOut, ssscIn);
            if (ssscOut != 0) {
                ssscBfs = div(sssc, ssscOut);
            } else {
                ssscBfs = 0;
            }
            jrlsc = dousub(jrlscOut, jrlscIn);
            if (jrlscOut != 0) {
                jrlscbfs = div(jrlsc, jrlscOut);
            } else {
                jrlscbfs = 0;
            }

            CxcSssjScls scDataTemp = new CxcSssjScls();
            scDataTemp.setScId(item.getId());
            scDataTemp.setScName(item.getScmc());
            scDataTemp.setStationId(item.getSysOrgCode());
            scDataTemp.setScType(item.getSclb());

            scDataTemp.setJrlIn(jrlscIn);
            scDataTemp.setJrlOut(jrlscOut);
            scDataTemp.setJrlsc(jrlsc);

            scDataTemp.setSsIn(ssscIn);
            scDataTemp.setSsOut(ssscOut);
            scDataTemp.setSssc(sssc);
            scDataTemp.setSsscbfs(ssscBfs);
            scDataTemp.setJrlscbfs(jrlscbfs);

            listsc.add(scDataTemp);

        });

        return listsc;
    }

    /**
     * 计量点基础信息列表中计量点数据信息读取
     * 与实时采集中的数据 通过tagid 拼成包含压力温度流量等形式的计量点
     *
     * @return List<Jlddata> jlddata
     */
    public static List<JldData> AllJldlist() throws InterruptedException {
        // 在这里
        Map<String, CxcScdtJldxx> jldxx = judge.getScpzService.getScdtJldId();
        List<CxcSssjSzJldxx> listAllJl = judge.getJldXxService.getAllJldxx("0");


        List<JldData> jlddata = new ArrayList<>();
        listAllJl.forEach(item -> {
            JldData jldDataTemp = new JldData();
            jldDataTemp.setId(item.getId());
            jldDataTemp.setZhan(item.getStationName());

            String jldName = item.getJldName().replace("_", "-").substring(2);

            //从生产动态模块查询计量点名字，获取计量点ID来替换实时数据获取的计量点的ID
            if (null != jldxx && jldxx.containsKey(jldName)) {
                jldDataTemp.setId(jldxx.get(jldName).getId());
                jldDataTemp.setZhan(jldxx.get(jldName).getZcmc());
                //设置进出站类型 by 闵
                jldDataTemp.setJczlx(jldxx.get(jldName).getJczlx());
            }
            jldDataTemp.setSqDw(item.getSqDw()); //新增输差配置 by 闵
            jldDataTemp.setJldname(jldName);
            jldDataTemp.setQu(item.getDepartName());
            jldDataTemp.setDepart_id(item.getDepartId());
            jldDataTemp.setStation_id(item.getStationId());

            jldDataTemp.setGykbz(item.getGykbz());
            jlddata.add(jldDataTemp);
        });
        Map GykDataList = KDBClient.MapJldData();
        jlddata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            try {
                String ls = item.getGykbz();
                if (ls != null && ls != "") {
                    gykbz = item.getGykbz().split(",");

                    gykValue = new double[gykbz.length];
                    for (int i = 0; i < gykbz.length; i++) {
                        gykValue[i] = 0.0;
                        if (i == 0 || i == 6 || i == 9) {
                            gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString()) / 10000;
                        } else {
                            gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
                        }
                    }
                    item.setSyll(String.format("%.4f", gykValue[0]));
                    item.setJrsj(String.format("%.1f", gykValue[1]));
                    item.setJrl(String.format("%.2f", gykValue[2]));
                    item.setYl(String.format("%.3f", gykValue[3]));
                    item.setYc(String.format("%.3f", gykValue[4]));
                    item.setBz("");
                    item.setZll(String.format("%.4f", gykValue[6]));
                    item.setZrsj(String.format("%.1f", gykValue[7]));
                    item.setZrl(String.format("%.2f", gykValue[8]));
                    item.setByll(String.format("%.4f", gykValue[9]));
                    item.setWd(String.format("%.2f", gykValue[10]));
                    if (gykValue[11] == 0.0) {
                        item.setYxzt("停表");
                    } else if (gykValue[11] == 1.0) {
                        item.setYxzt("运行");
                    } else {
                        item.setYxzt("其他");
                    }
                    item.setSsll(String.format("%.2f", gykValue[12]));
                }
            } catch (Exception e) {
            }

        });

//        jlddata.forEach(item->{
//            System.out.println("#"+item.getId());
//        });

        return (jlddata);
    }

    public static String getbjval(String canshu) {
        String res = "";
        switch (canshu) {
            case "温度":
                res = "WD";
                break;
            case "压力":
                res = "YL";
                break;
            case "压差":
                res = "YC";
                break;
        }
        return res;
    }

    public static List<JldData> getJldSssj(String zhanc) {
//        sssjTools sssjTools = new sssjTools();
        List<JldData> listAll = null;
        try {
            listAll = sssjTools.AllJldlist();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //筛选出station_id等于参数"zhanc"的计量点组成list
        List<JldData> listZhan = listAll.stream().filter(item -> item.getStation_id().equals(zhanc)).collect(Collectors.toList());
        listZhan.forEach(item -> {
            item.setBjzt("");
            if (item.getGykbz() != null && !item.getGykbz().isEmpty()) {
                String gykid[] = item.getGykbz().split("\\,");

                for (int i = 0; i < gykid.length; i++) {
                    String ls = gykid[i];
                    String ls1 = ls + "WG";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "W" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "WD";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "W" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "BG";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "B" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "BD";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "B" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                }
            }

        });

        return listZhan;
    }

    /**
    * @Description: 利用首页输差赛选
    * @author: 闵年泽
    * @date: 2024/7/26 15:29
    * @param id:
    * @Return: java.util.List<org.gyk.modules.sssj.entity.JldData>
    */
    public static List<JldData> getJldSssjBySqDw(String id) {
//        sssjTools sssjTools = new sssjTools();
        List<JldData> listAll = null;
        try {
            listAll = sssjTools.AllJldlist();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //筛选出station_id等于参数"zhanc"的计量点组成list
        List<JldData> listZhan = listAll.stream().filter(item ->{
            if (StringUtils.isEmpty(item.getSqDw())) return false;
           return item.getSqDw().contains(id);
        }).collect(Collectors.toList());
        listZhan.forEach(item -> {
            item.setBjzt("");
            if (item.getGykbz() != null && !item.getGykbz().isEmpty()) {
                String gykid[] = item.getGykbz().split("\\,");

                for (int i = 0; i < gykid.length; i++) {
                    String ls = gykid[i];
                    String ls1 = ls + "WG";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "W" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "WD";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "W" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "BG";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "B" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                    ls1 = ls + "BD";
                    if (mapTrqbjsj.containsKey(ls1)) {
                        String name = mapTrqbjsj.get(ls1).getBjName();
                        String strcs = name.substring(name.length() - 2);
                        String ls2 = item.getBjzt() + "B" + getbjval(strcs);
                        item.setBjzt(ls2);
                    }
                }
            }

        });

        return listZhan;
    }


    /**
     * 提供精确的加法运算。
     *
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
    public static Double douadd(Number value1, Number value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
        BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确的减法运算。
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     */
    public static double dousub(Number value1, Number value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
        BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供（相对）精确的除法运算，当发生除不尽的情况时， 精确到小数点以后10位，以后的数字四舍五入。
     *
     * @param dividend 被除数
     * @param divisor  除数
     * @return 两个参数的商
     */
    public static Double div(Double dividend, Double divisor) {
        return div(dividend, divisor, DEF_DIV_SCALE);
    }

    /**
     * 提供（相对）精确的除法运算。 当发生除不尽的情况时，由scale参数指定精度，以后的数字四舍五入。
     *
     * @param dividend 被除数
     * @param divisor  除数
     * @param scale    表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static Double div(Double dividend, Double divisor, Integer scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(dividend));
        BigDecimal b2 = new BigDecimal(Double.toString(divisor));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 提供精确的小数位四舍五入处理。
     *
     * @param value 需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static Double round(Double value, Integer scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(value));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static Double add(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.add(b2).doubleValue();
    }

    /**
     * 两个Double数相减
     *
     * @param v1
     * @param v2
     * @return Double
     */
    public static Double sub(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 两个Double数相乘
     *
     * @param v1
     * @param v2
     * @return Double
     */
    public static Double mul(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.multiply(b2).doubleValue();
    }


    /**
     * 计量点基础信息列表中工艺数据信息读取
     *
     * @return List<Jlddata> jlddata
     */
    public static List<JldData> AllGylist() throws InterruptedException {
        List<CxcSssjSzJldxx> listAllGy = judge.getJldXxService.getAllJldxx("2");
        List<JldData> gykrdata = new ArrayList<>();
        listAllGy.forEach(item -> {
            JldData jldDataTemp = new JldData();
            jldDataTemp.setId(item.getId());
            jldDataTemp.setJldname(item.getJldName().replace("_", "-"));
            jldDataTemp.setQu(item.getDepartName());
            jldDataTemp.setDepart_id(item.getDepartId());
            jldDataTemp.setStation_id(item.getStationId());
            jldDataTemp.setZhan(item.getStationName());
            jldDataTemp.setGykbz(item.getGykbz());
            jldDataTemp.setJlddw(item.getJlddw());
            gykrdata.add(jldDataTemp);
        });
        Map GykDataList = KDBClient.MapJldData();
        gykrdata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            String krqzt = "";
            try {
                gykbz = item.getGykbz().split(",");
                gykValue = new double[gykbz.length];
                for (int i = 0; i < gykbz.length; i++) {
                    gykValue[i] = 0.0;
                    gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
                }
                item.setGyvalue(String.format("%.4f", gykValue[0]));
//				 将工业库中仪表状态值从double型转为字符串再分割取整
                String krqzt1 = String.valueOf(gykValue[1]).split("\\.")[0];
                switch (krqzt1) {
                    case "0":
                        krqzt = "正常";
                        break;
                    case "1":
                        krqzt = "高报";
                        break;
                    case "2":
                        krqzt = "高高报警";
                        break;
                    case "3":
                        krqzt = "高信号故障";
                        break;
                    case "4":
                        krqzt = "高高信号故障";
                        break;
                    case "5":
                        krqzt = "未接";
                        break;
                    case "6":
                        krqzt = "硬件高报";
                        break;
                    case "7":
                        krqzt = "硬件高高报警";
                        break;
                    case "256":
                        krqzt = "通讯错误";
                        break;
                    case "512":
                        krqzt = "通讯来数据";
                        break;
                    case "768":
                        krqzt = "通信正常";
                        break;
                    default:
                        krqzt = "未知";
                }
                item.setKrzt(krqzt);
            } catch (Exception e) {
            }
        });
        return (gykrdata);
    }

    /**
     * 计量点基础信息列表中压缩机数据信息读取
     *
     * @return List<Jlddata> jlddata
     */
    public static List<JldData> AllYslist() throws InterruptedException {
        //初步考虑，在cxc_sssj_sz_jldxx中的备注字段中增加压缩机型号，或者使用 ssgx1,ssgx2连个字段分别存储压缩机型号和参数名
        List<CxcSssjSzJldxx> listAllYs = judge.getJldXxService.getAllJldxx("4");
        List<JldData> ysdata = new ArrayList<>();
        listAllYs.forEach(item -> {
            JldData jldDataTemp = new JldData();
            jldDataTemp.setId(item.getId());
            jldDataTemp.setJldname(item.getJldName().replace("_", "-"));
            jldDataTemp.setQu(item.getDepartName());
            jldDataTemp.setDepart_id(item.getDepartId());
            jldDataTemp.setStation_id(item.getStationId());
            jldDataTemp.setZhan(item.getStationName());
            jldDataTemp.setGykbz(item.getGykbz());
            jldDataTemp.setJlddw(item.getJlddw());
            ysdata.add(jldDataTemp);
        });
        Map GykDataList = KDBClient.MapJldData();
        ysdata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            try {
                gykbz = item.getGykbz().split(",");
                gykValue = new double[gykbz.length];
                for (int i = 0; i < gykbz.length; i++) {
                    gykValue[i] = 0.0;
                    gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
                }
                if (item.getJldname().indexOf("缸温") != -1 || item.getJldname().indexOf("水温") != -1 || item.getJldname().indexOf("温度") != -1 || item.getJldname().indexOf("油温") != -1) {
                    item.setYsvalue(String.format("%.1f", gykValue[0]));
                } else if (item.getJldname().indexOf("油压") != -1 || item.getJldname().indexOf("压力") != -1 || item.getJldname().indexOf("振动") != -1) {
                    item.setYsvalue(String.format("%.2f", gykValue[0]));
                } else if (item.getJldname().indexOf("转速") != -1) {
                    item.setYsvalue(String.format("%.0f", gykValue[0]));
                } else {
                    item.setYsvalue(String.format("%.4f", gykValue[0]));
                }

            } catch (Exception e) {
            }
        });
        return (ysdata);
    }

    /**
     * 计量点基础信息列表中偏远站数据信息读取
     *
     * @return List<Jlddata> jlddata
     */
    public static List<PianyuanZhan> getPylist() throws InterruptedException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<CxcSssjSzJldxx> listAllPy = judge.getJldXxService.getAllJldxx("5");

        Map GykDataList = KDBClient.MapJldData();

        String rqb="";
        String rqh="";
        LocalDateTime dateTime1 = LocalDateTime.now();
//        LocalDateTime dateTime1 = LocalDateTime.of(2024,1,8,6,5,0);
        //当天8点
        LocalDateTime dateTime2 = dateTime1.withHour(8);
        if (dateTime2.isAfter(dateTime1)) {
            rqb= dateTime2.plusDays(-2).format(formatter);
            rqh= dateTime2.plusDays(-1).format(formatter);
        } else {
            rqb= dateTime2.plusDays(-1).format(formatter);
            rqh = dateTime2.format(formatter);
        }

//        PianYuan pianYuan= new PianYuan();
        mapzrlj = judge.getZuoribklj(rqb,rqh);

        Map<String, PianyuanZhan> pydata = new HashMap<>();
        listAllPy.forEach(item -> {
            String[] jldname = item.getJldName().split("\\*");
            String gykbz = item.getGykbz().trim();
            String val = GykDataList.get(Integer.parseInt(gykbz)).toString();

            PianyuanZhan py = new PianyuanZhan();
            py.setJldname(jldname[1]);

            if (pydata.containsKey(jldname[1])) {
                py = pydata.get(jldname[1]);
            }

            PianyuanZhan pyres = xiugaiPiany(py, jldname[2], val);
            pydata.put(jldname[1], pyres);

        });

        if (pydata.containsKey("三气厂")) {
//            val2 * 1000000 + val1
            double bd = 0.0;
            double bg = 0.0;
            if ((pydata.get("三气厂").getBkzl6() != null && pydata.get("三气厂").getBkzl4() != null)) {
                bd = Double.parseDouble(pydata.get("三气厂").getBkzl6());
                bg = Double.parseDouble(pydata.get("三气厂").getBkzl4());
            }

            double ls = add(mul(bg, 1000000.0), bd);

            PianyuanZhan py = pydata.get("三气厂");
            py.setBkzl(String.format("%.4f", ls));

        }

        List<PianyuanZhan> reslist = new ArrayList<>();
        pydata.forEach((k, v) -> {
            if (mapzrlj.containsKey(k)) {
                v.setZrbklj(mapzrlj.get(k));
            }

            reslist.add(v);
        });

        return (reslist);
    }

    @Cacheable(value = "sqlBj", key = "'bklj'+#rq")
    public Map<String, String> getZuoribklj(String rq1,String rq2) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<PianyuanZhan> list = judge.jldlsMapper.listPiany(rq1);
        Map<String, String> mapday1 = new HashMap<>();
        Map<String, String> mapday2 = new HashMap<>();
        Map<String, String> mapres = new HashMap<>();
        list.forEach(item -> {
            if (item.getRq().format(formatter).equals(rq1)) {
                mapday1.put(item.getJldname(), item.getBkzl());  //昨天数据
            } else if (item.getRq().format(formatter).equals(rq2)){
                mapday2.put(item.getJldname(), item.getBkzl()); //今天数据
            }
            mapres.put(item.getJldname(), "0.0");
        });
        for (Map.Entry<String, String> entry : mapres.entrySet()) {
            String key = entry.getKey();
            double bklj1 = 0.0;
            double bklj2 = 0.0;
            if (mapday1.containsKey(key) && mapday1.get(key) != null) {
                bklj1 = Double.parseDouble(mapday1.get(key));
            }
            if (mapday2.containsKey(key) && mapday2.get(key) != null) {
                bklj2 = Double.parseDouble(mapday2.get(key));
            }
            double bkls = 0.0;
            if (bklj1>1 && bklj2>1) {
                bkls=sub(bklj2, bklj1);
            }

            mapres.put(key, String.format("%.4f", Math.abs(bkls)));
        }
        return mapres;
    }

    public static PianyuanZhan xiugaiPiany(PianyuanZhan py, String nm, String val) {
        switch (nm) {
            case "温度":
                py.setWd(val);
                break;
            case "压力":
                py.setYali(val);
                break;
            case "工况瞬时":
                py.setGkss(val);
                break;
            case "标况瞬时":
                py.setBkss(val);
                break;
            case "工况总量":
                py.setGkzl(val);
                break;
            case "标况总量":
                py.setBkzl(val);
                break;
            case "标况总累低6位":
                py.setBkzl6(val);
                break;
            case "标况总累高4位":
                py.setBkzl4(val);
                break;
            case "昨日标况累计":
                double ls = div(Double.parseDouble(val),1000.0,4);
                py.setZrbklj(String.format("%.4f",ls));
                break;
            default:
                break;
        }
        return py;
    }

    public static List<PianyuanZhan> pianyuan8list() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        String rq="";
        LocalDateTime dateTime1 = LocalDateTime.now();
        rq= dateTime1.plusDays(-2).format(formatter);
        LocalDate edate = LocalDate.from(dateTime1);
        LocalDate sdate = LocalDate.from(dateTime1.plusDays(-2));

        LocalDate date = sdate;
        Map<String,PianyuanZhan> map = new HashMap<>();
        while (!date.isAfter(edate)) {
            PianyuanZhan py = new PianyuanZhan();
            py.setJldname("白九来气");
            LocalDate localDate = LocalDate.parse(date.format(formatter),DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDateTime localDateTime = localDate.atTime(8,0);

            py.setRq(localDateTime);
            py.setId(UUID.randomUUID().toString());
            map.put("白九来气"+date,py);
            PianyuanZhan py2 = new PianyuanZhan();
            py2.setJldname("东明站来气");
            py2.setRq(localDateTime);
            py2.setId(UUID.randomUUID().toString());
            map.put("东明站来气"+date,py2);

            date = date.plusDays(1);
        }

        List<PianyuanZhan> list = judge.jldlsMapper.listPiany(rq);
        list.forEach(item->{
            String nm = item.getJldname();
            String lsrq = item.getRq().format(formatter);
            map.put(nm+lsrq,item);
        });

        List<PianyuanZhan> listres = new ArrayList<>();
        map.forEach((k,v)->{
            listres.add(v);
        });

        listres.sort(((o1, o2) -> o1.getRq().compareTo(o2.getRq())));
//        List<PianyuanZhan> res = Collectors.sort(listres)

        return listres;
    }

   @CacheEvict(value = "sqlBj", key = "'bklj'+#rq2")
    public  void pianyuan8edit(String jldname,String rq,String bkzl,String rq2) {
        judge.jldlsMapper.editPianyuan8(UUID.randomUUID().toString(),jldname,rq,bkzl);
    }

    /**
     * 计量点基础信息列表中可燃数据信息读取
     * @auther jiang 20240313
     * @return List<Jlddata> jlddata
     */
    public static List<JldData> AllKrlist() throws InterruptedException {
        List<CxcSssjSzJldxx> listAllKr = judge.getJldXxService.getAllJldxx("1");
        List<JldData> gykrdata = new ArrayList<>();
        listAllKr.forEach(item -> {
            JldData jldDataTemp = new JldData();
            jldDataTemp.setId(item.getId());
            jldDataTemp.setJldname(item.getJldName().replace("_", "-"));
            jldDataTemp.setQu(item.getDepartName());
            jldDataTemp.setDepart_id(item.getDepartId());
            jldDataTemp.setStation_id(item.getStationId());
            jldDataTemp.setZhan(item.getStationName());
            jldDataTemp.setGykbz(item.getGykbz());
            jldDataTemp.setJlddw(item.getJlddw());
            gykrdata.add(jldDataTemp);
        });
        Map GykDataList = KDBClient.MapJldData();
        gykrdata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            String krqzt = "";

            LocalDateTime now = LocalDateTime.now();
            try {
                gykbz = item.getGykbz().split(",");
                gykValue = new double[gykbz.length];
                for (int i = 0; i < gykbz.length; i++) {
                    gykValue[i] = 0.0;
                    gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
                }
                item.setKrvalue(String.format("%.6f", gykValue[0]));
                //判断值是否超过阈值
                if (Double.parseDouble(item.getKrvalue()) > KrWarning) {
                    krqzt = "异常";
                    //先检查map 中有没有数据。如果有更新下最后时间。
                    //键是工业库标志
                    if (mapbjsj.containsKey(item.getGykbz())) {
                        mapbjsj.get(item.getGykbz()).setEndTime(now);
                    // 如果没有就新增一条
                    } else {
                        AtomicReference<String> zhan = new AtomicReference<>("");
                        List<CxcSssjSzJldxx> krkbz = judge.getJldXxService.getJldxxById(item.getId());
                        krkbz.forEach(kr ->{
                            zhan.set(kr.getStationId());
                        });
                        // 将异常信息存到CxcSssjLssjBjlsjl 实体类中，再将实体类存到mapKrbjsj中
                        CxcSssjLssjBjlsjl krBj = new CxcSssjLssjBjlsjl();
                        krBj.setBjId(item.getGykbz());//报警点ID
                        krBj.setCreateTime(now);//报警时间
                        krBj.setBjName(item.getJldname());//报警计量点名称
                        krBj.setBz(zhan.get());
                        krBj.setBjz(item.getKrvalue()); //报警值
                        krBj.setReason(krqzt); // 报警描述
                        krBj.setJlbz("3"); // 报警标志,可燃是3
                        krBj.setZt("1"); //状态 未处置为1 已处置状态为0
                        mapKrbjsj.put(item.getGykbz(), krBj);
                    }
                } else {
                    krqzt = "正常";
                }
                item.setKrzt(krqzt);
            } catch (Exception ignored) {
            }
        });
        return (gykrdata);
    }

    /**
     * 根据bjid或者是工业库标识 查询报警表中有无报警记录，报警记录是否处置
     * @return ture false
     * @throws InterruptedException
     * @auther jiang 20240313
     */
    public static boolean queryBjxx(String bjid) throws InterruptedException {
        //根据bjid或者工业库标识查询未处置的报警记录
        List<CxcSssjLssjBjlsjl> bjxxList = judge.saveBjlsService.getWczBjxx(bjid);
        //list有值返回true，否者返回false
        if(bjxxList.isEmpty()){
            return false;
        }else {
            return true;
        }
    }

    public static List<JldData> AllPylist() throws InterruptedException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<CxcSssjSzJldxx> listAllPy = judge.getJldXxService.getAllJldxx("5");

        String rqb="";
        String rqh="";
        LocalDateTime dateTime1 = LocalDateTime.now();
//        LocalDateTime dateTime1 = LocalDateTime.of(2024,1,8,6,5,0);
        //当天8点
        LocalDateTime dateTime2 = dateTime1.withHour(8);
        if (dateTime2.isAfter(dateTime1)) {
            rqb= dateTime2.plusDays(-2).format(formatter);
            rqh= dateTime2.plusDays(-1).format(formatter);
        } else {
            rqb= dateTime2.plusDays(-1).format(formatter);
            rqh = dateTime2.format(formatter);
        }
        mapzrlj = judge.getZuoribklj(rqb,rqh);
        List<JldData> pydata = new ArrayList<>();
        listAllPy.forEach(item -> {
            JldData jldDataTemp = new JldData();
            jldDataTemp.setId(item.getId());
            jldDataTemp.setJldname(item.getJldName());
            jldDataTemp.setQu(item.getDepartName());
            jldDataTemp.setDepart_id(item.getDepartId());
            jldDataTemp.setStation_id(item.getStationId());
            jldDataTemp.setZhan(item.getStationName());
            jldDataTemp.setGykbz(item.getGykbz());
            jldDataTemp.setJlddw(item.getJlddw());
            pydata.add(jldDataTemp);
        });
        Map GykDataList = KDBClient.MapJldData();
        pydata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            try {
                gykbz = item.getGykbz().split(",");
                gykValue = new double[gykbz.length];
                for (int i = 0; i < gykbz.length; i++) {
                    gykValue[i] = 0.0;
//                    String key = gykbz[i];
                    gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
//                    if (GykDataList.containsKey(key)) {
//                        gykValue[i] = Double.parseDouble((String) GykDataList.get(key));
//                    }
                }
                item.setYsvalue(String.format("%.4f", gykValue[0]));

                String[] jldnm=item.getJldname().split("\\*");
                if (jldnm[2].equals("昨日标况累计")) {
                    if (mapzrlj.containsKey(jldnm[1])) {
                        item.setYsvalue(mapzrlj.get(jldnm[1]));
                    }
                }

            } catch (Exception e) {
            }
        });
        return (pydata);
    }

    /**
     * 通过报警设置，比对实时数据，满足报警条件的数据存入报警历史记录
     *
     * @return Result<String>
     */
//    public static List<CxcSssjSzBjsz> GetBjz(String strGykbz) {
//
//        LambdaQueryWrapper<CxcSssjSzBjsz> queryWrapper = new LambdaQueryWrapper<CxcSssjSzBjsz>();
//        List<CxcSssjSzBjsz> listAll = judge.bjszMapper.selectList(queryWrapper);
//        return listAll;
//    }
    public static String getbj(float bj, float ddb, float db, float gb, float ggb) {
        if (bj <= db) {
            if (bj <= ddb) {
                return "低低报";
            } else
                return "低报";
        }

        if (bj >= gb) {
            if (bj >= ggb) {
                return "高高报";
            } else
                return "高报";
        }
        return "0";
    }

    /**
     * 通过报警设置，比对实时数据，满足报警条件的数据存入报警历史记录
     *
     * @return Result<String>
     */

//    @Cacheable(value = "bjpz", key = "#root.methodName")
//    public List<CxcSssjSzBjsz> GetBjz() {
//        LambdaQueryWrapper<CxcSssjSzBjsz> queryWrapper = new LambdaQueryWrapper<CxcSssjSzBjsz>();
//        List<CxcSssjSzBjsz> listAll = judge.bjszMapper.selectList(queryWrapper);
//        return listAll;
//    }

    //通过cxc_sssj_jld_bj_canshu_sz 、cxc+sssj_jld_bj_shezhi两个表获取设置的报警GYKID和设定的报警值
    public static List<CxcSssjSzBjsz> getJldBjsz() {
        DecimalFormat df = new DecimalFormat("0.0000");

        Map<String, CxcSssjJldBjCanshuSz> mapcs = judge.cxcSssjJldBjCanshuSzService.getbjcs();

        List<CxcSssjJldBjShezhi> listallbjjld = judge.cxcSssjJldBjShezhiService.list();
        List<CxcSssjSzBjsz> listjldbj = new ArrayList<>();
        if (listallbjjld.size() > 0) {
            listallbjjld.forEach(item -> {
                if (item.getWdBjcs() != null && !item.getWdBjcs().trim().isEmpty()) {
                    if (mapcs.containsKey(item.getWdBjcs())) {
                        CxcSssjSzBjsz cxcSssjSzBjsz = new CxcSssjSzBjsz();
                        cxcSssjSzBjsz.setBjName(item.getJldname() + "温度");
                        cxcSssjSzBjsz.setId(item.getWdGykid());
                        if (mapcs.get(item.getWdBjcs()).getBaojingdi() != null) {
                            cxcSssjSzBjsz.setDbj(df.format(mapcs.get(item.getWdBjcs()).getBaojingdi()));
                        }
                        if (mapcs.get(item.getWdBjcs()).getBaojinggao() != null) {
                            cxcSssjSzBjsz.setGbj(df.format(mapcs.get(item.getWdBjcs()).getBaojinggao()));
                        }
                        if (mapcs.get(item.getWdBjcs()).getWeixiandi() != null) {
                            cxcSssjSzBjsz.setDdbj(df.format(mapcs.get(item.getWdBjcs()).getWeixiandi()));
                        }
                        if (mapcs.get(item.getWdBjcs()).getWeixiangao() != null) {
                            cxcSssjSzBjsz.setGgbj(df.format(mapcs.get(item.getWdBjcs()).getWeixiangao()));
                        }

                        cxcSssjSzBjsz.setSfbj("是");

                        listjldbj.add(cxcSssjSzBjsz);
                    }
                }

                if (item.getYlBjcs() != null && !item.getYlBjcs().trim().isEmpty()) {
                    if (mapcs.containsKey(item.getYlBjcs())) {
                        CxcSssjSzBjsz cxcSssjSzBjsz = new CxcSssjSzBjsz();
                        cxcSssjSzBjsz.setBjName(item.getJldname() + "压力");
                        cxcSssjSzBjsz.setId(item.getYlGykid());
                        if (mapcs.get(item.getYlBjcs()).getBaojingdi() != null) {
                            cxcSssjSzBjsz.setDbj(df.format(mapcs.get(item.getYlBjcs()).getBaojingdi()));
                        }
                        if (mapcs.get(item.getYlBjcs()).getBaojinggao() != null) {
                            cxcSssjSzBjsz.setGbj(df.format(mapcs.get(item.getYlBjcs()).getBaojinggao()));
                        }
                        if (mapcs.get(item.getYlBjcs()).getWeixiandi() != null) {
                            cxcSssjSzBjsz.setDdbj(df.format(mapcs.get(item.getYlBjcs()).getWeixiandi()));
                        }
                        if (mapcs.get(item.getYlBjcs()).getWeixiangao() != null) {
                            cxcSssjSzBjsz.setGgbj(df.format(mapcs.get(item.getYlBjcs()).getWeixiangao()));
                        }
                        cxcSssjSzBjsz.setSfbj("是");

                        listjldbj.add(cxcSssjSzBjsz);
                    }
                }

                if (item.getYcBjcs() != null && !item.getYcBjcs().trim().isEmpty()) {
                    if (mapcs.containsKey(item.getYcBjcs())) {
                        CxcSssjSzBjsz cxcSssjSzBjsz = new CxcSssjSzBjsz();
                        cxcSssjSzBjsz.setBjName(item.getJldname() + "压差");
                        cxcSssjSzBjsz.setId(item.getYcGykid());
                        if (mapcs.get(item.getYcBjcs()).getBaojingdi() != null) {
                            cxcSssjSzBjsz.setDbj(df.format(mapcs.get(item.getYcBjcs()).getBaojingdi()));
                        }
                        if (mapcs.get(item.getYcBjcs()).getBaojinggao() != null) {
                            cxcSssjSzBjsz.setGbj(df.format(mapcs.get(item.getYcBjcs()).getBaojinggao()));
                        }
                        if (mapcs.get(item.getYcBjcs()).getWeixiandi() != null) {
                            cxcSssjSzBjsz.setDdbj(df.format(mapcs.get(item.getYcBjcs()).getWeixiandi()));
                        }
                        if (mapcs.get(item.getYcBjcs()).getWeixiangao() != null) {
                            cxcSssjSzBjsz.setGgbj(df.format(mapcs.get(item.getYcBjcs()).getWeixiangao()));
                        }
                        cxcSssjSzBjsz.setSfbj("是");

                        listjldbj.add(cxcSssjSzBjsz);
                    }
                }

            });
        }

        return listjldbj;
    }

    /* 查询报警设置的数据库表中所有报警设置的报警信息  */
    public static List<CxcSssjLssjBjlsjl> GetAllBj() throws InterruptedException {
        DateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.0000");

        List<CxcSssjSzBjsz> listjldbj = getJldBjsz();

        Map GykDataMap = KDBClient.MapJldData();
        List<CxcSssjLssjBjlsjl> listBjxx = new ArrayList<CxcSssjLssjBjlsjl>();

        listjldbj.forEach(item -> {
            String flag = "N";

            float ggbj = 9999999;
            float gbj = 9999999;
            float ddbj = 9999999;
            float dbj = 9999999;

            if (item.getGgbj() != null && !item.getGgbj().trim().isEmpty()) {
                ggbj = Float.parseFloat(item.getGgbj());
            }
            if (item.getDdbj() != null && !item.getDdbj().trim().isEmpty()) {
                ddbj = Float.parseFloat(item.getDdbj());
            }
            if (item.getDbj() != null && !item.getDbj().trim().isEmpty()) {
                dbj = Float.parseFloat(item.getDbj());
            }
            if (item.getGbj() != null && !item.getGbj().trim().isEmpty()) {
                gbj = Float.parseFloat(item.getGbj());
            }

            String value = GykDataMap.get(Integer.parseInt(item.getId())).toString();

            if (value != null) {
                float gykValue = Float.parseFloat(value);

                int jb = 0;

                if (ggbj != 9999999 && gykValue >= ggbj) {
                    jb = jb + 10000;
                }
                if (ddbj != 9999999 && gykValue <= ddbj) {
                    jb = jb + 1000;
                }
                if (gbj != 9999999 && gykValue >= gbj) {
                    jb = jb + 100;
                }
                if (dbj != 9999999 && gykValue <= dbj) {
                    jb = jb + 10;
                }

                String reason = "";
                if (jb != 0) {
                    if (jb >= 10000) {
                        flag = "BG";
                        reason = "高高报";
                    }
                    if (jb < 10000 && jb >= 1000) {
                        flag = "BD";
                        reason = "低低报";
                    }
                    if (jb < 1000 && jb >= 100) {
                        flag = "WG";
                        reason = "高报";
                    }
                    if (jb < 100 && jb >= 10) {
                        flag = "WD";
                        reason = "低报";
                    }

                    CxcSssjLssjBjlsjl tempBj = new CxcSssjLssjBjlsjl();
                    tempBj.setBjName(item.getBjName());
                    tempBj.setBjId(item.getId());
                    tempBj.setBjz(df.format(gykValue));
                    tempBj.setBz(gykbzGetJcxx.get(item.getId()).getStationName());

                    tempBj.setReason(reason);
                    tempBj.setSdz("低低报警:" + df.format(ddbj) + "低报警:" + df.format(dbj) + "高报警:" + df.format(gbj) + "高高报警:" + df.format(ggbj));

                    LocalDateTime now = LocalDateTime.now();

                    if (mapTrqbjsj.containsKey(item.getId() + flag)) {
                        mapTrqbjsj.get(item.getId() + flag).setEndTime(now);
                    } else {
//                        tempBj.setId(UUID.randomUUID().toString());
                        tempBj.setCreateTime(now);
                        tempBj.setEndTime(now);
                        tempBj.setSaveflag(false);
                        tempBj.setJlbz("1"); //标志1代表是天然气计量点报警数据，2代表工艺，3代表可燃气体

                        mapTrqbjsj.put(item.getId() + flag, tempBj);
                    }

                }
            }
        });

        return listBjxx;
    }

    /* 查询报警设置的数据库表中所有报警设置的报警信息  */
    public static void GetYasuoBj() throws InterruptedException {
        //获取所有的报警设置
        Map<String, YasuojiBjCanshu> mapbjcanshu = judge.cxcSssjSzBjszService.GetYsjBjz();
//        mapbjcanshu.forEach((k,v)->{
//            log.info("hi:"+v.getGykbz()+" gg:"+v.getTingjiGao()+" g:"+v.getBaojingGao()+" dd:"+v.getTingjiDi()+" d:"+v.getBaojingDi());
//        });

        Map GykDataMap = KDBClient.MapJldData();
//        List<YasuojiSssj> Ysjsssj = new ArrayList<>();
        Ysjsssj.clear();

//        DateFormat dateTimeFormatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");

        ysjGykbz = judge.getJldXxService.getYsjGykbz("4");

        Map<String, YasuojiJcxx> mapGykbzToYsjJcxx = ysjGykbz.stream().collect(Collectors.toMap(YasuojiJcxx::getGykbz, Function.identity(), (key1, key2) -> key2));

//        log.info("total:"+ mapGykbzToYsjJcxx.size());
        ysjGykbz.forEach(item -> {
            Integer gykbz = Integer.parseInt(item.getGykbz());

            if (GykDataMap.containsKey(gykbz)) {
                YasuojiSssj tmp = new YasuojiSssj();
                tmp.setGykbz(item.getGykbz());
                tmp.setStationId(item.getStationId());
                tmp.setJldName(item.getJldName());
                tmp.setVal(Float.parseFloat(GykDataMap.get(gykbz).toString()));

                Ysjsssj.add(tmp);
            }
        });

        for (YasuojiSssj item : Ysjsssj) {
            float gykval = item.getVal();
            double tj_di = -999999;
            double tj_gao = 999999;
            double bj_di = -999999;
            double bj_gao = 999999;
            String msg = "";
            String flag = "N";

            if (mapbjcanshu.containsKey(item.getGykbz())) {
                String k = item.getGykbz();

                if (mapbjcanshu.get(k).getTingjiDi() != null) {
                    tj_di = mapbjcanshu.get(k).getTingjiDi();
                }
                if (mapbjcanshu.get(k).getTingjiGao() != null) {
                    tj_gao = mapbjcanshu.get(k).getTingjiGao();
                }
                if (mapbjcanshu.get(k).getBaojingGao() != null) {
                    bj_gao = mapbjcanshu.get(k).getBaojingGao();
                }
                if (mapbjcanshu.get(k).getBaojingDi() != null) {
                    bj_di = mapbjcanshu.get(k).getBaojingDi();
                }

                if (tj_gao != 999999 && gykval >= tj_gao) {
                    msg = "停机高报! " + df.format(gykval) + "(当前值) >= " + df.format(tj_gao) + "(设定值)";
                    flag = "BG";
                }
                if (tj_di != -999999 && gykval <= tj_di) {
                    msg = "停机低报! " + df.format(gykval) + "(当前值) <= " + df.format(tj_di) + "(设定值)";
                    flag = "BD";
                }
                if (bj_gao != 999999 && gykval >= bj_gao && gykval < tj_gao) {
                    msg = "警报! " + df.format(gykval) + "(当前值) >= " + df.format(bj_gao) + "(设定值)";
                    flag = "WG";
                }
                if (bj_di != -999999 && gykval <= bj_di && gykval > tj_di) {
                    msg = "警报! " + df.format(gykval) + "(当前值) <= " + df.format(bj_di) + "(设定值)";
                    flag = "WD";
                }


//                List<Map<String, Object>> listMapWarn = new ArrayList<Map<String, Object>>();

                if (msg.length() > 1) {

                    LocalDateTime now = LocalDateTime.now();

                    if (mapbjsj.containsKey(k + flag)) {
                        mapbjsj.get(k + flag).setEndTime(now);
//                        LocalDateTime ls = mapbjsj.get(k+flag).getBeginTime();
//                        tempbj.setBeginTime(ls);
//                        tempbj.setEndTime(now);
                    } else {
                        YasuojiBjSj tempbj = new YasuojiBjSj();
                        tempbj.setBjId(k);
                        tempbj.setCanshuZhi(gykval);
                        tempbj.setBjMs(msg);
                        String staname = mapGykbzToYsjJcxx.get(k).getStationName();
                        tempbj.setStationname(staname);
                        String[] tmpstr = mapGykbzToYsjJcxx.get(k).getJldName().split("\\*");
                        tempbj.setJizuhao(tmpstr[1]);
                        tempbj.setBeginTime(now);
                        tempbj.setEndTime(now);
                        tempbj.setSaveFlag(false);
                        tempbj.setZt("1");    //0为不需要处置，1为未处置，2为已处置

                        mapbjsj.put(k + flag, tempbj);

                        MapWarn.put(staname + " " + tmpstr[1], LocalDateTime.now());
                    }

                }
            }
            item.setZt(flag + item.getVal());
        }

//        LocalDateTime now =LocalDateTime.now();
//        int second = now.getSecond();
//
//        if (second % 60 < 2) {
//            mapbjsj.forEach((k,v)->{
//                log.info("key:"+k+" v1:"+v.getBeginTime()+" v2:"+v.getEndTime()+" v3:"+v.getBjMs());
//            });
//            log.info("**************************************");
//        }

        Iterator<Map.Entry<String, LocalDateTime>> iter = MapWarn.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, LocalDateTime> entry = iter.next();
            LocalDateTime tmpsj = entry.getValue();
            long betweenHours = ChronoUnit.HOURS.between(tmpsj, LocalDateTime.now());
            if (betweenHours > 1) {
                iter.remove();
            }
        }

        mapyasuojisssj = Ysjsssj.stream().collect(Collectors.toMap(YasuojiSssj::getGykbz, t -> t));
    }

    /**
     * 计量点基础信息列表中能管中心数据信息读取
     * 6是工业库设置计量点中能管的类别
     * jiang
     * 20231106
     * @return List<Jlddata> jlddata
     */
    public static List<NgSssj> AllNgzxlist() throws InterruptedException {

        String format = getStrCurrentTime();
        //获取166.13数据库中的工业库id
        List<CxcSssjSzJldxx> listAllNg = judge.getJldXxService.getAllJldxx("6");
        //把取到的值存到实体类中
        List<NgSssj> ngdata = new ArrayList<>();
        listAllNg.forEach(item -> {
            NgSssj jldDataTemp = new NgSssj();
            jldDataTemp.setJldName(item.getJldName().replace("_", "-"));
            jldDataTemp.setStationId(item.getStationId());
            jldDataTemp.setZhanName(item.getStationName());
            jldDataTemp.setGykbz(item.getGykbz());
            jldDataTemp.setAcquisitionTime(format);
            ngdata.add(jldDataTemp);
        });
        //工业库中根据gykbz获取相关数据
        Map GykDataList = KDBClient.MapJldData();
        ngdata.forEach(item -> {
            String[] gykbz;
            double[] gykValue;
            try {
                gykbz = item.getGykbz().split(",");
                gykValue = new double[gykbz.length];
                for (int i = 0; i < gykbz.length; i++) {
                    gykValue[i] = 0.0;
                    gykValue[i] = Double.parseDouble(GykDataList.get(Integer.parseInt(gykbz[i])).toString());
                }
                //保留小数点后四位
                item.setVal(String.format("%.4f", gykValue[0]));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //存到map中
        mapNgSssj = ngdata.stream().collect(Collectors.toMap(NgSssj::getGykbz, t -> t));
        return (ngdata);
    }

    /**
     * 保存能管中心数据到13数据库
     * jiang
     * 20231107
     * @throws InterruptedException
     */
    public static void saveNgzxSssj() throws InterruptedException {

        List<NgSssj> saveNgzxSj = AllNgzxlist() ;
        try {
            if (saveNgzxSj.size() > 0) {
                // todo 批量写入会报错
                // ; bad SQL grammar []; nested exception is java.sql.BatchUpdateException: Table 'jeecg-boot-cxc.cxc_sssj_ngzx' doesn't exist
                // judge.ingzxLssjService.saveBatch(saveNgzxSj);
                saveNgzxSj.forEach(item -> {
                    NgSssj ngSssj = new NgSssj();
                    ngSssj.setVal(item.getVal());
                    ngSssj.setZt(item.getZt());
                    ngSssj.setGykbz(item.getGykbz());
                    ngSssj.setZhanName(item.getZhanName());
                    ngSssj.setStationId(item.getStationId());
                    ngSssj.setJldName(item.getJldName());
                    ngSssj.setAcquisitionTime(item.getAcquisitionTime());
                    //保存到数据库中
//                    judge.ingzxLssjService.save(ngSssj);
                });
                log.info(sssjTools.getStrCurrentTime() + "-----保存能管中心数据" + saveNgzxSj.size() + "条成功");
            }else{
                log.info(sssjTools.getStrCurrentTime() + "-----能管中心数据未能保存！");
            }
        } catch (Exception e) {
            log.error("hi:" + e);
        }
    }
    /* 将saveBj多线程中获取的所有报警信息存入历史数据库中 */
    public static void saveBjls(List<CxcSssjLssjBjlsjl> bjlsList) {
            judge.saveBjlsService.saveBatch(bjlsList);
    }

    public static List<YasuojiSj> saveYasuojiSssj() {
        ysjGykbz = judge.getJldXxService.getYsjGykbz("4");
        DecimalFormat df = new DecimalFormat("0.00");

        List<YasuojiSj> listyasuojisj = new ArrayList<>();
        List<YasuojiSj> saveyasuojisj = new ArrayList<>();

        ysjGykbz.forEach(item -> {
            String[] split = item.getJldName().split("\\*");

            if (split[0].equals("ys")) {
                YasuojiSj yasuojiSj = new YasuojiSj();
//                log.info("depa:"+item.getDepartName()+" xh:"+item.getSsgx1());
                yasuojiSj.setDepartName(item.getDepartName());
                yasuojiSj.setStationName(item.getStationName());
                yasuojiSj.setGykbz(item.getGykbz());
                yasuojiSj.setJizuHao(split[1]);
                yasuojiSj.setYsjxh(item.getSsgx1());
                yasuojiSj.setCanshu(split[2]);

                listyasuojisj.add(yasuojiSj);
            }
        });

        Map<String, List<YasuojiSj>> mapfz;
        mapfz = listyasuojisj.stream().collect(Collectors.groupingBy(obj -> obj.getStationName() + "_" + obj.getJizuHao()));

        if (mapyasuojisssj.size() > 0) {
            mapfz.forEach((k, v) -> {
                YasuojiSj ysjsj = new YasuojiSj();
                StringBuilder shuju = new StringBuilder();
                v.forEach(item -> {
                    shuju.append(item.getGykbz());
                    shuju.append(":");
                    if (mapyasuojisssj.containsKey(item.getGykbz())) {
                        shuju.append(df.format(mapyasuojisssj.get(item.getGykbz()).getVal()));
                    } else {
                        shuju.append("0");
                    }
                    shuju.append(" ");
//                 log.info("depa:"+(v.get(0).getStationName()+" xh:"+mapyasuojisssj.get(item.getGykbz()).getVal()));
                    String tmpstr = item.getCanshu();
                    if (tmpstr.equals("发动机转速")) {
                        float tmpval = mapyasuojisssj.get(item.getGykbz()).getVal();
                        if (tmpval < 1) {
                            MapStop.put(v.get(0).getStationName() + " " + v.get(0).getJizuHao(), tmpval);
                        } else {
                            MapGood.put(v.get(0).getStationName() + " " + v.get(0).getJizuHao(), tmpval);
                        }
//                        log.info("hi:" + item.getJizuHao()+" "+v.get(0).getJizuHao());
                    }
//                    log.info("canshu:"+ tmpstr);
                });
                ysjsj.setId(UUID.randomUUID().toString());
                ysjsj.setDepartName(v.get(0).getDepartName());
                ysjsj.setStationName(v.get(0).getStationName());
                ysjsj.setYsjxh(v.get(0).getYsjxh());
                ysjsj.setJizuHao(v.get(0).getJizuHao());
                LocalDateTime now = LocalDateTime.now();
//            String now1=dateTimeFormatter.format(now);
                ysjsj.setRq(now);
                ysjsj.setShuju(shuju.toString());

                saveyasuojisj.add(ysjsj);

            });
        }
        return saveyasuojisj;

//        try {
//            if (saveyasuojisj.size() > 0) {
//
//                //***************************************     压缩机实时  *********************************************************************
//
//                judge.jldlsMapper.YasuojiSssj(saveyasuojisj);
//                log.info(sssjTools.getStrCurrentTime() + "-----保存压缩机数据" + saveyasuojisj.size() + "条成功");
//
//                //***************************************************************************************
//            }
//        } catch (Exception e) {
//            log.error("hi:" + e);
//        }

    }

    //获取gykbz对应的计量点信息,该方法在savedata中调用，实现只运行一次
    public static void getJldxxKeyGykbz() {
        List<YasuojiJcxx> Gykbz = judge.getJldXxService.getYsjGykbz("1");
        if (Gykbz.size() > 0) {
            Gykbz.forEach(item -> {
                if (item.getGykbz() != null) {
                    List<String> strgykgz = Arrays.asList(item.getGykbz().split(","));
                    strgykgz.forEach(item2 -> {
                        gykbzGetJcxx.put(item2, item);
                    });
                }
            });
        }
//        gykbzGetJcxx.forEach((k,v)->{
//            log.info("gykbz:"+k);
//        });

    }

    //获取当前时区当前日期
    public static String getStrCurrentTime() {
        TimeZone time = TimeZone.getTimeZone("GMT+8"); //设置为东八区
        time = TimeZone.getDefault();// 这个是国际化所用的
        TimeZone.setDefault(time);// 设置时区
        Calendar calendar = Calendar.getInstance();// 获取实例
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//构造格式化模板
        Date date = calendar.getTime(); //获取Date对象
        String str = new String();
        str = format1.format(date);//对象进行格式化，获取字符串格式的输出
        return str;
    }

    //获取当前时区当前日期
    public static Date getDateCurrentTime() {
        TimeZone time = TimeZone.getTimeZone("GMT+8"); //设置为东八区
        time = TimeZone.getDefault();// 这个是国际化所用的
        TimeZone.setDefault(time);// 设置时区
        Calendar calendar = Calendar.getInstance();// 获取实例
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//构造格式化模板
        Date date = calendar.getTime(); //获取Date对象

        return date;
    }

    @PostConstruct
    public void init() {
        judge = this;
        judge.getJldXxService = this.getJldXxService;
        judge.saveJldlsService = this.saveJldlsService;
        judge.rsjService = this.rsjService;
        judge.bjszMapper = this.bjszMapper;
        judge.jldlsMapper = this.jldlsMapper;
        judge.saveBjlsService = this.saveBjlsService;
        judge.getScpzService = this.getScpzService;
        judge.saveSclsService = this.saveSclsService;
        judge.rishujuService = this.rishujuService;
        judge.qijingService = this.qijingService;
    }
    /**
     * 气井数据信息读取
     *
     * @return List<Jlddata> jlddata
     */
//    public static  CxcQijingRB getAllQjData() {
//
////        QueryWrapper queryjh =
//        List<Map<String,Object>> RsjQjlist = judge.qijingService.getYMDataByjh("部10井");
//        for (Map<String,Object>map :RsjQjlist){
//            System.out.println(map.get("qilMData"));
//        }

//        System.out.println(listAllQj);
//        List<CxcQijingRB> qjrbData = new ArrayList<>();
//        listAllQj.forEach(item -> {
//            CxcQijingRB qjDataTemp = new CxcQijingRB();
//            qjDataTemp.setId(item.getId());
//            qjDataTemp.setDepartName(item.getDepartName());
//            qjDataTemp.setStationName(item.getStationName());
//            qjDataTemp.setJh(item.getJh());
//            qjDataTemp.setScsj(item.getScsj());
//            qjrbData.add(qjDataTemp);
//        });


//    return CxcQijingRB;
//    }
}

