using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Metrics;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PrintBarCode.Helper
{
    public class PrintHelper
    {
        private DataTable dt = new DataTable();

        public PrintHelper()
        {
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Value", typeof(string));
            dt.Columns.Add("Size", typeof(string));
        }

        public string GetPrintString(string path, string PrintStr)
        {
            
            string[] array = File.ReadAllLines(path, Encoding.Default);

            int count2 = 0;
            for (int num = array.Length - 1; num >= 0; num--)
            {
                if (array[num].IndexOf("%%") > -1)
                {
                    count2++; // 每找到一个包含“%%”的行，计数器加1
                }
            }


            for (int num = array.Length - 1; num >= 0; num--)
            {
                if (array[num].IndexOf("%%") > -1)
                {
                    string sourse = array[num];
                    string text = MidStrEx_New(sourse, "A0N,", "FH");
                    int fontSize = GetFontSize(text);
                    string text2 = MidStrEx_New(sourse, "FD%%", "FS");
                    string value = "%%" + text2.Split('^')[0];
                    DataRow dataRow = dt.NewRow();
                    dataRow[0] = value;
                    dataRow[1] = text;
                    dataRow[2] = fontSize.ToString();
                    dt.Rows.Add(dataRow);
                }
                else if (array[num].IndexOf("^LL") > -1)
                {
                    break;
                }
            }

            string boxFlie = getBoxFlie(path);
            return replaceGXStr(PrintStr, boxFlie);
        }

        private string MidStrEx_New(string sourse, string startstr, string endstr)
        {
            Regex regex = new Regex("(?<=(" + startstr + "))[.\\s\\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return regex.Match(sourse).Value;
        }

        private int GetFontSize(string hw)
        {
            int result = 9;
            string[] array = hw.Split(',');
            try
            {
                result = (int)(Convert.ToDouble(array[0]) / 2.8 + 0.4);
            }
            catch
            {
            }

            return result;
        }

        private string ConvertImageToCode(Bitmap img)
        {
            StringBuilder stringBuilder = new StringBuilder();
            long num = 0L;
            long num2 = 0L;
            int num3 = 0;
            for (int i = 0; i < img.Size.Height; i++)
            {
                for (int j = 0; j < img.Size.Width; j++)
                {
                    num3 *= 2;
                    string text = ((long)img.GetPixel(j, i).ToArgb()).ToString("X");
                    if (text.Substring(text.Length - 6, 6).CompareTo("BBBBBB") < 0)
                    {
                        num3++;
                    }

                    num2++;
                    if (j == img.Size.Width - 1 && num2 < 8)
                    {
                        stringBuilder.Append((num3 * (2 ^ (8 - (int)num2))).ToString("X").PadLeft(2, '0'));
                        num3 = 0;
                        num2 = 0L;
                    }

                    if (num2 >= 8)
                    {
                        stringBuilder.Append(num3.ToString("X").PadLeft(2, '0'));
                        num3 = 0;
                        num2 = 0L;
                    }
                }

                stringBuilder.Append(Environment.NewLine);
            }

            return stringBuilder.ToString();
        }

        private Bitmap CreateImage(string data, Font f)
        {
            if (string.IsNullOrEmpty(data))
            {
                return null;
            }

            TextBox textBox = new TextBox();
            textBox.Text = data;
            textBox.Font = f;
            Bitmap bitmap = new Bitmap(textBox.PreferredSize.Width, (textBox.PreferredSize.Height - 5) * textBox.Lines.Length + 5);
            Graphics graphics = Graphics.FromImage(bitmap);
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Black, Color.Black, 1.2f, isAngleScaleable: true);
            graphics.Clear(Color.White);
            graphics.DrawString(data, f, brush, 1f, 1f);
            return bitmap;
        }

        private string ZPLStr(string data, string name, float Size = 9f)
        {
            if(Size <=15f)
            {
                Size = 15f;
            }
            Bitmap bitmap = CreateImage(data, new Font("黑体", Size, FontStyle.Bold));
            string text = ((bitmap.Size.Width / 8 + ((bitmap.Size.Width % 8 != 0) ? 1 : 0)) * bitmap.Size.Height).ToString();
            string text2 = (bitmap.Size.Width / 8 + ((bitmap.Size.Width % 8 != 0) ? 1 : 0)).ToString();
            string text3 = ConvertImageToCode(bitmap);
            return $"~DGR:{name}.GRF,{text},{text2},{text3}";
        }

        private bool HasChinese(string str)
        {
            return Regex.IsMatch(str, "[\\u4e00-\\u9fa5]");
        }

        private string replaceGXStr(string list, string boxStr)
        {
            string text = boxStr;
            string[] array = list.Split('~');
            if (!HasChinese(list))
            {
                for (int num = array.Length; num >= 1; num--)
                {
                    text = text.Replace("%%" + num, array[num - 1]);
                }
            }
            else
            {
                for (int num2 = array.Length; num2 >= 1; num2--)
                {
                    string text2 = array[num2 - 1];
                    if (HasChinese(text2))
                    {
                        float size = Convert.ToInt16(dt.Select("Name = '%%" + num2 + "'")[0]["Size"].ToString());
                        string text3 = ZPLStr(text2, num2.ToString(), size);
                        text = text.Replace("^LS0", "^LS0\r\n" + text3);
                        text = text.Replace("FD%%" + num2, "XGR:" + num2 + ".GRF");
                        text = text.Replace("FD##" + num2, "XGR:" + num2 + ".GRF");
                        text = text + "\r\n^XA^ID" + num2 + ".GRF^FS^XZ";
                    }
                    else
                    {
                        text = text.Replace("%%" + num2, array[num2 - 1]);
                    }
                }
            }

            return text;
        }

        private string getBoxFlie(string _path)
        {
            FileStream fileStream = new FileStream(_path, FileMode.Open);
            fileStream.Seek(0L, SeekOrigin.Begin);
            BinaryReader binaryReader = new BinaryReader(fileStream, Encoding.Default);
            byte[] array = new byte[fileStream.Length];
            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
            string text = "";
            array = binaryReader.ReadBytes(array.Length);
            text = Encoding.Default.GetString(array);
            fileStream.Close();
            binaryReader.Close();
            return text;
        }
    }
}
