package  org.ts.ddcs.filter;

import org.ts.ddcs.main.DataProcessHolder;
import org.ts.ddcs.common.constant.GBConstants;
import org.ts.ddcs.dataStream.DataStreamAdapter;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.util.BytesUtil;
;

import java.util.Date;

/**
 * created by swp on 2017/9/15
 *
 * @author dylan
 */
public class DataCheckFilter2014 implements DataFilter {

    @Override
    public boolean filter(byte[] byteBuff, int pos, int length, DataStreamAdapter dataStreamAdapter, Object template) {

        String logId = LogHelper.createLogId(dataStreamAdapter.getAdapterKey() + " DataCheckFilter2014");
        try {
            Date checkTime = new Date();
            byte[] datagramBuff = new byte[length];
            System.arraycopy(byteBuff, pos, datagramBuff, 0, length);
            String datagram = BytesUtil.byte2HexStr(datagramBuff);
            LogHelper.info(logId + " datagram :" + datagram);
            //校验码，取报文最后两个字节
            byte[] PacketCrc16 = new byte[2];
            PacketCrc16[0] = byteBuff[datagramBuff.length - 2];
            PacketCrc16[1] = byteBuff[datagramBuff.length - 1];
            //生成校验码,包体，去掉报文最后两个字节
            byte[] crc16 = BytesUtil.crcFun2014(datagramBuff, 0, byteBuff.length - 2);
            String crcInfo = "报文中 CRC=" + BytesUtil.byte2HexStr(PacketCrc16) + " 计算的 CRC=" + BytesUtil.byte2HexStr(crc16);
            if (BytesUtil.byte2HexStr(PacketCrc16).equals(BytesUtil.byte2HexStr(crc16))) {
                LogHelper.info(logId + " 校验成功：" + crcInfo);
                return true;
            } else {
                LogHelper.info(logId + " 校验错误：" + crcInfo);
                String rtuCode = datagram.substring(6, 6 + 10);
                //DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(checkTime, GBConstants.AGREEMENT_KIND_SW, rtuCode, GBConstants.WARNING_TYPE_CRC_ERROR, datagram, "校验错误：" + crcInfo);
            }
        } catch (Exception e) {
            LogHelper.error(e);
        } finally {
            LogHelper.info(logId + " 过滤器处理完成");
        }
        return false;
    }
}
