using Edge.Core.Parser.BinaryParser.MessageEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace HengshanPaymentTerminal.MessageEntity.Incoming
{
    /// <summary>
    /// 油机发送油枪信息数据对象
    /// </summary>
    public class NozzleInfo : CommonMessage
    {
        /// <summary>
        /// 油枪数
        /// </summary>
        public int GunNum { get; set; }

        /// <summary>
        /// 各油枪信息
        /// </summary>
        public List<Nozzle> nozzles { get; set; }
        public class Nozzle
        {
            /// <summary>
            /// 加油点
            /// </summary>
            public int fpoint { get; set; }

            /// <summary>
            /// 内部枪号
            /// </summary>
            public int internalNum { get; set; }

            /// <summary>
            /// 外部枪号
            /// </summary>
            public int externalNum { get; set; }

            /// <summary>
            /// 单价
            /// </summary>
            public decimal price { get; set; }

            /// <summary>
            /// 油品代码
            /// </summary>
            public string oilCode { get; set; }

        }

        public override byte[] ToCommonByteArray()
        {
            byte[] content = new byte[] { 0x55, this.Handle, 0x00, ((byte)RESULT.OVER) };
            return content2data(content);
        }

        public override CommonMessage ToObject(byte[] datas)
        {
            getBaseData(datas);
            this.GunNum = datas[7];
            int index = 8;
            List<Nozzle> nozzles = new List<Nozzle>();
            while (index + 7 <= datas.Length)
            {
                Nozzle nozzle = new Nozzle();
                nozzle.fpoint =  datas[index];
                nozzle.internalNum = datas[index + 1];
                nozzle.externalNum = datas[index + 2];
                Span<byte> priceSpan = datas.AsSpan(index + 3, 2);
                if (BitConverter.IsLittleEndian)
                {
                    priceSpan.Reverse();
                }
                ushort priceShort = MemoryMarshal.Read<ushort>(priceSpan);
                nozzle.price = priceShort / 100;
                nozzle.oilCode = Bcd2Int(datas[index + 5], datas[index+6]).ToString();

                nozzles.Add(nozzle);
                index += 7;
            }
            this.nozzles = nozzles;
            return this;
        }
    }
}
