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 DataCheckFilter2012 implements DataFilter {
    @Override
    public boolean filter(byte[] byteBuff, int pos, int length, DataStreamAdapter dataStreamAdapter, Object template) {

        String logId = LogHelper.createLogId(dataStreamAdapter.getAdapterKey() + " DataCheckFilter2012");
        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[] crc = new byte[1];
            crc[0] = BytesUtil.GetCRCByte(BytesUtil.subBytes(datagramBuff, 3, datagramBuff.length - 5));
            byte[] baowenCrc = BytesUtil.subBytes(byteBuff, datagramBuff.length - 2, 1);
            String crcInfo = "报文中 CRC=" + BytesUtil.byte2HexStr(baowenCrc) + " 计算的 CRC=" + BytesUtil.byte2HexStr(crc);
            if (crc[0] == baowenCrc[0]) {
                LogHelper.info(logId + " 校验成功：" + crcInfo);
                return true;
            } else {
                LogHelper.info(logId + " 校验错误：" + crcInfo);
                String rtuCode = datagram.substring(8, 8 + 10);
              //  DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(checkTime, GBConstants.AGREEMENT_KIND_SZY, rtuCode, GBConstants.WARNING_TYPE_CRC_ERROR, datagram, "校验错误：" + crcInfo);
            }
        } catch (Exception e) {
            LogHelper.error(e);
        } finally {
            LogHelper.info(logId + " 过滤器处理完成");
        }
        return false;
    }
}
