package com.mvc.service;


import com.mvc.entity.TAiread;
import com.mvc.entity.TPackLog;
import com.mvc.model.*;
import com.mvc.model.upgrade.TUpgradeResultsModel;
import com.mvc.netty.MessageParser;
import com.mvc.netty.ParserFactory;
import com.mvc.netty.dealconstant.HandleMsgCode;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.netty.serveriden.ServerParse;
import com.mvc.service.aiiden.AiIdenTask;
import com.mvc.service.app.TAppComlogService;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.copy.TPackLogService;
import com.mvc.service.taizhang.DeviceAccService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.service.taizhang.TAicnnService;
import com.mvc.service.taizhang.TTaskDownService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.FileUtil;
import com.mvc.utils.NumberUtil;
import com.mvc.utils.StoreBlockingQueue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ScheduleService {

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

    @Autowired
    private TPackLogService tPackLogService;

    @Resource
    private ParserFactory parserFactory;

    @Autowired
    private TAireadService tAireadService;

    @Autowired
    private StationAccService stationAccService;

    @Resource
    private Environment env;

    @Autowired
    private TTaskDownService tTaskDownService;

    @Autowired
    private TAppComlogService tAppComlogService;

    @Autowired
    private TAicnnService tAicnnService;

    @Autowired
    private ServerParse serverParse;

    @Resource
    private DeviceAccService deviceAccService;

    public void handleMsg() {
        List<TPackLog> packageList = tPackLogService.selectUnParse();
        if (!packageList.isEmpty()) {
            log.info("-----处理报文-----");
            for (TPackLog tPackage : packageList) {
                MessageParser messageParser = parserFactory.getInstance(HandleMsgCode.get(tPackage.getFunCode()));
                if (messageParser == null) {
                    continue;
                }
                // 解析报文
                List<TAiread> handleList = new ArrayList<>();
                Object data = messageParser.parse(tPackage, "S");
                if (data != null) {
                    if (data instanceof TAiread) {
                        handleList.add((TAiread) data);
                    } else if (data instanceof ArrayList) {
                        handleList.addAll((List<TAiread>) data);
                    }
                }
                // 处理数据
                if (!handleList.isEmpty()) {
                    for (TAiread rawdata : handleList) {
                        if (tAireadService.countHasRepeatrRecord(rawdata) == 0) {
                            tAireadService.addTAiread(rawdata);
                        }

                    }
                }
            }
        } else {
            return;
        }
        List<TPackLog> completeList = new ArrayList<>();
        List<TPackLog> errorList = new ArrayList<>();
        for (TPackLog tPackage : packageList) {
            if (tPackage.getFlag() == null || tPackage.getFlag().equals("1")) {
                tPackage.setFlag("1");
                tPackLogService.updateTPackLog(tPackage);
            } else if (tPackage.getFlag().equals("2")) {
                tPackLogService.updateTPackLog(tPackage);
            }
        }
    }

    public void handleMsg_datu() {
        //List<String> codeList = tPackLogService.selectDistinctUnParsecode_DT("10");       //下面改为用组查包  2022-07-14 guozhao
        List<String> gidList = tPackLogService.selectDistinctUnParsecode_PackGid_DT("10");
        Date nowdate = new Date();
        for (int i = 0; i < gidList.size(); i++) {
            //String stationcode = gidList.get(i);
            //List<TPackLog> tPackages = tPackLogService.selectUnParse_DT(stationcode);
            String packGid = gidList.get(i);
            List<TPackLog> tPackages = tPackLogService.selectUnParse_ByGid(packGid, "10");
            if (tPackages.size() > 0) {
                TPackLog tPackage_1 = tPackages.get(0);
                Integer baonum = tPackage_1.getPackCount();
                Integer baoindex = tPackage_1.getPackIndex();
                if (baonum != null && tPackages.size() >= baonum && baonum > 0) {
                    TPackLog lastpackage = tPackages.get(baonum - 1);
                    if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 200) {
                        //开始组包
                        StringBuffer imagebuffer = new StringBuffer();
                        TAiread trrawdata = new TAiread();
                        trrawdata.setAireadId(tPackage_1.getPackId());
                        trrawdata.setSampleTime(tPackage_1.getDatatime());
                        trrawdata.setRptTime(tPackage_1.getRptTime());
                        trrawdata.setRevTime(tPackage_1.getRevTime());
                        trrawdata.setStationCode(tPackage_1.getStationCode());
                        trrawdata.setFunCode(tPackage_1.getFunCode());
                        String baseImagePath = env.getProperty(ResourceTag.ResourceUrlTag.getTag()) + ResourcePath.Image.getPath() + ResourcePath.Rawdata.getPath();
                        String writepath = env.getProperty(ResourceTag.UploadPathTag.getTag()) + ResourcePath.Rawdata.getPath();
                        baseImagePath += DateUtil.formateDate(trrawdata.getSampleTime(), "yyyy-MM") + "/";
                        writepath += DateUtil.formateDate(trrawdata.getSampleTime(), "yyyy-MM") + "/";
                        trrawdata.setBigJpgUrl(baseImagePath);
                        trrawdata.setBigJpgPackGid(tPackage_1.getPackGid());
                        imagebuffer.append(tPackage_1.getMessage());
                        tPackage_1.setFlag("11");
                        //tPackage_1.setPackGid(tPackage_1.getPackId());
                        for (int j = 1; j < baonum; j++) {
                            TPackLog tt = tPackages.get(j);
                            imagebuffer.append(tt.getMessage());
                            tt.setFlag("11");
                            //tt.setPackGid(tPackage_1.getPackId());
                        }

                        String deviceSn = trrawdata.getDeviceSn();
                        String nowtime = DateUtil.formateDate(new Date(), "yyyyMMddHHmmss");
                        String bigUrl = trrawdata.getBigJpgUrl();
                        String filename = deviceSn + "_" + nowtime + "_B.jpg";

                        //找到对应的小图，设定bigurl,待优化
                        TAireadModel smallriead = tAireadService.findTairedBySnAndTime(trrawdata.getStationCode(), trrawdata.getSampleTime(), 1);
                        if (smallriead != null) {
                            deviceSn = smallriead.getDeviceSn();              //大图没有SN,从小图对象中获取
                            filename = deviceSn + "_" + nowtime + "_B.jpg";
                            bigUrl = bigUrl + filename;
                            smallriead.setBigJpgUrl(bigUrl);
                            smallriead.setBigJpgPackGid(trrawdata.getBigJpgPackGid());
                            tAireadService.updateTAiread(smallriead);
                        } else {
                            //防止先解析大图,deviceSn==null 2022-07-09 guozhao
                            //注释掉了,如果只有大图的情况下,会从站点台账中匹配SN,但台账往往更新不及时,导致SN错误,会让人误解 2023-08-22 guozhao
                            /*StationAccModel stationAccModel = stationAccService.findStationAccByStationCode(trrawdata.getStationCode());
                            if (stationAccModel != null) {
                                deviceSn = stationAccModel.getDeviceSn();
                                trrawdata.setDeviceSn(deviceSn);
                            }*/
                            //如果还没有登记上遥测站台账,deviceSn取不到可能会导致文件名重复,文件会被覆盖,前台会年到大中图不一是个表 2022-07-19 guozhao
                            if (StringUtils.isEmpty(deviceSn)) {
                                deviceSn = "D" + trrawdata.getStationCode();
                            }
                            filename = deviceSn + "_" + nowtime + "_B.jpg";
                            bigUrl = bigUrl + filename;
                            trrawdata.setBigJpgUrl(bigUrl);
                            //没有找到匹配的小图 2022-07-02 guozhao
                            tAireadService.addTAiread(trrawdata);
                        }

                        //存储图片
                        byte[] byteAll = NumberUtil.hexStringToBytes(imagebuffer.toString());
                        try {
                            FileUtil.writeBytesFile(writepath, filename, byteAll);
                            //trrawdata.setBigJpgUrl(trrawdata.getBigJpgUrl()+filename);
                        } catch (IOException e) {
                            e.printStackTrace();
                            log.error("图片文件保存失败---" + trrawdata.getAireadId());
                        }

                        //跟新 tpackage标志
                        for (int k = 0; k < baonum; k++) {
                            tPackLogService.updateTPackLog(tPackages.get(k));
                        }
                    } else {
                        for (int k = 0; k < tPackages.size(); k++) {
                            TPackLog tt = tPackages.get(k);
                            tt.setFlag("12");
                            tPackLogService.updateTPackLog(tPackages.get(k));
                        }
                    }
                } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
                    TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
                    if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                        for (int k = 0; k < tPackages.size(); k++) {
                            TPackLog tt = tPackages.get(k);
                            tt.setFlag("12");
                            tPackLogService.updateTPackLog(tt);
                        }
                    }
                }
            }
        }

    }

    public void handleMsg_datuBypages(List<TPackLog> tPackages, String randomCode) {
        try {

            Date nowdate = new Date();
            TPackLog tPackage_1 = tPackages.get(0);
            Integer baonum = tPackage_1.getPackCount();
            Integer baoindex = tPackage_1.getPackIndex();
            if (baonum != null && tPackages.size() >= baonum && baonum > 0) {
                TPackLog lastpackage = tPackages.get(baonum - 1);
                //改为< 1000 (相当于去年此限制,此判断不合理,会正确的数据不解析) 2024-06-03 guozhao
                if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 1000) {
                    //开始组包
                    StringBuffer imagebuffer = new StringBuffer();
                    TAiread trrawdata = new TAiread();
                    trrawdata.setAireadId(tPackage_1.getPackId());
                    trrawdata.setSampleTime(tPackage_1.getDatatime());
                    trrawdata.setRptTime(tPackage_1.getRptTime());
                    trrawdata.setRevTime(tPackage_1.getRevTime());
                    trrawdata.setRandomCode(randomCode);
                    trrawdata.setStationCode(tPackage_1.getStationCode());
                    trrawdata.setFunCode(tPackage_1.getFunCode());
                    String baseImagePath = env.getProperty(ResourceTag.ResourceUrlTag.getTag()) + ResourcePath.Image.getPath() + ResourcePath.Rawdata.getPath();
                    String writepath = env.getProperty(ResourceTag.UploadPathTag.getTag()) + ResourcePath.Rawdata.getPath();
                    baseImagePath += DateUtil.formateDate(trrawdata.getSampleTime(), "yyyy-MM") + "/" + trrawdata.getStationCode() + "/";
                    writepath += DateUtil.formateDate(trrawdata.getSampleTime(), "yyyy-MM") + "/" + trrawdata.getStationCode() + "/";
                    trrawdata.setBigJpgUrl(baseImagePath);
                    trrawdata.setBigJpgPackGid(tPackage_1.getPackId());
                    imagebuffer.append(tPackage_1.getMessage());
                    tPackage_1.setFlag("11");

                    //读数表存储报文中的设备类型 2022-09-15 guozhao
                    if (StringUtils.isNotEmpty(tPackage_1.getRptPwd())) {
                        String devType = StringUtils.isNotEmpty(tPackage_1.getRptPwd()) && tPackage_1.getRptPwd().substring(0, 2).equals("21") ? "2" : "1";
                        trrawdata.setDeviceType(devType);
                    }

                    //tPackage_1.setPackGid(tPackage_1.getPackId());
                    for (int j = 1; j < baonum; j++) {
                        TPackLog tt = tPackages.get(j);
                        imagebuffer.append(tt.getMessage());
                        tt.setFlag("11");
                        //tt.setPackGid(tPackage_1.getPackId());
                    }

                    String deviceSn = trrawdata.getDeviceSn();
                    String nowtime = DateUtil.formateDate(new Date(), "yyyyMMddHHmmss");
                    String bigUrl = trrawdata.getBigJpgUrl();
                    String filename = deviceSn + "_" + nowtime + "_B.jpg";

                    StationAccModel stationAccModel = stationAccService.findStationAccByStationCode(trrawdata.getStationCode());
                    //找到对应的小图，设定bigurl,待优化
                    TAireadModel smallriead = tAireadService.findTairedBySnAndTime(trrawdata.getStationCode(), trrawdata.getSampleTime(), 1);
                    //如果是月末最后一天，数据库大图路径存储水印大图
                    boolean lastdayofmonth = false;
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    int getDay = calendar.get(Calendar.DAY_OF_MONTH);
                    if (getDay == calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) {//是月末最后一天
                        lastdayofmonth = true;
                    }
                    TAireadModel resModel = null;
                    if (smallriead != null) {
                        deviceSn = smallriead.getDeviceSn();              //大图没有SN,从小图对象中获取
                        filename = deviceSn + "_" + nowtime + "_B.jpg";
                        if (lastdayofmonth && stationAccModel != null) {//月末最后一天,数据库存储带水印大图(添加accModel判断,不然与存储图片加水印逻辑不一致 2023-10-31 guozhao)
                            bigUrl = bigUrl + filename.substring(0, filename.indexOf(".jpg")) + "SY.jpg";
                        } else {
                            bigUrl = bigUrl + filename;
                        }
                        smallriead.setBigJpgUrl(bigUrl);
                        smallriead.setBigJpgPackGid(trrawdata.getBigJpgPackGid());
                        resModel = tAireadService.updateTAiread(smallriead);
                    } else {
                        //防止先解析大图,deviceSn==null 2022-07-09 guozhao
                        //注释掉了,如果只有大图的情况下,会从站点台账中匹配SN,但台账往往更新不及时,导致SN错误,会让人误解 2023-08-22 guozhao
                    /*if (stationAccModel != null) {
                        deviceSn = stationAccModel.getDeviceSn();
                        trrawdata.setDeviceSn(deviceSn);
                    }*/
                        //如果还没有登记上遥测站台账,deviceSn取不到可能会导致文件名重复,文件会被覆盖,前台会年到大中图不一是个表 2022-07-19 guozhao
                        if (StringUtils.isEmpty(deviceSn)) {
                            deviceSn = "D" + trrawdata.getStationCode();
                        }
                        filename = deviceSn + "_" + nowtime + "_B.jpg";
                        if (lastdayofmonth && stationAccModel != null) {//月末最后一天,数据库存储带水印大图(添加accModel判断,不然与存储图片加水印逻辑不一致 2023-10-31 guozhao)
                            bigUrl = bigUrl + filename.substring(0, filename.indexOf(".jpg")) + "SY.jpg";
                        } else {
                            bigUrl = bigUrl + filename;
                        }
                        trrawdata.setBigJpgUrl(bigUrl);
                        //没有找到匹配的小图 2022-07-02 guozhao
                        TAiread airead = tAireadService.addTAiread(trrawdata);
                        if (airead != null) {
                            if (resModel == null) {
                                resModel = new TAireadModel();
                            }
                            BeanUtils.copyProperties(airead, resModel);
                        }
                    }
                    if (resModel != null) {//兼容纯服务侧识别 2023-11-08 guozhao
                        //改为全部调一次服务器识别(不然一会这个没有服务侧值,一会那个没有服务侧值) 2024-03-04 guozhao
                        try {
                            StoreBlockingQueue.tAireadQueue.put(resModel);
                        } catch (Exception ex) {

                        }
                    /*try {
                        DeviceAccModel accModel = deviceAccService.findDeviceAccBysn(resModel.getDeviceSn());
                        if (accModel != null && accModel.getDeviceType().equals("3")) {
                            StoreBlockingQueue.tAireadQueue.put(resModel);
                        }
                    } catch (Exception ex) {
                        log.error(ex.getMessage());
                    }*/
                    }
                    //存储图片
                    byte[] byteAll = NumberUtil.hexStringToBytes(imagebuffer.toString());
                    try {
                        if (byteAll != null) {
                            FileUtil.writeBytesFile(writepath, filename, byteAll);
                            //存储一遍带有水印的大图图片
                            if (stationAccModel != null && lastdayofmonth) {
                                String filename2 = writepath + filename.substring(0, filename.indexOf(".jpg")) + "SY.jpg";
                                //ByteArrayInputStream in= new ByteArrayInputStream(byteAll);
                                File file = new File(writepath + filename);
                                BufferedImage image = ImageIO.read(file);
                                // 创建画笔
                                Graphics2D pen = image.createGraphics();
                                // 设置画笔颜色为白色
                                pen.setColor(Color.red);
                                //  pen.setColor(new Color(179, 250, 233, 200));
                                //设置画笔字体样式为微软雅黑，加粗，文字大小为15px
                                pen.setFont(new Font("微软雅黑", Font.BOLD, 15));
                                // 写上水印文字和坐标
                                String sampleDate = DateUtil.formateDate(trrawdata.getSampleTime(), "yyyy-MM-dd HH:mm");
                                pen.drawString(stationAccModel.getStationCode(), 10, 170);
                                pen.drawString(stationAccModel.getStationName(), 10, 190);
                                pen.drawString(sampleDate, 10, 210);//采样时间 2022-10-31 guozhao
                                // 创建新图片文件
                                // 将处理好的图片数据写入到新图片文件中
                                FileOutputStream fos = new FileOutputStream(filename2);
                                ImageIO.write(image, "jpg", fos);
                                fos.flush();
                                fos.close();
                            }
                        } else {
                            log.error("图片文件为空---" + trrawdata.getAireadId());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error("图片文件保存失败---" + trrawdata.getAireadId());
                    }

                    //跟新 tpackage标志
                    for (int k = 0; k < baonum; k++) {
                        tPackLogService.updateTPackLog(tPackages.get(k));
                    }
                } else {
                    for (int k = 0; k < tPackages.size(); k++) {
                        TPackLog tt = tPackages.get(k);
                        tt.setFlag("12");
                        tPackLogService.updateTPackLog(tPackages.get(k));
                    }
                }
            } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
                TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
                if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                    for (int k = 0; k < tPackages.size(); k++) {
                        TPackLog tt = tPackages.get(k);
                        tt.setFlag("12");
                        tPackLogService.updateTPackLog(tt);
                    }
                }
            }
        } catch (Exception e) {
            log.error("handleMsg_datuBypages:" + e.getMessage(), e);
        }
    }

    //处理定时包多包方法(添加最后一包的接收时间)
    public void handleMsg_duobaoBypackages(List<TPackLog> tPackages, String randomCode) {
        try {
            Date nowdate = new Date();
            TPackLog tPackage_1 = tPackages.get(0);
            Integer baonum = tPackage_1.getPackCount();
            Integer baoindex = tPackage_1.getPackIndex();
            if (baonum != null && tPackages.size() >= baonum && baonum > 0) {  //
                TPackLog lastpackage = tPackages.get(baonum - 1);
                //if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 120) {
                if (baoindex == 1 && (lastpackage.getPackIndex() == baonum)) {
                    if (DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) > 180) {//此条件从上级移过来的,做日志观察
                        String info = "解析异常:[" + tPackage_1.getStationCode() + "],首尾包间隔超过180秒[";
                        info += DateUtil.formateDate(tPackage_1.getRevTime(), "yyyy-MM-dd HH:mm:ss]");
                        info += DateUtil.formateDate(lastpackage.getRevTime(), "-[yyyy-MM-dd HH:mm:ss]");
                        log.info(info);
                    }

                    TAiread trrawdata = null;
                    //开始组包
                    if (tPackage_1.getRptPwd().startsWith("70")) {//片段式图片 2023-01-13 guozhao
                        trrawdata = serverParse.parsePart(tPackages);
                    } else {
                        StringBuffer imagebuffer = new StringBuffer();
                        imagebuffer.append(tPackage_1.getMessage());
                        tPackage_1.setFlag("21");
                        for (int j = 1; j < baonum; j++) {
                            TPackLog tt = tPackages.get(j);
                            imagebuffer.append(tt.getMessage());
                            tt.setFlag("21");
                        }
                        tPackage_1.setMessage(imagebuffer.toString());

                        MessageParser messageParser = parserFactory.getInstance(HandleMsgCode.get(tPackage_1.getFunCode()));
                        trrawdata = (TAiread) messageParser.parse(tPackage_1, "M");
                    }

                    //读数表存储报文中的设备类型 2022-09-15 guozhao
                    if (StringUtils.isNotEmpty(tPackage_1.getRptPwd())) {
                        String devType = StringUtils.isNotEmpty(tPackage_1.getRptPwd()) && tPackage_1.getRptPwd().substring(0, 2).equals("21") ? "2" : "1";
                        trrawdata.setDeviceType(devType);
                    }
                    trrawdata.setRevTime(tPackage_1.getRevTime());
                    trrawdata.setRandomCode(randomCode);
                    //保存rawdata
                    TAiread entity = tAireadService.addTAiread(trrawdata);
                    if (entity != null) {
                        //收到中图后,如果没有该设备的配置或配置中sn和stationcode不匹配,自动创建召测任务(会判断是否已经有任务) 2022-09-05 guozhao
                        tTaskDownService.generateTaskDownByDeviceSnAndStationCode(entity.getDeviceSn(), entity.getStationCode());
                    }
                    //{ //全部都走一遍服务器侧识别 2022-07-10 guozhao
                    TAireadModel tAireadModel = new TAireadModel();
                    BeanUtils.copyProperties(entity, tAireadModel);
                    try {
                        //if (!tAireadModel.getDeviceType().equals("2")) {       //压力表不进行服务识别 2022-09-14 guozhao
                        DeviceAccModel accModel = deviceAccService.findDeviceAccBysn(tAireadModel.getDeviceSn());
                        if (accModel != null && accModel.getDeviceType().equals("9")) {//服务侧识别设备调用大模型 2023-11-09 guozhao
                            StoreBlockingQueue.tAireadQueue.put(tAireadModel);
                        } else {
                            StoreBlockingQueue.tAireadQueue.put(tAireadModel);       //服务侧已经加入压力表和LED表的识别 2023-07-01 guozhao
                        }

                        //加入转发或其它处理队列 2024-06-12 guozhao
                        StoreBlockingQueue.forwarderQueue.put(tAireadModel);
                        //}
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //}

                    //跟新 tpackage标志
                    for (int k = 0; k < baonum; k++) {
                        tPackLogService.updateTPackLog(tPackages.get(k));
                    }
                } else {
                    for (int k = 0; k < tPackages.size(); k++) {
                        TPackLog tt = tPackages.get(k);
                        tt.setFlag("22");
                        tPackLogService.updateTPackLog(tt);
                    }
                }
            } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
                TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
                if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                    for (int k = 0; k < tPackages.size(); k++) {
                        TPackLog tt = tPackages.get(k);
                        tt.setFlag("22");
                        tPackLogService.updateTPackLog(tt);
                        log.info("解析异常:[" + tPackage_1.getStationCode() + "],超时未收到完整包[" + DateUtil.formateDate(lasttpackage.getRevTime(), "yyyy-MM-dd HH:mm:ss") + "]");
                    }
                }
            }
        } catch (Exception e) {
            log.error("handleMsg_duobaoBypackages:" + e.getMessage(), e);
        }
    }

    //运行日志 2022.10.09 guozhao
    public void handleMsg_runLogsBypages(List<TPackLog> tPackages) throws IOException {
        Date nowdate = new Date();
        TPackLog tPackage_1 = tPackages.get(0);
        Integer baonum = tPackage_1.getPackCount();
        Integer baoindex = tPackage_1.getPackIndex();
        StringBuffer logbuffer = new StringBuffer();
        if (baonum != null && tPackages.size() >= baonum && baonum > 0) {
            TPackLog lastpackage = tPackages.get(baonum - 1);
            if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 200) {
                logbuffer.append(tPackage_1.getMessage());
                tPackage_1.setFlag("1");
                for (int j = 1; j < baonum; j++) {
                    TPackLog tt = tPackages.get(j);
                    logbuffer.append(tt.getMessage());
                    tt.setFlag("1");
                }
            }
        } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
            TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
            if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                for (int k = 0; k < tPackages.size(); k++) {
                    TPackLog tt = tPackages.get(k);
                    tt.setFlag("44");
                    tPackLogService.updateTPackLog(tt);
                    logbuffer.append(tt.getMessage());
                }
            }
        }

        //保存comLog记录
        TAppComlogModel comlogModel = new TAppComlogModel();
        //处理借用的字段,解析日志属性 2022.10.10 guozhao
        String logInfo = tPackage_1.getPackGid();
        if (StringUtils.isNotEmpty(logInfo) && logInfo.length() == 6) {
            comlogModel.setLogFrom(Integer.valueOf(logInfo.substring(0, 2)) + "");
            comlogModel.setMcuLogLevel(Integer.valueOf(logInfo.substring(2, 4)) + "");
            comlogModel.setAiLogLevel(Integer.valueOf(logInfo.substring(4)) + "");
        }
        String fileName = PackLogMana.saveRunLog(logbuffer, tPackage_1.getStationCode(), tPackage_1.getDatatime(), comlogModel.getLogFrom());
        comlogModel.setStationCode(tPackage_1.getStationCode());
        comlogModel.setDeviceSn(tPackage_1.getDeviceSn());
        comlogModel.setSampleTime(tPackage_1.getDatatime());
        comlogModel.setLogType("1");
        comlogModel.setFileName(fileName);

        //处理借用字段,上次错误运行日志的采样时间
        if (StringUtils.isNotEmpty(tPackage_1.getPackId()) && tPackage_1.getPackId().length() == 10) {
            comlogModel.setSampleTime(DateUtil.parseTimeStr(tPackage_1.getPackId(), "yyMMddHHmm"));
        }
        tAppComlogService.saveTAppComlog(comlogModel);
        tPackage_1.setPackId("");//清空借用的
    }

    //cnn网络传输报文 2022.10.09 guozhao
    public void handleMsg_cnnLogsBypages(List<TPackLog> tPackages, String randomCode) throws IOException {
        Date nowdate = new Date();
        TPackLog tPackage_1 = tPackages.get(0);
        Integer baonum = tPackage_1.getPackCount();
        Integer baoindex = tPackage_1.getPackIndex();
        StringBuffer logbuffer = new StringBuffer();
        if (baonum != null && tPackages.size() >= baonum && baonum > 0) {
            TPackLog lastpackage = tPackages.get(baonum - 1);
            if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 200) {
                logbuffer.append(tPackage_1.getMessage());
                tPackage_1.setFlag("1");
                for (int j = 1; j < baonum; j++) {
                    TPackLog tt = tPackages.get(j);
                    logbuffer.append(tt.getMessage());
                    tt.setFlag("1");
                }
            }
        } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
            TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
            if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                for (int k = 0; k < tPackages.size(); k++) {
                    TPackLog tt = tPackages.get(k);
                    tt.setFlag("44");
                    tPackLogService.updateTPackLog(tt);
                    logbuffer.append(tt.getMessage());
                }
            }
        }

        TAicnnModel cnnModel = new TAicnnModel();
        cnnModel.setDeviceSn(tPackage_1.getDeviceSn());
        cnnModel.setStationCode(tPackage_1.getStationCode());
        cnnModel.setSampleTime(tPackage_1.getDatatime());
        cnnModel.setRptTime(tPackage_1.getRptTime());
        cnnModel.setRevTime(tPackage_1.getRevTime());
        cnnModel.setFunCode(tPackage_1.getFunCode());
        cnnModel.setRandomCode(randomCode);
        cnnModel.setTargetsNum(Integer.valueOf(tPackage_1.getPackGid()));
        cnnModel.setZipAfterLen(Integer.valueOf(tPackage_1.getPackId()));
        cnnModel.setIsCompress(tPackage_1.getFileName());

        tAicnnService.saveTAicnn(cnnModel, logbuffer);

        //重置借用字段
        tPackage_1.setPackId("");
        tPackage_1.setPackGid("");
    }

    //处理定时包多包方法
    public void handleMsg_VersionInfo(TPackLog tPackLog) {
        String msg = tPackLog.getMessage();


        TUpgradeResultsModel model = new TUpgradeResultsModel();
    }

    //处理定时包多包方法
    public void handleMsg_duobao() {
        //List<String> codeList = tPackLogService.selectDistinctUnParsecode_DT("20");
        List<String> gidList = tPackLogService.selectDistinctUnParsecode_PackGid_DT("20");
        Date nowdate = new Date();
        for (int i = 0; i < gidList.size(); i++) {
            String packGid = gidList.get(i);
            //List<TPackLog> tPackages = tPackLogService.selectUnParse_duobao(telemetryStationCode);
            List<TPackLog> tPackages = tPackLogService.selectUnParse_ByGid(packGid, "20");
            if (tPackages.size() > 0) {
                TPackLog tPackage_1 = tPackages.get(0);
                Integer baonum = tPackage_1.getPackCount();
                Integer baoindex = tPackage_1.getPackIndex();
                if (baonum != null && tPackages.size() >= baonum && baonum > 0) {  //
                    TPackLog lastpackage = tPackages.get(baonum - 1);
                    if (baoindex == 1 && (lastpackage.getPackIndex() == baonum) && DateUtil.getSencondsbetweenTime(tPackage_1.getRevTime(), lastpackage.getRevTime()) < 120) {
                        //开始组包
                        StringBuffer imagebuffer = new StringBuffer();
                        imagebuffer.append(tPackage_1.getMessage());
                        tPackage_1.setFlag("21");
                        //tPackage_1.setPackGid(tPackage_1.getPackId());
                        for (int j = 1; j < baonum; j++) {
                            TPackLog tt = tPackages.get(j);
                            imagebuffer.append(tt.getMessage());
                            tt.setFlag("21");
                            //tt.setPackGid(tPackage_1.getPackId());
                        }
                        tPackage_1.setMessage(imagebuffer.toString());
                        MessageParser messageParser = parserFactory.getInstance(HandleMsgCode.get(tPackage_1.getFunCode()));
                        TAiread trrawdata = (TAiread) messageParser.parse(tPackage_1, "M");

                        //大中图匹配,由于大中小图定时任务时间间隔较大且相同,可能会出现先有大图的情况 2022-07-07 guozhao
                        TAireadModel bigModel = tAireadService.findTairedBySnAndTime(trrawdata.getStationCode(), trrawdata.getSampleTime(), 2);
                        if (bigModel != null) {
                            trrawdata.setBigJpgUrl(bigModel.getBigJpgUrl());
                            trrawdata.setBigJpgPackGid(bigModel.getBigJpgPackGid());
                            tAireadService.deleteTAiread(bigModel.getId());
                        }
                        trrawdata.setResultValue(trrawdata.getIdentValue());
                        //保存rawdata
                        TAiread entity = tAireadService.addTAiread(trrawdata);

                        //把结果值不准确的加入到服务器侧识别列表中 2022-07-06 guozhao
                        //if (entity.getGoodFlag() != null && entity.getGoodFlag() == "0")
                        //{ //全部都走一遍服务器侧识别 2022-07-10 guozhao
                        TAireadModel tAireadModel = new TAireadModel();
                        BeanUtils.copyProperties(entity, tAireadModel);
                        AiIdenTask.addTAireadModel(tAireadModel);
                        //}

                        //跟新 tpackage标志
                        for (int k = 0; k < baonum; k++) {
                            tPackLogService.updateTPackLog(tPackages.get(k));
                        }
                    } else {
                        for (int k = 0; k < tPackages.size(); k++) {
                            TPackLog tt = tPackages.get(k);
                            tt.setFlag("22");
                            tPackLogService.updateTPackLog(tt);
                        }
                    }
                } else { //不够一整包，判断数据有没有问题，有问题直接标记问题
                    TPackLog lasttpackage = tPackages.get(tPackages.size() - 1);
                    if (DateUtil.getSencondsbetweenTime(lasttpackage.getRevTime(), nowdate) > 600) {//超过10min 还没收到完整包
                        for (int k = 0; k < tPackages.size(); k++) {
                            TPackLog tt = tPackages.get(k);
                            tt.setFlag("22");
                            tPackLogService.updateTPackLog(tt);
                        }
                    }
                }
            }
        }
    }
}
