package com.zd.laboratory.socket.constant;


import com.zd.laboratory.socket.exception.AnalysisException;
import com.zd.laboratory.socket.util.SocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JXCTPacket {
    private static Logger log = LoggerFactory.getLogger(JXCTPacket.class);
    /**
     * 帧头(2) 固定为0xfe 0xdc
     */
    public String header = "FEDC";
    /**
     * 长度(1) 不包含2字节帧头、2字节帧尾的指令长度
     */
    public int length;
    /**
     * 设备 ID(6)  6字节唯一设备ID，第一个字节表示继电器有多少路，如0x10代表16路继电器，0x08表示8路继电器，0x04表示4路继电器
     */
    public String deviceNumber;
    /**
     * 命令字节(1) 功能码
     * 0x01-设备端即时动作
     * 0x02-要求设备端保存的定时指令
     * 0x03-修改设备时间
     * 0x04-继电器属性相关操作
     * 0x05-联动继电器相关操作
     * 0x06-互斥继电器相关操作
     */
    public String order;
    /**
     * 消息体(N)
     */
    public String body;
    /**
     * 校验和(2)
     */
    public String crc;
    /**
     * 包尾(2) 固定为0xac 0xdb
     */
    public String end = "ACDB";

    public JXCTPacket() {

    }

    public JXCTPacket(String data) throws AnalysisException {
        if (data.length() < 28) {
            throw new AnalysisException("内容长度错误");
        }
        int dataLen = data.length();
        end = data.substring(dataLen - 4, dataLen);
        if (!"ACDB".equals(end)) {
            throw new AnalysisException("帧尾错误");
        }
        crc = data.substring(dataLen - 8, dataLen - 4);
        byte[] crcData = SocketUtils.str2byte(data.substring(0, dataLen - 8));
        String dataCrc = SocketUtils.getHexString(SocketUtils.crc16(crcData, crcData.length), 4);
        if (!crc.equals(dataCrc)) {
            //throw new AnalysisException("校验错误 当前：" + crc + " 正确：" + dataCrc);
        }
        header = data.substring(0, 4);
        length = Integer.parseInt(data.substring(4, 6), 16);
        deviceNumber = data.substring(6, 18);
        order = data.substring(18, 20);
        body = data.substring(20, 20 + (length - 9) * 2);

    }

    public String encodeString() {
        length = (deviceNumber + order + body).length() / 2 + 2;
        String sendBody = header + SocketUtils.getHexString(length, 2) + deviceNumber + order + body;
        byte[] crcByte = SocketUtils.str2byte(sendBody);
        String crc = SocketUtils.getHexString(SocketUtils.crc16(crcByte, crcByte.length), 4);
        sendBody += crc + end;
        log.info(deviceNumber + " : " + sendBody + "  order:" + order + "  body:" + body);
        return sendBody;
    }

    public byte[] encode() {
        return SocketUtils.str2byte(encodeString());
    }

    @Override
    public String toString() {
        return "BasePacket{" +
                "header='" + header + '\'' +
                ", length=" + length +
                ", deviceNumber='" + deviceNumber + '\'' +
                ", order='" + order + '\'' +
                ", body='" + body + '\'' +
                ", crc='" + crc + '\'' +
                ", end='" + end + '\'' +
                '}';
    }
}
