using System;
using GPSBusiness.Helper;
namespace GPSBusiness.BBGPSStandard
{
    public class DataHead
    {
        public static int intSerialNo = 0;
        /// <summary>
        /// 获取流水号
        /// </summary>
        /// <returns></returns>
        public int GetSerialNo()
        {
            if (intSerialNo >= 255)
            {
                intSerialNo = 0;
            }
            intSerialNo++;
            return intSerialNo;
        }
        /// <summary>
        /// 消息ID
        /// </summary>
        public UInt16 DataID;
        /// <summary>
        /// 消息体属性
        /// </summary>
        public UInt16 DataAttribute;
        /// <summary>
        /// 终端手机号=centerid+mdtid
        /// </summary>
        public UInt16 CenterID;
        public byte[] MdtID;
        /// <summary>
        /// 消息流水号
        /// </summary>
        public UInt16 DataSerialNo;
        /// <summary>
        /// 消息体
        /// </summary>
        public byte[] DataContent;
        public byte[] GetBytes()
        {
            this.DataAttribute = (UInt16)this.DataContent.Length;
            ByteBuilder bb = new ByteBuilder();
            bb.Append(ByteConvert.ToBytes(this.DataID));
            bb.Append(ByteConvert.ToBytes(this.DataAttribute));
            bb.Append(ByteConvert.ToBytes(this.CenterID));
            bb.Append(this.MdtID);
            bb.Append(ByteConvert.ToBytes(this.DataSerialNo));
            if (this.DataContent.Length > 0)
            {
                bb.Append(this.DataContent);
            }
            byte Crc = ByteConvert.GetCRC(bb.GetBytes(), 0, bb.GetBytes().Length);
            ByteBuilder bb2 = new ByteBuilder();
            bb2.Append(0x7e);
            bb2.Append(bb.GetBytes());
            bb2.Append(Crc);
            bb2.Append(0x7e);
            return bb2.GetBytes();
        }
        public void Frombytes(DataHead model, byte[] buffer)
        {
            model.DataID = ByteConvert.ToUInt16(buffer, 1);
            model.DataAttribute = ByteConvert.ToUInt16(buffer, 3);//buffer.Length - 15
            model.CenterID = ByteConvert.ToUInt16(buffer, 5);
            model.MdtID = ByteConvert.ToBytes(buffer, 7, 4);
            model.DataSerialNo = ByteConvert.ToUInt16(buffer, 11);
            if (buffer.Length > 15)
            {
                //消息体属性 暂定为消息体长度
                model.DataContent = ByteConvert.ToBytes(buffer, 13, this.DataAttribute);
            }
        }
    }
}