using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SlnMesnac.Common
{
    public sealed class InkJetCodeHelper
    {

        #region 单例实现
        private static readonly InkJetCodeHelper lazy = new InkJetCodeHelper();
        public static InkJetCodeHelper Instance
        {
            get
            {
                return lazy;
            }
        }
        #endregion

       

        /// <summary>
        /// 条码转换为待发送字节数组
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public byte[] GetBytesByCommand(string barCode)
        {
            byte[] buffer = null;
            byte[] SOI = new byte[] { 0x7E };
            byte[] OrderID = new byte[] { 0x30, 0x32 };
            byte[] MemoID = new byte[] { 0x30, 0x31 };
            byte[] Info = GetInfoBytes(barCode);
            byte[] Length = GetLengthByte(Info.Length);
            byte[] CheckSum = GetCheckSumBytes(OrderID, MemoID, Info, Length);
            byte[] EOI = new byte[] { 0x0D };

            using (MemoryStream stream = new MemoryStream())
            {
                // 将所有数组依次写入 MemoryStream
                stream.Write(SOI, 0, SOI.Length);
                stream.Write(OrderID, 0, OrderID.Length);
                stream.Write(MemoID, 0, MemoID.Length);
                stream.Write(Length, 0, Length.Length);
                stream.Write(Info, 0, Info.Length);
                stream.Write(CheckSum, 0, CheckSum.Length);
                stream.Write(EOI, 0, EOI.Length);

                // 获取最终的合并后的字节数组
                buffer = stream.ToArray();
            }

            return buffer;

        }


        #region 计算Info数据

        public byte[] GetInfoBytes(string input)
        {
            try
            {
                List<byte> bytes = new List<byte>();

                // X
                bytes.Add(0x30);
                bytes.Add(0x30);
                bytes.Add(0x35);
                bytes.Add(0x38);
                //0
                bytes.Add(0x30);
                bytes.Add(0x30);
                bytes.Add(0x33);
                bytes.Add(0x30);

                foreach (char c in input)
                {
                    byte[] charBytes = ConvertCharToBytes(c);
                    foreach (byte b in charBytes)
                    {
                        bytes.Add(b);
                    }
                }

                // 固定尾部分隔符
                bytes.Add(0x30);
                bytes.Add(0x30);
                bytes.Add(0x31);
                bytes.Add(0x46);

                return bytes.ToArray();
            }
            catch (Exception ex)
            {
                // 处理异常，这里可以根据实际情况处理异常，例如记录日志等
                Console.WriteLine($"Error in GetInfoBytes: {ex.Message}");
                return null;
            }
        }

        // 将字符转换为符合规则的四字节表示
        public byte[] ConvertCharToBytes(char c)
        {
            byte[] result = new byte[4];

            // 获取字符的 ASCII 码
            byte ascii = (byte)c;

            // 高4位的 ASCII 码表示
            byte high4 = (byte)((ascii >> 4) + 0x30);
            // 低4位的 ASCII 码表示
            byte low4 = (byte)((ascii & 0x0F) + 0x30);

            // 构建四字节表示，前两位和后两位
            result[0] = 0x30; // 高位补 '0'
            result[1] = 0x30; // 高位补 '0'
            result[2] = high4;
            result[3] = low4;

            return result;
        }
        #endregion

        #region 计算Length  将十进制数转换为两个字节的 ASCII 表示
        public byte[] GetLengthByte(int dec)
        {
            byte[] result = new byte[4];

            // 将十进制数转换为十六进制字符串
            string hexString = dec.ToString("X4");

            for (int i = 0; i < hexString.Length; i++)
            {
                char c = hexString[i];

                int asciiValue = (int)c;


                result[i] = Convert.ToByte(asciiValue.ToString("X2"), 16);
            }

            return result;
        }
        #endregion

        #region  计算校验码
        public byte[] GetCheckSumBytes(byte[] OrderID, byte[] MemoID, byte[] Info, byte[] Length)
        {
            byte[] result = new byte[4]; // 始终返回四个字节
            // 计算校验和
            ushort checksum = CalculateLCheckSum(OrderID, MemoID, Info, Length);
            string checksumHex = checksum.ToString("X4");
            for (int i = 0; i < checksumHex.Length; i++)
            {
                char c = checksumHex[i];
                // 获取字符 c 的 ASCII 码
                int asciiValue = (int)c;

                // 将 ASCII 码转换成十六进制表示，并存储到 result 数组中
                result[i] = Convert.ToByte(asciiValue.ToString("X2"), 16);
            }
            return result;
        }

        private ushort CalculateLCheckSum(byte[] OrderID, byte[] MemoID, byte[] Info, byte[] Length)
        {
            // 计算除去 SOI、EOI 和 CheckSUM 外的数据的和
            int sum = CalculateSumWithoutCheckSum(OrderID) +
                      CalculateSumWithoutCheckSum(MemoID) +
                      CalculateSumWithoutCheckSum(Info) +
                      CalculateSumWithoutCheckSum(Length);

            // 取模 65536
            ushort modResult = (ushort)(sum % 65536);

            // 求反加1
            ushort checksum = (ushort)(((ushort)~modResult) + 1);

            return checksum;
        }

        private int CalculateSumWithoutCheckSum(byte[] data)
        {
            int sum = 0;
            foreach (byte b in data)
            {
                sum += b;
            }
            return sum;
        }
        #endregion







    }


}
