package com.mvc.netty;

import com.mvc.entity.TPackLog;
import com.mvc.service.copy.TPackLogService;
import com.mvc.utils.NumberUtil;
import com.mvc.utils.StoreBlockingQueue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class ErrorParseThread implements Runnable {


    @Autowired
    private TPackLogService tPackLogService;

    @Override
    public void run() {
        while (true) {
            try {
                FzBaowenModel take = StoreBlockingQueue.errorQueue.take();
                System.out.println("---------------channel结束解析错误数据---------------");
                TPackLog tPackLog = new TPackLog();

                //有小部分数据是只收到了第一包,因此是带有sn、stationCode这些信息的,不赋值查询不方便 2023-07-03 guozhao
                tPackLog.setDeviceSn(take.getSn());
                tPackLog.setStationCode(take.getStationcode());
                if (take.getHandleMsgCode() != null) {
                    tPackLog.setFunCode(take.getHandleMsgCode().getCode());
                    tPackLog.setFunName(take.getHandleMsgCode().getDesc());
                }

                tPackLog.setRevTime(take.getLastRevTime() == null ? new Date() : take.getLastRevTime());
                tPackLog.setRevTime(new Date());
                if (StringUtils.isNotEmpty(take.getErrorflag()) && take.getErrorflag().equals("1")) {//记录CRC状态 2022-11-09 guozhao
                    tPackLog.setCrcCheckFlag("0");
                }
                tPackLog.setFlag("44");
                tPackLog.setRptLen(take.getTotalmsg().length() / 2);

                List<TPackLog> logs = new ArrayList<>();
                //如果是多条报文,格式一下内容,方便查看 2024-09-14 guozhao
                if (take.getBaowen() != null && take.getBaowen().size() > 1) {
                    tPackLog.setOriginmessage(take.getBaowen().get(0));
                    logs.add(tPackLog);
                    for(int i = 1; i < take.getBaowen().size(); i++){
                        TPackLog tPackLog2 = new TPackLog();
                        tPackLog2.setOriginmessage(take.getBaowen().get(i));
                        logs.add(tPackLog2);
                    }
                }

                //tPackLogService.savePackLog(tPackLog, take.getLastRevTime());
                tPackLogService.savePackLog(logs, take.getLastRevTime());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
